PackageManagerService.java revision f9124ecad9ec20f572df8cdca6f985ef3f97210d
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.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE;
66import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
67import static android.content.pm.PackageManager.MATCH_ENCRYPTION_UNAWARE;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100import android.Manifest;
101import android.annotation.NonNull;
102import android.annotation.Nullable;
103import android.app.ActivityManager;
104import android.app.ActivityManagerNative;
105import android.app.IActivityManager;
106import android.app.admin.DevicePolicyManagerInternal;
107import android.app.admin.IDevicePolicyManager;
108import android.app.backup.IBackupManager;
109import android.content.BroadcastReceiver;
110import android.content.ComponentName;
111import android.content.Context;
112import android.content.IIntentReceiver;
113import android.content.Intent;
114import android.content.IntentFilter;
115import android.content.IntentSender;
116import android.content.IntentSender.SendIntentException;
117import android.content.ServiceConnection;
118import android.content.pm.ActivityInfo;
119import android.content.pm.ApplicationInfo;
120import android.content.pm.AppsQueryHelper;
121import android.content.pm.ComponentInfo;
122import android.content.pm.EphemeralApplicationInfo;
123import android.content.pm.EphemeralResolveInfo;
124import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
125import android.content.pm.FeatureInfo;
126import android.content.pm.IOnPermissionsChangeListener;
127import android.content.pm.IPackageDataObserver;
128import android.content.pm.IPackageDeleteObserver;
129import android.content.pm.IPackageDeleteObserver2;
130import android.content.pm.IPackageInstallObserver2;
131import android.content.pm.IPackageInstaller;
132import android.content.pm.IPackageManager;
133import android.content.pm.IPackageMoveObserver;
134import android.content.pm.IPackageStatsObserver;
135import android.content.pm.InstrumentationInfo;
136import android.content.pm.IntentFilterVerificationInfo;
137import android.content.pm.KeySet;
138import android.content.pm.PackageCleanItem;
139import android.content.pm.PackageInfo;
140import android.content.pm.PackageInfoLite;
141import android.content.pm.PackageInstaller;
142import android.content.pm.PackageManager;
143import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
144import android.content.pm.PackageManagerInternal;
145import android.content.pm.PackageParser;
146import android.content.pm.PackageParser.ActivityIntentInfo;
147import android.content.pm.PackageParser.PackageLite;
148import android.content.pm.PackageParser.PackageParserException;
149import android.content.pm.PackageStats;
150import android.content.pm.PackageUserState;
151import android.content.pm.ParceledListSlice;
152import android.content.pm.PermissionGroupInfo;
153import android.content.pm.PermissionInfo;
154import android.content.pm.ProviderInfo;
155import android.content.pm.ResolveInfo;
156import android.content.pm.ServiceInfo;
157import android.content.pm.Signature;
158import android.content.pm.UserInfo;
159import android.content.pm.VerifierDeviceIdentity;
160import android.content.pm.VerifierInfo;
161import android.content.res.Resources;
162import android.graphics.Bitmap;
163import android.hardware.display.DisplayManager;
164import android.net.Uri;
165import android.os.Binder;
166import android.os.Build;
167import android.os.Bundle;
168import android.os.Debug;
169import android.os.Environment;
170import android.os.Environment.UserEnvironment;
171import android.os.FileUtils;
172import android.os.Handler;
173import android.os.IBinder;
174import android.os.Looper;
175import android.os.Message;
176import android.os.Parcel;
177import android.os.ParcelFileDescriptor;
178import android.os.Process;
179import android.os.RemoteCallbackList;
180import android.os.RemoteException;
181import android.os.ResultReceiver;
182import android.os.SELinux;
183import android.os.ServiceManager;
184import android.os.SystemClock;
185import android.os.SystemProperties;
186import android.os.Trace;
187import android.os.UserHandle;
188import android.os.UserManager;
189import android.os.storage.IMountService;
190import android.os.storage.MountServiceInternal;
191import android.os.storage.StorageEventListener;
192import android.os.storage.StorageManager;
193import android.os.storage.VolumeInfo;
194import android.os.storage.VolumeRecord;
195import android.security.KeyStore;
196import android.security.SystemKeyStore;
197import android.system.ErrnoException;
198import android.system.Os;
199import android.text.TextUtils;
200import android.text.format.DateUtils;
201import android.util.ArrayMap;
202import android.util.ArraySet;
203import android.util.AtomicFile;
204import android.util.DisplayMetrics;
205import android.util.EventLog;
206import android.util.ExceptionUtils;
207import android.util.Log;
208import android.util.LogPrinter;
209import android.util.MathUtils;
210import android.util.PrintStreamPrinter;
211import android.util.Slog;
212import android.util.SparseArray;
213import android.util.SparseBooleanArray;
214import android.util.SparseIntArray;
215import android.util.Xml;
216import android.view.Display;
217
218import com.android.internal.R;
219import com.android.internal.annotations.GuardedBy;
220import com.android.internal.app.IMediaContainerService;
221import com.android.internal.app.ResolverActivity;
222import com.android.internal.content.NativeLibraryHelper;
223import com.android.internal.content.PackageHelper;
224import com.android.internal.os.IParcelFileDescriptorFactory;
225import com.android.internal.os.InstallerConnection.InstallerException;
226import com.android.internal.os.SomeArgs;
227import com.android.internal.os.Zygote;
228import com.android.internal.util.ArrayUtils;
229import com.android.internal.util.FastPrintWriter;
230import com.android.internal.util.FastXmlSerializer;
231import com.android.internal.util.IndentingPrintWriter;
232import com.android.internal.util.Preconditions;
233import com.android.internal.util.XmlUtils;
234import com.android.server.EventLogTags;
235import com.android.server.FgThread;
236import com.android.server.IntentResolver;
237import com.android.server.LocalServices;
238import com.android.server.ServiceThread;
239import com.android.server.SystemConfig;
240import com.android.server.Watchdog;
241import com.android.server.pm.PermissionsState.PermissionState;
242import com.android.server.pm.Settings.DatabaseVersion;
243import com.android.server.pm.Settings.VersionInfo;
244import com.android.server.storage.DeviceStorageMonitorInternal;
245
246import dalvik.system.DexFile;
247import dalvik.system.VMRuntime;
248
249import libcore.io.IoUtils;
250import libcore.util.EmptyArray;
251
252import org.xmlpull.v1.XmlPullParser;
253import org.xmlpull.v1.XmlPullParserException;
254import org.xmlpull.v1.XmlSerializer;
255
256import java.io.BufferedInputStream;
257import java.io.BufferedOutputStream;
258import java.io.BufferedReader;
259import java.io.ByteArrayInputStream;
260import java.io.ByteArrayOutputStream;
261import java.io.File;
262import java.io.FileDescriptor;
263import java.io.FileNotFoundException;
264import java.io.FileOutputStream;
265import java.io.FileReader;
266import java.io.FilenameFilter;
267import java.io.IOException;
268import java.io.InputStream;
269import java.io.PrintWriter;
270import java.nio.charset.StandardCharsets;
271import java.security.MessageDigest;
272import java.security.NoSuchAlgorithmException;
273import java.security.PublicKey;
274import java.security.cert.CertificateEncodingException;
275import java.security.cert.CertificateException;
276import java.text.SimpleDateFormat;
277import java.util.ArrayList;
278import java.util.Arrays;
279import java.util.Collection;
280import java.util.Collections;
281import java.util.Comparator;
282import java.util.Date;
283import java.util.HashSet;
284import java.util.Iterator;
285import java.util.List;
286import java.util.Map;
287import java.util.Objects;
288import java.util.Set;
289import java.util.concurrent.CountDownLatch;
290import java.util.concurrent.TimeUnit;
291import java.util.concurrent.atomic.AtomicBoolean;
292import java.util.concurrent.atomic.AtomicInteger;
293import java.util.concurrent.atomic.AtomicLong;
294
295/**
296 * Keep track of all those .apks everywhere.
297 *
298 * This is very central to the platform's security; please run the unit
299 * tests whenever making modifications here:
300 *
301runtest -c android.content.pm.PackageManagerTests frameworks-core
302 *
303 * {@hide}
304 */
305public class PackageManagerService extends IPackageManager.Stub {
306    static final String TAG = "PackageManager";
307    static final boolean DEBUG_SETTINGS = false;
308    static final boolean DEBUG_PREFERRED = false;
309    static final boolean DEBUG_UPGRADE = false;
310    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
311    private static final boolean DEBUG_BACKUP = false;
312    private static final boolean DEBUG_INSTALL = false;
313    private static final boolean DEBUG_REMOVE = false;
314    private static final boolean DEBUG_BROADCASTS = false;
315    private static final boolean DEBUG_SHOW_INFO = false;
316    private static final boolean DEBUG_PACKAGE_INFO = false;
317    private static final boolean DEBUG_INTENT_MATCHING = false;
318    private static final boolean DEBUG_PACKAGE_SCANNING = false;
319    private static final boolean DEBUG_VERIFY = false;
320
321    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
322    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
323    // user, but by default initialize to this.
324    static final boolean DEBUG_DEXOPT = false;
325
326    private static final boolean DEBUG_ABI_SELECTION = false;
327    private static final boolean DEBUG_EPHEMERAL = false;
328    private static final boolean DEBUG_TRIAGED_MISSING = false;
329    private static final boolean DEBUG_APP_DATA = false;
330
331    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
332
333    private static final boolean DISABLE_EPHEMERAL_APPS = true;
334
335    private static final int RADIO_UID = Process.PHONE_UID;
336    private static final int LOG_UID = Process.LOG_UID;
337    private static final int NFC_UID = Process.NFC_UID;
338    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
339    private static final int SHELL_UID = Process.SHELL_UID;
340
341    // Cap the size of permission trees that 3rd party apps can define
342    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
343
344    // Suffix used during package installation when copying/moving
345    // package apks to install directory.
346    private static final String INSTALL_PACKAGE_SUFFIX = "-";
347
348    static final int SCAN_NO_DEX = 1<<1;
349    static final int SCAN_FORCE_DEX = 1<<2;
350    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
351    static final int SCAN_NEW_INSTALL = 1<<4;
352    static final int SCAN_NO_PATHS = 1<<5;
353    static final int SCAN_UPDATE_TIME = 1<<6;
354    static final int SCAN_DEFER_DEX = 1<<7;
355    static final int SCAN_BOOTING = 1<<8;
356    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
357    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
358    static final int SCAN_REPLACING = 1<<11;
359    static final int SCAN_REQUIRE_KNOWN = 1<<12;
360    static final int SCAN_MOVE = 1<<13;
361    static final int SCAN_INITIAL = 1<<14;
362    static final int SCAN_CHECK_ONLY = 1<<15;
363    static final int SCAN_DONT_KILL_APP = 1<<17;
364
365    static final int REMOVE_CHATTY = 1<<16;
366
367    private static final int[] EMPTY_INT_ARRAY = new int[0];
368
369    /**
370     * Timeout (in milliseconds) after which the watchdog should declare that
371     * our handler thread is wedged.  The usual default for such things is one
372     * minute but we sometimes do very lengthy I/O operations on this thread,
373     * such as installing multi-gigabyte applications, so ours needs to be longer.
374     */
375    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
376
377    /**
378     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
379     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
380     * settings entry if available, otherwise we use the hardcoded default.  If it's been
381     * more than this long since the last fstrim, we force one during the boot sequence.
382     *
383     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
384     * one gets run at the next available charging+idle time.  This final mandatory
385     * no-fstrim check kicks in only of the other scheduling criteria is never met.
386     */
387    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
388
389    /**
390     * Whether verification is enabled by default.
391     */
392    private static final boolean DEFAULT_VERIFY_ENABLE = true;
393
394    /**
395     * The default maximum time to wait for the verification agent to return in
396     * milliseconds.
397     */
398    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
399
400    /**
401     * The default response for package verification timeout.
402     *
403     * This can be either PackageManager.VERIFICATION_ALLOW or
404     * PackageManager.VERIFICATION_REJECT.
405     */
406    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
407
408    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
409
410    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
411            DEFAULT_CONTAINER_PACKAGE,
412            "com.android.defcontainer.DefaultContainerService");
413
414    private static final String KILL_APP_REASON_GIDS_CHANGED =
415            "permission grant or revoke changed gids";
416
417    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
418            "permissions revoked";
419
420    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
421
422    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
423
424    /** Permission grant: not grant the permission. */
425    private static final int GRANT_DENIED = 1;
426
427    /** Permission grant: grant the permission as an install permission. */
428    private static final int GRANT_INSTALL = 2;
429
430    /** Permission grant: grant the permission as a runtime one. */
431    private static final int GRANT_RUNTIME = 3;
432
433    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
434    private static final int GRANT_UPGRADE = 4;
435
436    /** Canonical intent used to identify what counts as a "web browser" app */
437    private static final Intent sBrowserIntent;
438    static {
439        sBrowserIntent = new Intent();
440        sBrowserIntent.setAction(Intent.ACTION_VIEW);
441        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
442        sBrowserIntent.setData(Uri.parse("http:"));
443    }
444
445    final ServiceThread mHandlerThread;
446
447    final PackageHandler mHandler;
448
449    /**
450     * Messages for {@link #mHandler} that need to wait for system ready before
451     * being dispatched.
452     */
453    private ArrayList<Message> mPostSystemReadyMessages;
454
455    final int mSdkVersion = Build.VERSION.SDK_INT;
456
457    final Context mContext;
458    final boolean mFactoryTest;
459    final boolean mOnlyCore;
460    final DisplayMetrics mMetrics;
461    final int mDefParseFlags;
462    final String[] mSeparateProcesses;
463    final boolean mIsUpgrade;
464
465    /** The location for ASEC container files on internal storage. */
466    final String mAsecInternalPath;
467
468    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
469    // LOCK HELD.  Can be called with mInstallLock held.
470    @GuardedBy("mInstallLock")
471    final Installer mInstaller;
472
473    /** Directory where installed third-party apps stored */
474    final File mAppInstallDir;
475    final File mEphemeralInstallDir;
476
477    /**
478     * Directory to which applications installed internally have their
479     * 32 bit native libraries copied.
480     */
481    private File mAppLib32InstallDir;
482
483    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
484    // apps.
485    final File mDrmAppPrivateInstallDir;
486
487    // ----------------------------------------------------------------
488
489    // Lock for state used when installing and doing other long running
490    // operations.  Methods that must be called with this lock held have
491    // the suffix "LI".
492    final Object mInstallLock = new Object();
493
494    // ----------------------------------------------------------------
495
496    // Keys are String (package name), values are Package.  This also serves
497    // as the lock for the global state.  Methods that must be called with
498    // this lock held have the prefix "LP".
499    @GuardedBy("mPackages")
500    final ArrayMap<String, PackageParser.Package> mPackages =
501            new ArrayMap<String, PackageParser.Package>();
502
503    final ArrayMap<String, Set<String>> mKnownCodebase =
504            new ArrayMap<String, Set<String>>();
505
506    // Tracks available target package names -> overlay package paths.
507    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
508        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
509
510    /**
511     * Tracks new system packages [received in an OTA] that we expect to
512     * find updated user-installed versions. Keys are package name, values
513     * are package location.
514     */
515    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
516
517    /**
518     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
519     */
520    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
521    /**
522     * Whether or not system app permissions should be promoted from install to runtime.
523     */
524    boolean mPromoteSystemApps;
525
526    final Settings mSettings;
527    boolean mRestoredSettings;
528
529    // System configuration read by SystemConfig.
530    final int[] mGlobalGids;
531    final SparseArray<ArraySet<String>> mSystemPermissions;
532    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
533
534    // If mac_permissions.xml was found for seinfo labeling.
535    boolean mFoundPolicyFile;
536
537    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
538
539    public static final class SharedLibraryEntry {
540        public final String path;
541        public final String apk;
542
543        SharedLibraryEntry(String _path, String _apk) {
544            path = _path;
545            apk = _apk;
546        }
547    }
548
549    // Currently known shared libraries.
550    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
551            new ArrayMap<String, SharedLibraryEntry>();
552
553    // All available activities, for your resolving pleasure.
554    final ActivityIntentResolver mActivities =
555            new ActivityIntentResolver();
556
557    // All available receivers, for your resolving pleasure.
558    final ActivityIntentResolver mReceivers =
559            new ActivityIntentResolver();
560
561    // All available services, for your resolving pleasure.
562    final ServiceIntentResolver mServices = new ServiceIntentResolver();
563
564    // All available providers, for your resolving pleasure.
565    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
566
567    // Mapping from provider base names (first directory in content URI codePath)
568    // to the provider information.
569    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
570            new ArrayMap<String, PackageParser.Provider>();
571
572    // Mapping from instrumentation class names to info about them.
573    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
574            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
575
576    // Mapping from permission names to info about them.
577    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
578            new ArrayMap<String, PackageParser.PermissionGroup>();
579
580    // Packages whose data we have transfered into another package, thus
581    // should no longer exist.
582    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
583
584    // Broadcast actions that are only available to the system.
585    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
586
587    /** List of packages waiting for verification. */
588    final SparseArray<PackageVerificationState> mPendingVerification
589            = new SparseArray<PackageVerificationState>();
590
591    /** Set of packages associated with each app op permission. */
592    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
593
594    final PackageInstallerService mInstallerService;
595
596    private final PackageDexOptimizer mPackageDexOptimizer;
597
598    private AtomicInteger mNextMoveId = new AtomicInteger();
599    private final MoveCallbacks mMoveCallbacks;
600
601    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
602
603    // Cache of users who need badging.
604    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
605
606    /** Token for keys in mPendingVerification. */
607    private int mPendingVerificationToken = 0;
608
609    volatile boolean mSystemReady;
610    volatile boolean mSafeMode;
611    volatile boolean mHasSystemUidErrors;
612
613    ApplicationInfo mAndroidApplication;
614    final ActivityInfo mResolveActivity = new ActivityInfo();
615    final ResolveInfo mResolveInfo = new ResolveInfo();
616    ComponentName mResolveComponentName;
617    PackageParser.Package mPlatformPackage;
618    ComponentName mCustomResolverComponentName;
619
620    boolean mResolverReplaced = false;
621
622    private final @Nullable ComponentName mIntentFilterVerifierComponent;
623    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
624
625    private int mIntentFilterVerificationToken = 0;
626
627    /** Component that knows whether or not an ephemeral application exists */
628    final ComponentName mEphemeralResolverComponent;
629    /** The service connection to the ephemeral resolver */
630    final EphemeralResolverConnection mEphemeralResolverConnection;
631
632    /** Component used to install ephemeral applications */
633    final ComponentName mEphemeralInstallerComponent;
634    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
635    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
636
637    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
638            = new SparseArray<IntentFilterVerificationState>();
639
640    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
641            new DefaultPermissionGrantPolicy(this);
642
643    // List of packages names to keep cached, even if they are uninstalled for all users
644    private List<String> mKeepUninstalledPackages;
645
646    private static class IFVerificationParams {
647        PackageParser.Package pkg;
648        boolean replacing;
649        int userId;
650        int verifierUid;
651
652        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
653                int _userId, int _verifierUid) {
654            pkg = _pkg;
655            replacing = _replacing;
656            userId = _userId;
657            replacing = _replacing;
658            verifierUid = _verifierUid;
659        }
660    }
661
662    private interface IntentFilterVerifier<T extends IntentFilter> {
663        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
664                                               T filter, String packageName);
665        void startVerifications(int userId);
666        void receiveVerificationResponse(int verificationId);
667    }
668
669    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
670        private Context mContext;
671        private ComponentName mIntentFilterVerifierComponent;
672        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
673
674        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
675            mContext = context;
676            mIntentFilterVerifierComponent = verifierComponent;
677        }
678
679        private String getDefaultScheme() {
680            return IntentFilter.SCHEME_HTTPS;
681        }
682
683        @Override
684        public void startVerifications(int userId) {
685            // Launch verifications requests
686            int count = mCurrentIntentFilterVerifications.size();
687            for (int n=0; n<count; n++) {
688                int verificationId = mCurrentIntentFilterVerifications.get(n);
689                final IntentFilterVerificationState ivs =
690                        mIntentFilterVerificationStates.get(verificationId);
691
692                String packageName = ivs.getPackageName();
693
694                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
695                final int filterCount = filters.size();
696                ArraySet<String> domainsSet = new ArraySet<>();
697                for (int m=0; m<filterCount; m++) {
698                    PackageParser.ActivityIntentInfo filter = filters.get(m);
699                    domainsSet.addAll(filter.getHostsList());
700                }
701                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
702                synchronized (mPackages) {
703                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
704                            packageName, domainsList) != null) {
705                        scheduleWriteSettingsLocked();
706                    }
707                }
708                sendVerificationRequest(userId, verificationId, ivs);
709            }
710            mCurrentIntentFilterVerifications.clear();
711        }
712
713        private void sendVerificationRequest(int userId, int verificationId,
714                IntentFilterVerificationState ivs) {
715
716            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
717            verificationIntent.putExtra(
718                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
719                    verificationId);
720            verificationIntent.putExtra(
721                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
722                    getDefaultScheme());
723            verificationIntent.putExtra(
724                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
725                    ivs.getHostsString());
726            verificationIntent.putExtra(
727                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
728                    ivs.getPackageName());
729            verificationIntent.setComponent(mIntentFilterVerifierComponent);
730            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
731
732            UserHandle user = new UserHandle(userId);
733            mContext.sendBroadcastAsUser(verificationIntent, user);
734            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
735                    "Sending IntentFilter verification broadcast");
736        }
737
738        public void receiveVerificationResponse(int verificationId) {
739            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
740
741            final boolean verified = ivs.isVerified();
742
743            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
744            final int count = filters.size();
745            if (DEBUG_DOMAIN_VERIFICATION) {
746                Slog.i(TAG, "Received verification response " + verificationId
747                        + " for " + count + " filters, verified=" + verified);
748            }
749            for (int n=0; n<count; n++) {
750                PackageParser.ActivityIntentInfo filter = filters.get(n);
751                filter.setVerified(verified);
752
753                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
754                        + " verified with result:" + verified + " and hosts:"
755                        + ivs.getHostsString());
756            }
757
758            mIntentFilterVerificationStates.remove(verificationId);
759
760            final String packageName = ivs.getPackageName();
761            IntentFilterVerificationInfo ivi = null;
762
763            synchronized (mPackages) {
764                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
765            }
766            if (ivi == null) {
767                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
768                        + verificationId + " packageName:" + packageName);
769                return;
770            }
771            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
772                    "Updating IntentFilterVerificationInfo for package " + packageName
773                            +" verificationId:" + verificationId);
774
775            synchronized (mPackages) {
776                if (verified) {
777                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
778                } else {
779                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
780                }
781                scheduleWriteSettingsLocked();
782
783                final int userId = ivs.getUserId();
784                if (userId != UserHandle.USER_ALL) {
785                    final int userStatus =
786                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
787
788                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
789                    boolean needUpdate = false;
790
791                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
792                    // already been set by the User thru the Disambiguation dialog
793                    switch (userStatus) {
794                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
795                            if (verified) {
796                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
797                            } else {
798                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
799                            }
800                            needUpdate = true;
801                            break;
802
803                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
804                            if (verified) {
805                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
806                                needUpdate = true;
807                            }
808                            break;
809
810                        default:
811                            // Nothing to do
812                    }
813
814                    if (needUpdate) {
815                        mSettings.updateIntentFilterVerificationStatusLPw(
816                                packageName, updatedStatus, userId);
817                        scheduleWritePackageRestrictionsLocked(userId);
818                    }
819                }
820            }
821        }
822
823        @Override
824        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
825                    ActivityIntentInfo filter, String packageName) {
826            if (!hasValidDomains(filter)) {
827                return false;
828            }
829            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
830            if (ivs == null) {
831                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
832                        packageName);
833            }
834            if (DEBUG_DOMAIN_VERIFICATION) {
835                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
836            }
837            ivs.addFilter(filter);
838            return true;
839        }
840
841        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
842                int userId, int verificationId, String packageName) {
843            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
844                    verifierUid, userId, packageName);
845            ivs.setPendingState();
846            synchronized (mPackages) {
847                mIntentFilterVerificationStates.append(verificationId, ivs);
848                mCurrentIntentFilterVerifications.add(verificationId);
849            }
850            return ivs;
851        }
852    }
853
854    private static boolean hasValidDomains(ActivityIntentInfo filter) {
855        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
856                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
857                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
858    }
859
860    // Set of pending broadcasts for aggregating enable/disable of components.
861    static class PendingPackageBroadcasts {
862        // for each user id, a map of <package name -> components within that package>
863        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
864
865        public PendingPackageBroadcasts() {
866            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
867        }
868
869        public ArrayList<String> get(int userId, String packageName) {
870            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
871            return packages.get(packageName);
872        }
873
874        public void put(int userId, String packageName, ArrayList<String> components) {
875            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
876            packages.put(packageName, components);
877        }
878
879        public void remove(int userId, String packageName) {
880            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
881            if (packages != null) {
882                packages.remove(packageName);
883            }
884        }
885
886        public void remove(int userId) {
887            mUidMap.remove(userId);
888        }
889
890        public int userIdCount() {
891            return mUidMap.size();
892        }
893
894        public int userIdAt(int n) {
895            return mUidMap.keyAt(n);
896        }
897
898        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
899            return mUidMap.get(userId);
900        }
901
902        public int size() {
903            // total number of pending broadcast entries across all userIds
904            int num = 0;
905            for (int i = 0; i< mUidMap.size(); i++) {
906                num += mUidMap.valueAt(i).size();
907            }
908            return num;
909        }
910
911        public void clear() {
912            mUidMap.clear();
913        }
914
915        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
916            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
917            if (map == null) {
918                map = new ArrayMap<String, ArrayList<String>>();
919                mUidMap.put(userId, map);
920            }
921            return map;
922        }
923    }
924    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
925
926    // Service Connection to remote media container service to copy
927    // package uri's from external media onto secure containers
928    // or internal storage.
929    private IMediaContainerService mContainerService = null;
930
931    static final int SEND_PENDING_BROADCAST = 1;
932    static final int MCS_BOUND = 3;
933    static final int END_COPY = 4;
934    static final int INIT_COPY = 5;
935    static final int MCS_UNBIND = 6;
936    static final int START_CLEANING_PACKAGE = 7;
937    static final int FIND_INSTALL_LOC = 8;
938    static final int POST_INSTALL = 9;
939    static final int MCS_RECONNECT = 10;
940    static final int MCS_GIVE_UP = 11;
941    static final int UPDATED_MEDIA_STATUS = 12;
942    static final int WRITE_SETTINGS = 13;
943    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
944    static final int PACKAGE_VERIFIED = 15;
945    static final int CHECK_PENDING_VERIFICATION = 16;
946    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
947    static final int INTENT_FILTER_VERIFIED = 18;
948
949    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
950
951    // Delay time in millisecs
952    static final int BROADCAST_DELAY = 10 * 1000;
953
954    static UserManagerService sUserManager;
955
956    // Stores a list of users whose package restrictions file needs to be updated
957    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
958
959    final private DefaultContainerConnection mDefContainerConn =
960            new DefaultContainerConnection();
961    class DefaultContainerConnection implements ServiceConnection {
962        public void onServiceConnected(ComponentName name, IBinder service) {
963            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
964            IMediaContainerService imcs =
965                IMediaContainerService.Stub.asInterface(service);
966            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
967        }
968
969        public void onServiceDisconnected(ComponentName name) {
970            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
971        }
972    }
973
974    // Recordkeeping of restore-after-install operations that are currently in flight
975    // between the Package Manager and the Backup Manager
976    static class PostInstallData {
977        public InstallArgs args;
978        public PackageInstalledInfo res;
979
980        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
981            args = _a;
982            res = _r;
983        }
984    }
985
986    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
987    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
988
989    // XML tags for backup/restore of various bits of state
990    private static final String TAG_PREFERRED_BACKUP = "pa";
991    private static final String TAG_DEFAULT_APPS = "da";
992    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
993
994    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
995    private static final String TAG_ALL_GRANTS = "rt-grants";
996    private static final String TAG_GRANT = "grant";
997    private static final String ATTR_PACKAGE_NAME = "pkg";
998
999    private static final String TAG_PERMISSION = "perm";
1000    private static final String ATTR_PERMISSION_NAME = "name";
1001    private static final String ATTR_IS_GRANTED = "g";
1002    private static final String ATTR_USER_SET = "set";
1003    private static final String ATTR_USER_FIXED = "fixed";
1004    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1005
1006    // System/policy permission grants are not backed up
1007    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1008            FLAG_PERMISSION_POLICY_FIXED
1009            | FLAG_PERMISSION_SYSTEM_FIXED
1010            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1011
1012    // And we back up these user-adjusted states
1013    private static final int USER_RUNTIME_GRANT_MASK =
1014            FLAG_PERMISSION_USER_SET
1015            | FLAG_PERMISSION_USER_FIXED
1016            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1017
1018    final @Nullable String mRequiredVerifierPackage;
1019    final @Nullable String mRequiredInstallerPackage;
1020
1021    private final PackageUsage mPackageUsage = new PackageUsage();
1022
1023    private class PackageUsage {
1024        private static final int WRITE_INTERVAL
1025            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1026
1027        private final Object mFileLock = new Object();
1028        private final AtomicLong mLastWritten = new AtomicLong(0);
1029        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1030
1031        private boolean mIsHistoricalPackageUsageAvailable = true;
1032
1033        boolean isHistoricalPackageUsageAvailable() {
1034            return mIsHistoricalPackageUsageAvailable;
1035        }
1036
1037        void write(boolean force) {
1038            if (force) {
1039                writeInternal();
1040                return;
1041            }
1042            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1043                && !DEBUG_DEXOPT) {
1044                return;
1045            }
1046            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1047                new Thread("PackageUsage_DiskWriter") {
1048                    @Override
1049                    public void run() {
1050                        try {
1051                            writeInternal();
1052                        } finally {
1053                            mBackgroundWriteRunning.set(false);
1054                        }
1055                    }
1056                }.start();
1057            }
1058        }
1059
1060        private void writeInternal() {
1061            synchronized (mPackages) {
1062                synchronized (mFileLock) {
1063                    AtomicFile file = getFile();
1064                    FileOutputStream f = null;
1065                    try {
1066                        f = file.startWrite();
1067                        BufferedOutputStream out = new BufferedOutputStream(f);
1068                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1069                        StringBuilder sb = new StringBuilder();
1070                        for (PackageParser.Package pkg : mPackages.values()) {
1071                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1072                                continue;
1073                            }
1074                            sb.setLength(0);
1075                            sb.append(pkg.packageName);
1076                            sb.append(' ');
1077                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1078                            sb.append('\n');
1079                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1080                        }
1081                        out.flush();
1082                        file.finishWrite(f);
1083                    } catch (IOException e) {
1084                        if (f != null) {
1085                            file.failWrite(f);
1086                        }
1087                        Log.e(TAG, "Failed to write package usage times", e);
1088                    }
1089                }
1090            }
1091            mLastWritten.set(SystemClock.elapsedRealtime());
1092        }
1093
1094        void readLP() {
1095            synchronized (mFileLock) {
1096                AtomicFile file = getFile();
1097                BufferedInputStream in = null;
1098                try {
1099                    in = new BufferedInputStream(file.openRead());
1100                    StringBuffer sb = new StringBuffer();
1101                    while (true) {
1102                        String packageName = readToken(in, sb, ' ');
1103                        if (packageName == null) {
1104                            break;
1105                        }
1106                        String timeInMillisString = readToken(in, sb, '\n');
1107                        if (timeInMillisString == null) {
1108                            throw new IOException("Failed to find last usage time for package "
1109                                                  + packageName);
1110                        }
1111                        PackageParser.Package pkg = mPackages.get(packageName);
1112                        if (pkg == null) {
1113                            continue;
1114                        }
1115                        long timeInMillis;
1116                        try {
1117                            timeInMillis = Long.parseLong(timeInMillisString);
1118                        } catch (NumberFormatException e) {
1119                            throw new IOException("Failed to parse " + timeInMillisString
1120                                                  + " as a long.", e);
1121                        }
1122                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1123                    }
1124                } catch (FileNotFoundException expected) {
1125                    mIsHistoricalPackageUsageAvailable = false;
1126                } catch (IOException e) {
1127                    Log.w(TAG, "Failed to read package usage times", e);
1128                } finally {
1129                    IoUtils.closeQuietly(in);
1130                }
1131            }
1132            mLastWritten.set(SystemClock.elapsedRealtime());
1133        }
1134
1135        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1136                throws IOException {
1137            sb.setLength(0);
1138            while (true) {
1139                int ch = in.read();
1140                if (ch == -1) {
1141                    if (sb.length() == 0) {
1142                        return null;
1143                    }
1144                    throw new IOException("Unexpected EOF");
1145                }
1146                if (ch == endOfToken) {
1147                    return sb.toString();
1148                }
1149                sb.append((char)ch);
1150            }
1151        }
1152
1153        private AtomicFile getFile() {
1154            File dataDir = Environment.getDataDirectory();
1155            File systemDir = new File(dataDir, "system");
1156            File fname = new File(systemDir, "package-usage.list");
1157            return new AtomicFile(fname);
1158        }
1159    }
1160
1161    class PackageHandler extends Handler {
1162        private boolean mBound = false;
1163        final ArrayList<HandlerParams> mPendingInstalls =
1164            new ArrayList<HandlerParams>();
1165
1166        private boolean connectToService() {
1167            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1168                    " DefaultContainerService");
1169            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1170            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1171            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1172                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1173                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174                mBound = true;
1175                return true;
1176            }
1177            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1178            return false;
1179        }
1180
1181        private void disconnectService() {
1182            mContainerService = null;
1183            mBound = false;
1184            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1185            mContext.unbindService(mDefContainerConn);
1186            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1187        }
1188
1189        PackageHandler(Looper looper) {
1190            super(looper);
1191        }
1192
1193        public void handleMessage(Message msg) {
1194            try {
1195                doHandleMessage(msg);
1196            } finally {
1197                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1198            }
1199        }
1200
1201        void doHandleMessage(Message msg) {
1202            switch (msg.what) {
1203                case INIT_COPY: {
1204                    HandlerParams params = (HandlerParams) msg.obj;
1205                    int idx = mPendingInstalls.size();
1206                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1207                    // If a bind was already initiated we dont really
1208                    // need to do anything. The pending install
1209                    // will be processed later on.
1210                    if (!mBound) {
1211                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1212                                System.identityHashCode(mHandler));
1213                        // If this is the only one pending we might
1214                        // have to bind to the service again.
1215                        if (!connectToService()) {
1216                            Slog.e(TAG, "Failed to bind to media container service");
1217                            params.serviceError();
1218                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1219                                    System.identityHashCode(mHandler));
1220                            if (params.traceMethod != null) {
1221                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1222                                        params.traceCookie);
1223                            }
1224                            return;
1225                        } else {
1226                            // Once we bind to the service, the first
1227                            // pending request will be processed.
1228                            mPendingInstalls.add(idx, params);
1229                        }
1230                    } else {
1231                        mPendingInstalls.add(idx, params);
1232                        // Already bound to the service. Just make
1233                        // sure we trigger off processing the first request.
1234                        if (idx == 0) {
1235                            mHandler.sendEmptyMessage(MCS_BOUND);
1236                        }
1237                    }
1238                    break;
1239                }
1240                case MCS_BOUND: {
1241                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1242                    if (msg.obj != null) {
1243                        mContainerService = (IMediaContainerService) msg.obj;
1244                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1245                                System.identityHashCode(mHandler));
1246                    }
1247                    if (mContainerService == null) {
1248                        if (!mBound) {
1249                            // Something seriously wrong since we are not bound and we are not
1250                            // waiting for connection. Bail out.
1251                            Slog.e(TAG, "Cannot bind to media container service");
1252                            for (HandlerParams params : mPendingInstalls) {
1253                                // Indicate service bind error
1254                                params.serviceError();
1255                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1256                                        System.identityHashCode(params));
1257                                if (params.traceMethod != null) {
1258                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1259                                            params.traceMethod, params.traceCookie);
1260                                }
1261                                return;
1262                            }
1263                            mPendingInstalls.clear();
1264                        } else {
1265                            Slog.w(TAG, "Waiting to connect to media container service");
1266                        }
1267                    } else if (mPendingInstalls.size() > 0) {
1268                        HandlerParams params = mPendingInstalls.get(0);
1269                        if (params != null) {
1270                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1271                                    System.identityHashCode(params));
1272                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1273                            if (params.startCopy()) {
1274                                // We are done...  look for more work or to
1275                                // go idle.
1276                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                        "Checking for more work or unbind...");
1278                                // Delete pending install
1279                                if (mPendingInstalls.size() > 0) {
1280                                    mPendingInstalls.remove(0);
1281                                }
1282                                if (mPendingInstalls.size() == 0) {
1283                                    if (mBound) {
1284                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                                "Posting delayed MCS_UNBIND");
1286                                        removeMessages(MCS_UNBIND);
1287                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1288                                        // Unbind after a little delay, to avoid
1289                                        // continual thrashing.
1290                                        sendMessageDelayed(ubmsg, 10000);
1291                                    }
1292                                } else {
1293                                    // There are more pending requests in queue.
1294                                    // Just post MCS_BOUND message to trigger processing
1295                                    // of next pending install.
1296                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1297                                            "Posting MCS_BOUND for next work");
1298                                    mHandler.sendEmptyMessage(MCS_BOUND);
1299                                }
1300                            }
1301                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1302                        }
1303                    } else {
1304                        // Should never happen ideally.
1305                        Slog.w(TAG, "Empty queue");
1306                    }
1307                    break;
1308                }
1309                case MCS_RECONNECT: {
1310                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1311                    if (mPendingInstalls.size() > 0) {
1312                        if (mBound) {
1313                            disconnectService();
1314                        }
1315                        if (!connectToService()) {
1316                            Slog.e(TAG, "Failed to bind to media container service");
1317                            for (HandlerParams params : mPendingInstalls) {
1318                                // Indicate service bind error
1319                                params.serviceError();
1320                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                                        System.identityHashCode(params));
1322                            }
1323                            mPendingInstalls.clear();
1324                        }
1325                    }
1326                    break;
1327                }
1328                case MCS_UNBIND: {
1329                    // If there is no actual work left, then time to unbind.
1330                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1331
1332                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1333                        if (mBound) {
1334                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1335
1336                            disconnectService();
1337                        }
1338                    } else if (mPendingInstalls.size() > 0) {
1339                        // There are more pending requests in queue.
1340                        // Just post MCS_BOUND message to trigger processing
1341                        // of next pending install.
1342                        mHandler.sendEmptyMessage(MCS_BOUND);
1343                    }
1344
1345                    break;
1346                }
1347                case MCS_GIVE_UP: {
1348                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1349                    HandlerParams params = mPendingInstalls.remove(0);
1350                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1351                            System.identityHashCode(params));
1352                    break;
1353                }
1354                case SEND_PENDING_BROADCAST: {
1355                    String packages[];
1356                    ArrayList<String> components[];
1357                    int size = 0;
1358                    int uids[];
1359                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1360                    synchronized (mPackages) {
1361                        if (mPendingBroadcasts == null) {
1362                            return;
1363                        }
1364                        size = mPendingBroadcasts.size();
1365                        if (size <= 0) {
1366                            // Nothing to be done. Just return
1367                            return;
1368                        }
1369                        packages = new String[size];
1370                        components = new ArrayList[size];
1371                        uids = new int[size];
1372                        int i = 0;  // filling out the above arrays
1373
1374                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1375                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1376                            Iterator<Map.Entry<String, ArrayList<String>>> it
1377                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1378                                            .entrySet().iterator();
1379                            while (it.hasNext() && i < size) {
1380                                Map.Entry<String, ArrayList<String>> ent = it.next();
1381                                packages[i] = ent.getKey();
1382                                components[i] = ent.getValue();
1383                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1384                                uids[i] = (ps != null)
1385                                        ? UserHandle.getUid(packageUserId, ps.appId)
1386                                        : -1;
1387                                i++;
1388                            }
1389                        }
1390                        size = i;
1391                        mPendingBroadcasts.clear();
1392                    }
1393                    // Send broadcasts
1394                    for (int i = 0; i < size; i++) {
1395                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1396                    }
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1398                    break;
1399                }
1400                case START_CLEANING_PACKAGE: {
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402                    final String packageName = (String)msg.obj;
1403                    final int userId = msg.arg1;
1404                    final boolean andCode = msg.arg2 != 0;
1405                    synchronized (mPackages) {
1406                        if (userId == UserHandle.USER_ALL) {
1407                            int[] users = sUserManager.getUserIds();
1408                            for (int user : users) {
1409                                mSettings.addPackageToCleanLPw(
1410                                        new PackageCleanItem(user, packageName, andCode));
1411                            }
1412                        } else {
1413                            mSettings.addPackageToCleanLPw(
1414                                    new PackageCleanItem(userId, packageName, andCode));
1415                        }
1416                    }
1417                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418                    startCleaningPackages();
1419                } break;
1420                case POST_INSTALL: {
1421                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1422
1423                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1424                    mRunningInstalls.delete(msg.arg1);
1425
1426                    if (data != null) {
1427                        InstallArgs args = data.args;
1428                        PackageInstalledInfo parentRes = data.res;
1429
1430                        final boolean grantPermissions = (args.installFlags
1431                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1432                        final boolean killApp = (args.installFlags
1433                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1434                        final String[] grantedPermissions = args.installGrantPermissions;
1435
1436                        // Handle the parent package
1437                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1438                                grantedPermissions, args.observer);
1439
1440                        // Handle the child packages
1441                        final int childCount = (parentRes.addedChildPackages != null)
1442                                ? parentRes.addedChildPackages.size() : 0;
1443                        for (int i = 0; i < childCount; i++) {
1444                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1445                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1446                                    grantedPermissions, args.observer);
1447                        }
1448
1449                        // Log tracing if needed
1450                        if (args.traceMethod != null) {
1451                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1452                                    args.traceCookie);
1453                        }
1454                    } else {
1455                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1456                    }
1457
1458                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1459                } break;
1460                case UPDATED_MEDIA_STATUS: {
1461                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1462                    boolean reportStatus = msg.arg1 == 1;
1463                    boolean doGc = msg.arg2 == 1;
1464                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1465                    if (doGc) {
1466                        // Force a gc to clear up stale containers.
1467                        Runtime.getRuntime().gc();
1468                    }
1469                    if (msg.obj != null) {
1470                        @SuppressWarnings("unchecked")
1471                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1472                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1473                        // Unload containers
1474                        unloadAllContainers(args);
1475                    }
1476                    if (reportStatus) {
1477                        try {
1478                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1479                            PackageHelper.getMountService().finishMediaUpdate();
1480                        } catch (RemoteException e) {
1481                            Log.e(TAG, "MountService not running?");
1482                        }
1483                    }
1484                } break;
1485                case WRITE_SETTINGS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_SETTINGS);
1489                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1490                        mSettings.writeLPr();
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case WRITE_PACKAGE_RESTRICTIONS: {
1496                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1497                    synchronized (mPackages) {
1498                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1499                        for (int userId : mDirtyUsers) {
1500                            mSettings.writePackageRestrictionsLPr(userId);
1501                        }
1502                        mDirtyUsers.clear();
1503                    }
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1505                } break;
1506                case CHECK_PENDING_VERIFICATION: {
1507                    final int verificationId = msg.arg1;
1508                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1509
1510                    if ((state != null) && !state.timeoutExtended()) {
1511                        final InstallArgs args = state.getInstallArgs();
1512                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1513
1514                        Slog.i(TAG, "Verification timed out for " + originUri);
1515                        mPendingVerification.remove(verificationId);
1516
1517                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518
1519                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1520                            Slog.i(TAG, "Continuing with installation of " + originUri);
1521                            state.setVerifierResponse(Binder.getCallingUid(),
1522                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1523                            broadcastPackageVerified(verificationId, originUri,
1524                                    PackageManager.VERIFICATION_ALLOW,
1525                                    state.getInstallArgs().getUser());
1526                            try {
1527                                ret = args.copyApk(mContainerService, true);
1528                            } catch (RemoteException e) {
1529                                Slog.e(TAG, "Could not contact the ContainerService");
1530                            }
1531                        } else {
1532                            broadcastPackageVerified(verificationId, originUri,
1533                                    PackageManager.VERIFICATION_REJECT,
1534                                    state.getInstallArgs().getUser());
1535                        }
1536
1537                        Trace.asyncTraceEnd(
1538                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1539
1540                        processPendingInstall(args, ret);
1541                        mHandler.sendEmptyMessage(MCS_UNBIND);
1542                    }
1543                    break;
1544                }
1545                case PACKAGE_VERIFIED: {
1546                    final int verificationId = msg.arg1;
1547
1548                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1549                    if (state == null) {
1550                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1551                        break;
1552                    }
1553
1554                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1555
1556                    state.setVerifierResponse(response.callerUid, response.code);
1557
1558                    if (state.isVerificationComplete()) {
1559                        mPendingVerification.remove(verificationId);
1560
1561                        final InstallArgs args = state.getInstallArgs();
1562                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1563
1564                        int ret;
1565                        if (state.isInstallAllowed()) {
1566                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1567                            broadcastPackageVerified(verificationId, originUri,
1568                                    response.code, state.getInstallArgs().getUser());
1569                            try {
1570                                ret = args.copyApk(mContainerService, true);
1571                            } catch (RemoteException e) {
1572                                Slog.e(TAG, "Could not contact the ContainerService");
1573                            }
1574                        } else {
1575                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1576                        }
1577
1578                        Trace.asyncTraceEnd(
1579                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1580
1581                        processPendingInstall(args, ret);
1582                        mHandler.sendEmptyMessage(MCS_UNBIND);
1583                    }
1584
1585                    break;
1586                }
1587                case START_INTENT_FILTER_VERIFICATIONS: {
1588                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1589                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1590                            params.replacing, params.pkg);
1591                    break;
1592                }
1593                case INTENT_FILTER_VERIFIED: {
1594                    final int verificationId = msg.arg1;
1595
1596                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1597                            verificationId);
1598                    if (state == null) {
1599                        Slog.w(TAG, "Invalid IntentFilter verification token "
1600                                + verificationId + " received");
1601                        break;
1602                    }
1603
1604                    final int userId = state.getUserId();
1605
1606                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1607                            "Processing IntentFilter verification with token:"
1608                            + verificationId + " and userId:" + userId);
1609
1610                    final IntentFilterVerificationResponse response =
1611                            (IntentFilterVerificationResponse) msg.obj;
1612
1613                    state.setVerifierResponse(response.callerUid, response.code);
1614
1615                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1616                            "IntentFilter verification with token:" + verificationId
1617                            + " and userId:" + userId
1618                            + " is settings verifier response with response code:"
1619                            + response.code);
1620
1621                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1622                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1623                                + response.getFailedDomainsString());
1624                    }
1625
1626                    if (state.isVerificationComplete()) {
1627                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1628                    } else {
1629                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1630                                "IntentFilter verification with token:" + verificationId
1631                                + " was not said to be complete");
1632                    }
1633
1634                    break;
1635                }
1636            }
1637        }
1638    }
1639
1640    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1641            boolean killApp, String[] grantedPermissions,
1642            IPackageInstallObserver2 installObserver) {
1643        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1644            // Send the removed broadcasts
1645            if (res.removedInfo != null) {
1646                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1647            }
1648
1649            // Now that we successfully installed the package, grant runtime
1650            // permissions if requested before broadcasting the install.
1651            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1652                    >= Build.VERSION_CODES.M) {
1653                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1654            }
1655
1656            final boolean update = res.removedInfo != null
1657                    && res.removedInfo.removedPackage != null;
1658
1659            // If this is the first time we have child packages for a disabled privileged
1660            // app that had no children, we grant requested runtime permissions to the new
1661            // children if the parent on the system image had them already granted.
1662            if (res.pkg.parentPackage != null) {
1663                synchronized (mPackages) {
1664                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1665                }
1666            }
1667
1668            synchronized (mPackages) {
1669                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1670            }
1671
1672            final String packageName = res.pkg.applicationInfo.packageName;
1673            Bundle extras = new Bundle(1);
1674            extras.putInt(Intent.EXTRA_UID, res.uid);
1675
1676            // Determine the set of users who are adding this package for
1677            // the first time vs. those who are seeing an update.
1678            int[] firstUsers = EMPTY_INT_ARRAY;
1679            int[] updateUsers = EMPTY_INT_ARRAY;
1680            if (res.origUsers == null || res.origUsers.length == 0) {
1681                firstUsers = res.newUsers;
1682            } else {
1683                for (int newUser : res.newUsers) {
1684                    boolean isNew = true;
1685                    for (int origUser : res.origUsers) {
1686                        if (origUser == newUser) {
1687                            isNew = false;
1688                            break;
1689                        }
1690                    }
1691                    if (isNew) {
1692                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1693                    } else {
1694                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1695                    }
1696                }
1697            }
1698
1699            // Send installed broadcasts if the install/update is not ephemeral
1700            if (!isEphemeral(res.pkg)) {
1701                // Send added for users that see the package for the first time
1702                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1703                        extras, 0 /*flags*/, null /*targetPackage*/,
1704                        null /*finishedReceiver*/, firstUsers);
1705
1706                // Send added for users that don't see the package for the first time
1707                if (update) {
1708                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1709                }
1710                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1711                        extras, 0 /*flags*/, null /*targetPackage*/,
1712                        null /*finishedReceiver*/, updateUsers);
1713
1714                // Send replaced for users that don't see the package for the first time
1715                if (update) {
1716                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1717                            packageName, extras, 0 /*flags*/,
1718                            null /*targetPackage*/, null /*finishedReceiver*/,
1719                            updateUsers);
1720                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1721                            null /*package*/, null /*extras*/, 0 /*flags*/,
1722                            packageName /*targetPackage*/,
1723                            null /*finishedReceiver*/, updateUsers);
1724                }
1725
1726                // Send broadcast package appeared if forward locked/external for all users
1727                // treat asec-hosted packages like removable media on upgrade
1728                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1729                    if (DEBUG_INSTALL) {
1730                        Slog.i(TAG, "upgrading pkg " + res.pkg
1731                                + " is ASEC-hosted -> AVAILABLE");
1732                    }
1733                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1734                    ArrayList<String> pkgList = new ArrayList<>(1);
1735                    pkgList.add(packageName);
1736                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1737                }
1738            }
1739
1740            // Work that needs to happen on first install within each user
1741            if (firstUsers != null && firstUsers.length > 0) {
1742                synchronized (mPackages) {
1743                    for (int userId : firstUsers) {
1744                        // If this app is a browser and it's newly-installed for some
1745                        // users, clear any default-browser state in those users. The
1746                        // app's nature doesn't depend on the user, so we can just check
1747                        // its browser nature in any user and generalize.
1748                        if (packageIsBrowser(packageName, userId)) {
1749                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1750                        }
1751
1752                        // We may also need to apply pending (restored) runtime
1753                        // permission grants within these users.
1754                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1755                    }
1756                }
1757            }
1758
1759            // Log current value of "unknown sources" setting
1760            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1761                    getUnknownSourcesSettings());
1762
1763            // Force a gc to clear up things
1764            Runtime.getRuntime().gc();
1765
1766            // Remove the replaced package's older resources safely now
1767            // We delete after a gc for applications  on sdcard.
1768            if (res.removedInfo != null && res.removedInfo.args != null) {
1769                synchronized (mInstallLock) {
1770                    res.removedInfo.args.doPostDeleteLI(true);
1771                }
1772            }
1773        }
1774
1775        // If someone is watching installs - notify them
1776        if (installObserver != null) {
1777            try {
1778                Bundle extras = extrasForInstallResult(res);
1779                installObserver.onPackageInstalled(res.name, res.returnCode,
1780                        res.returnMsg, extras);
1781            } catch (RemoteException e) {
1782                Slog.i(TAG, "Observer no longer exists.");
1783            }
1784        }
1785    }
1786
1787    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1788            PackageParser.Package pkg) {
1789        if (pkg.parentPackage == null) {
1790            return;
1791        }
1792        if (pkg.requestedPermissions == null) {
1793            return;
1794        }
1795        final PackageSetting disabledSysParentPs = mSettings
1796                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1797        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1798                || !disabledSysParentPs.isPrivileged()
1799                || (disabledSysParentPs.childPackageNames != null
1800                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1801            return;
1802        }
1803        final int[] allUserIds = sUserManager.getUserIds();
1804        final int permCount = pkg.requestedPermissions.size();
1805        for (int i = 0; i < permCount; i++) {
1806            String permission = pkg.requestedPermissions.get(i);
1807            BasePermission bp = mSettings.mPermissions.get(permission);
1808            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1809                continue;
1810            }
1811            for (int userId : allUserIds) {
1812                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1813                        permission, userId)) {
1814                    grantRuntimePermission(pkg.packageName, permission, userId);
1815                }
1816            }
1817        }
1818    }
1819
1820    private StorageEventListener mStorageListener = new StorageEventListener() {
1821        @Override
1822        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1823            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1824                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1825                    final String volumeUuid = vol.getFsUuid();
1826
1827                    // Clean up any users or apps that were removed or recreated
1828                    // while this volume was missing
1829                    reconcileUsers(volumeUuid);
1830                    reconcileApps(volumeUuid);
1831
1832                    // Clean up any install sessions that expired or were
1833                    // cancelled while this volume was missing
1834                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1835
1836                    loadPrivatePackages(vol);
1837
1838                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1839                    unloadPrivatePackages(vol);
1840                }
1841            }
1842
1843            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1844                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1845                    updateExternalMediaStatus(true, false);
1846                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1847                    updateExternalMediaStatus(false, false);
1848                }
1849            }
1850        }
1851
1852        @Override
1853        public void onVolumeForgotten(String fsUuid) {
1854            if (TextUtils.isEmpty(fsUuid)) {
1855                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1856                return;
1857            }
1858
1859            // Remove any apps installed on the forgotten volume
1860            synchronized (mPackages) {
1861                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1862                for (PackageSetting ps : packages) {
1863                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1864                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1865                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1866                }
1867
1868                mSettings.onVolumeForgotten(fsUuid);
1869                mSettings.writeLPr();
1870            }
1871        }
1872    };
1873
1874    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1875            String[] grantedPermissions) {
1876        for (int userId : userIds) {
1877            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1878        }
1879
1880        // We could have touched GID membership, so flush out packages.list
1881        synchronized (mPackages) {
1882            mSettings.writePackageListLPr();
1883        }
1884    }
1885
1886    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1887            String[] grantedPermissions) {
1888        SettingBase sb = (SettingBase) pkg.mExtras;
1889        if (sb == null) {
1890            return;
1891        }
1892
1893        PermissionsState permissionsState = sb.getPermissionsState();
1894
1895        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1896                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1897
1898        synchronized (mPackages) {
1899            for (String permission : pkg.requestedPermissions) {
1900                BasePermission bp = mSettings.mPermissions.get(permission);
1901                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1902                        && (grantedPermissions == null
1903                               || ArrayUtils.contains(grantedPermissions, permission))) {
1904                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1905                    // Installer cannot change immutable permissions.
1906                    if ((flags & immutableFlags) == 0) {
1907                        grantRuntimePermission(pkg.packageName, permission, userId);
1908                    }
1909                }
1910            }
1911        }
1912    }
1913
1914    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1915        Bundle extras = null;
1916        switch (res.returnCode) {
1917            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1918                extras = new Bundle();
1919                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1920                        res.origPermission);
1921                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1922                        res.origPackage);
1923                break;
1924            }
1925            case PackageManager.INSTALL_SUCCEEDED: {
1926                extras = new Bundle();
1927                extras.putBoolean(Intent.EXTRA_REPLACING,
1928                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1929                break;
1930            }
1931        }
1932        return extras;
1933    }
1934
1935    void scheduleWriteSettingsLocked() {
1936        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1937            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1938        }
1939    }
1940
1941    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1942        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1943        scheduleWritePackageRestrictionsLocked(userId);
1944    }
1945
1946    void scheduleWritePackageRestrictionsLocked(int userId) {
1947        final int[] userIds = (userId == UserHandle.USER_ALL)
1948                ? sUserManager.getUserIds() : new int[]{userId};
1949        for (int nextUserId : userIds) {
1950            if (!sUserManager.exists(nextUserId)) return;
1951            mDirtyUsers.add(nextUserId);
1952            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1953                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1954            }
1955        }
1956    }
1957
1958    public static PackageManagerService main(Context context, Installer installer,
1959            boolean factoryTest, boolean onlyCore) {
1960        PackageManagerService m = new PackageManagerService(context, installer,
1961                factoryTest, onlyCore);
1962        m.enableSystemUserPackages();
1963        ServiceManager.addService("package", m);
1964        return m;
1965    }
1966
1967    private void enableSystemUserPackages() {
1968        if (!UserManager.isSplitSystemUser()) {
1969            return;
1970        }
1971        // For system user, enable apps based on the following conditions:
1972        // - app is whitelisted or belong to one of these groups:
1973        //   -- system app which has no launcher icons
1974        //   -- system app which has INTERACT_ACROSS_USERS permission
1975        //   -- system IME app
1976        // - app is not in the blacklist
1977        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1978        Set<String> enableApps = new ArraySet<>();
1979        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1980                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1981                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1982        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1983        enableApps.addAll(wlApps);
1984        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1985                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1986        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1987        enableApps.removeAll(blApps);
1988        Log.i(TAG, "Applications installed for system user: " + enableApps);
1989        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1990                UserHandle.SYSTEM);
1991        final int allAppsSize = allAps.size();
1992        synchronized (mPackages) {
1993            for (int i = 0; i < allAppsSize; i++) {
1994                String pName = allAps.get(i);
1995                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1996                // Should not happen, but we shouldn't be failing if it does
1997                if (pkgSetting == null) {
1998                    continue;
1999                }
2000                boolean install = enableApps.contains(pName);
2001                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2002                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2003                            + " for system user");
2004                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2005                }
2006            }
2007        }
2008    }
2009
2010    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2011        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2012                Context.DISPLAY_SERVICE);
2013        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2014    }
2015
2016    public PackageManagerService(Context context, Installer installer,
2017            boolean factoryTest, boolean onlyCore) {
2018        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2019                SystemClock.uptimeMillis());
2020
2021        if (mSdkVersion <= 0) {
2022            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2023        }
2024
2025        mContext = context;
2026        mFactoryTest = factoryTest;
2027        mOnlyCore = onlyCore;
2028        mMetrics = new DisplayMetrics();
2029        mSettings = new Settings(mPackages);
2030        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2031                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2032        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2033                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2034        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2035                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2036        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2037                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2038        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2039                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2040        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2041                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2042
2043        String separateProcesses = SystemProperties.get("debug.separate_processes");
2044        if (separateProcesses != null && separateProcesses.length() > 0) {
2045            if ("*".equals(separateProcesses)) {
2046                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2047                mSeparateProcesses = null;
2048                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2049            } else {
2050                mDefParseFlags = 0;
2051                mSeparateProcesses = separateProcesses.split(",");
2052                Slog.w(TAG, "Running with debug.separate_processes: "
2053                        + separateProcesses);
2054            }
2055        } else {
2056            mDefParseFlags = 0;
2057            mSeparateProcesses = null;
2058        }
2059
2060        mInstaller = installer;
2061        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2062                "*dexopt*");
2063        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2064
2065        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2066                FgThread.get().getLooper());
2067
2068        getDefaultDisplayMetrics(context, mMetrics);
2069
2070        SystemConfig systemConfig = SystemConfig.getInstance();
2071        mGlobalGids = systemConfig.getGlobalGids();
2072        mSystemPermissions = systemConfig.getSystemPermissions();
2073        mAvailableFeatures = systemConfig.getAvailableFeatures();
2074
2075        synchronized (mInstallLock) {
2076        // writer
2077        synchronized (mPackages) {
2078            mHandlerThread = new ServiceThread(TAG,
2079                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2080            mHandlerThread.start();
2081            mHandler = new PackageHandler(mHandlerThread.getLooper());
2082            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2083
2084            File dataDir = Environment.getDataDirectory();
2085            mAppInstallDir = new File(dataDir, "app");
2086            mAppLib32InstallDir = new File(dataDir, "app-lib");
2087            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2088            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2089            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2090
2091            sUserManager = new UserManagerService(context, this, mPackages);
2092
2093            // Propagate permission configuration in to package manager.
2094            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2095                    = systemConfig.getPermissions();
2096            for (int i=0; i<permConfig.size(); i++) {
2097                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2098                BasePermission bp = mSettings.mPermissions.get(perm.name);
2099                if (bp == null) {
2100                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2101                    mSettings.mPermissions.put(perm.name, bp);
2102                }
2103                if (perm.gids != null) {
2104                    bp.setGids(perm.gids, perm.perUser);
2105                }
2106            }
2107
2108            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2109            for (int i=0; i<libConfig.size(); i++) {
2110                mSharedLibraries.put(libConfig.keyAt(i),
2111                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2112            }
2113
2114            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2115
2116            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2117
2118            String customResolverActivity = Resources.getSystem().getString(
2119                    R.string.config_customResolverActivity);
2120            if (TextUtils.isEmpty(customResolverActivity)) {
2121                customResolverActivity = null;
2122            } else {
2123                mCustomResolverComponentName = ComponentName.unflattenFromString(
2124                        customResolverActivity);
2125            }
2126
2127            long startTime = SystemClock.uptimeMillis();
2128
2129            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2130                    startTime);
2131
2132            // Set flag to monitor and not change apk file paths when
2133            // scanning install directories.
2134            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2135
2136            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2137            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2138
2139            if (bootClassPath == null) {
2140                Slog.w(TAG, "No BOOTCLASSPATH found!");
2141            }
2142
2143            if (systemServerClassPath == null) {
2144                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2145            }
2146
2147            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2148            final String[] dexCodeInstructionSets =
2149                    getDexCodeInstructionSets(
2150                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2151
2152            /**
2153             * Ensure all external libraries have had dexopt run on them.
2154             */
2155            if (mSharedLibraries.size() > 0) {
2156                // NOTE: For now, we're compiling these system "shared libraries"
2157                // (and framework jars) into all available architectures. It's possible
2158                // to compile them only when we come across an app that uses them (there's
2159                // already logic for that in scanPackageLI) but that adds some complexity.
2160                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2161                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2162                        final String lib = libEntry.path;
2163                        if (lib == null) {
2164                            continue;
2165                        }
2166
2167                        try {
2168                            // Shared libraries do not have profiles so we perform a full
2169                            // AOT compilation (if needed).
2170                            int dexoptNeeded = DexFile.getDexOptNeeded(
2171                                    lib, dexCodeInstructionSet,
2172                                    DexFile.COMPILATION_TYPE_FULL);
2173                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2174                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2175                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2176                                        StorageManager.UUID_PRIVATE_INTERNAL,
2177                                        false /*useProfiles*/);
2178                            }
2179                        } catch (FileNotFoundException e) {
2180                            Slog.w(TAG, "Library not found: " + lib);
2181                        } catch (IOException | InstallerException e) {
2182                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2183                                    + e.getMessage());
2184                        }
2185                    }
2186                }
2187            }
2188
2189            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2190
2191            final VersionInfo ver = mSettings.getInternalVersion();
2192            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2193            // when upgrading from pre-M, promote system app permissions from install to runtime
2194            mPromoteSystemApps =
2195                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2196
2197            // save off the names of pre-existing system packages prior to scanning; we don't
2198            // want to automatically grant runtime permissions for new system apps
2199            if (mPromoteSystemApps) {
2200                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2201                while (pkgSettingIter.hasNext()) {
2202                    PackageSetting ps = pkgSettingIter.next();
2203                    if (isSystemApp(ps)) {
2204                        mExistingSystemPackages.add(ps.name);
2205                    }
2206                }
2207            }
2208
2209            // Collect vendor overlay packages.
2210            // (Do this before scanning any apps.)
2211            // For security and version matching reason, only consider
2212            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2213            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2214            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2215                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2216
2217            // Find base frameworks (resource packages without code).
2218            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2219                    | PackageParser.PARSE_IS_SYSTEM_DIR
2220                    | PackageParser.PARSE_IS_PRIVILEGED,
2221                    scanFlags | SCAN_NO_DEX, 0);
2222
2223            // Collected privileged system packages.
2224            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2225            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2226                    | PackageParser.PARSE_IS_SYSTEM_DIR
2227                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2228
2229            // Collect ordinary system packages.
2230            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2231            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2232                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2233
2234            // Collect all vendor packages.
2235            File vendorAppDir = new File("/vendor/app");
2236            try {
2237                vendorAppDir = vendorAppDir.getCanonicalFile();
2238            } catch (IOException e) {
2239                // failed to look up canonical path, continue with original one
2240            }
2241            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2242                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2243
2244            // Collect all OEM packages.
2245            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2246            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2247                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2248
2249            // Prune any system packages that no longer exist.
2250            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2251            if (!mOnlyCore) {
2252                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2253                while (psit.hasNext()) {
2254                    PackageSetting ps = psit.next();
2255
2256                    /*
2257                     * If this is not a system app, it can't be a
2258                     * disable system app.
2259                     */
2260                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2261                        continue;
2262                    }
2263
2264                    /*
2265                     * If the package is scanned, it's not erased.
2266                     */
2267                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2268                    if (scannedPkg != null) {
2269                        /*
2270                         * If the system app is both scanned and in the
2271                         * disabled packages list, then it must have been
2272                         * added via OTA. Remove it from the currently
2273                         * scanned package so the previously user-installed
2274                         * application can be scanned.
2275                         */
2276                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2277                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2278                                    + ps.name + "; removing system app.  Last known codePath="
2279                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2280                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2281                                    + scannedPkg.mVersionCode);
2282                            removePackageLI(scannedPkg, true);
2283                            mExpectingBetter.put(ps.name, ps.codePath);
2284                        }
2285
2286                        continue;
2287                    }
2288
2289                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2290                        psit.remove();
2291                        logCriticalInfo(Log.WARN, "System package " + ps.name
2292                                + " no longer exists; wiping its data");
2293                        removeDataDirsLI(null, ps.name);
2294                    } else {
2295                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2296                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2297                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2298                        }
2299                    }
2300                }
2301            }
2302
2303            //look for any incomplete package installations
2304            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2305            //clean up list
2306            for(int i = 0; i < deletePkgsList.size(); i++) {
2307                //clean up here
2308                cleanupInstallFailedPackage(deletePkgsList.get(i));
2309            }
2310            //delete tmp files
2311            deleteTempPackageFiles();
2312
2313            // Remove any shared userIDs that have no associated packages
2314            mSettings.pruneSharedUsersLPw();
2315
2316            if (!mOnlyCore) {
2317                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2318                        SystemClock.uptimeMillis());
2319                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2320
2321                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2322                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2323
2324                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2325                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2326
2327                /**
2328                 * Remove disable package settings for any updated system
2329                 * apps that were removed via an OTA. If they're not a
2330                 * previously-updated app, remove them completely.
2331                 * Otherwise, just revoke their system-level permissions.
2332                 */
2333                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2334                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2335                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2336
2337                    String msg;
2338                    if (deletedPkg == null) {
2339                        msg = "Updated system package " + deletedAppName
2340                                + " no longer exists; wiping its data";
2341                        removeDataDirsLI(null, deletedAppName);
2342                    } else {
2343                        msg = "Updated system app + " + deletedAppName
2344                                + " no longer present; removing system privileges for "
2345                                + deletedAppName;
2346
2347                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2348
2349                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2350                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2351                    }
2352                    logCriticalInfo(Log.WARN, msg);
2353                }
2354
2355                /**
2356                 * Make sure all system apps that we expected to appear on
2357                 * the userdata partition actually showed up. If they never
2358                 * appeared, crawl back and revive the system version.
2359                 */
2360                for (int i = 0; i < mExpectingBetter.size(); i++) {
2361                    final String packageName = mExpectingBetter.keyAt(i);
2362                    if (!mPackages.containsKey(packageName)) {
2363                        final File scanFile = mExpectingBetter.valueAt(i);
2364
2365                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2366                                + " but never showed up; reverting to system");
2367
2368                        final int reparseFlags;
2369                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2370                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2371                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2372                                    | PackageParser.PARSE_IS_PRIVILEGED;
2373                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2374                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2375                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2376                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2377                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2378                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2379                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2380                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2381                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2382                        } else {
2383                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2384                            continue;
2385                        }
2386
2387                        mSettings.enableSystemPackageLPw(packageName);
2388
2389                        try {
2390                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2391                        } catch (PackageManagerException e) {
2392                            Slog.e(TAG, "Failed to parse original system package: "
2393                                    + e.getMessage());
2394                        }
2395                    }
2396                }
2397            }
2398            mExpectingBetter.clear();
2399
2400            // Now that we know all of the shared libraries, update all clients to have
2401            // the correct library paths.
2402            updateAllSharedLibrariesLPw();
2403
2404            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2405                // NOTE: We ignore potential failures here during a system scan (like
2406                // the rest of the commands above) because there's precious little we
2407                // can do about it. A settings error is reported, though.
2408                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2409                        false /* boot complete */);
2410            }
2411
2412            // Now that we know all the packages we are keeping,
2413            // read and update their last usage times.
2414            mPackageUsage.readLP();
2415
2416            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2417                    SystemClock.uptimeMillis());
2418            Slog.i(TAG, "Time to scan packages: "
2419                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2420                    + " seconds");
2421
2422            // If the platform SDK has changed since the last time we booted,
2423            // we need to re-grant app permission to catch any new ones that
2424            // appear.  This is really a hack, and means that apps can in some
2425            // cases get permissions that the user didn't initially explicitly
2426            // allow...  it would be nice to have some better way to handle
2427            // this situation.
2428            int updateFlags = UPDATE_PERMISSIONS_ALL;
2429            if (ver.sdkVersion != mSdkVersion) {
2430                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2431                        + mSdkVersion + "; regranting permissions for internal storage");
2432                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2433            }
2434            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2435            ver.sdkVersion = mSdkVersion;
2436
2437            // If this is the first boot or an update from pre-M, and it is a normal
2438            // boot, then we need to initialize the default preferred apps across
2439            // all defined users.
2440            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2441                for (UserInfo user : sUserManager.getUsers(true)) {
2442                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2443                    applyFactoryDefaultBrowserLPw(user.id);
2444                    primeDomainVerificationsLPw(user.id);
2445                }
2446            }
2447
2448            // Prepare storage for system user really early during boot,
2449            // since core system apps like SettingsProvider and SystemUI
2450            // can't wait for user to start
2451            final int storageFlags;
2452            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2453                storageFlags = StorageManager.FLAG_STORAGE_DE;
2454            } else {
2455                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2456            }
2457            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2458                    storageFlags);
2459
2460            // If this is first boot after an OTA, and a normal boot, then
2461            // we need to clear code cache directories.
2462            if (mIsUpgrade && !onlyCore) {
2463                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2464                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2465                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2466                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2467                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2468                    }
2469                }
2470                ver.fingerprint = Build.FINGERPRINT;
2471            }
2472
2473            checkDefaultBrowser();
2474
2475            // clear only after permissions and other defaults have been updated
2476            mExistingSystemPackages.clear();
2477            mPromoteSystemApps = false;
2478
2479            // All the changes are done during package scanning.
2480            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2481
2482            // can downgrade to reader
2483            mSettings.writeLPr();
2484
2485            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2486                    SystemClock.uptimeMillis());
2487
2488            if (!mOnlyCore) {
2489                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2490                mRequiredInstallerPackage = getRequiredInstallerLPr();
2491                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2492                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2493                        mIntentFilterVerifierComponent);
2494            } else {
2495                mRequiredVerifierPackage = null;
2496                mRequiredInstallerPackage = null;
2497                mIntentFilterVerifierComponent = null;
2498                mIntentFilterVerifier = null;
2499            }
2500
2501            mInstallerService = new PackageInstallerService(context, this);
2502
2503            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2504            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2505            // both the installer and resolver must be present to enable ephemeral
2506            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2507                if (DEBUG_EPHEMERAL) {
2508                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2509                            + " installer:" + ephemeralInstallerComponent);
2510                }
2511                mEphemeralResolverComponent = ephemeralResolverComponent;
2512                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2513                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2514                mEphemeralResolverConnection =
2515                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2516            } else {
2517                if (DEBUG_EPHEMERAL) {
2518                    final String missingComponent =
2519                            (ephemeralResolverComponent == null)
2520                            ? (ephemeralInstallerComponent == null)
2521                                    ? "resolver and installer"
2522                                    : "resolver"
2523                            : "installer";
2524                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2525                }
2526                mEphemeralResolverComponent = null;
2527                mEphemeralInstallerComponent = null;
2528                mEphemeralResolverConnection = null;
2529            }
2530
2531            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2532        } // synchronized (mPackages)
2533        } // synchronized (mInstallLock)
2534
2535        // Now after opening every single application zip, make sure they
2536        // are all flushed.  Not really needed, but keeps things nice and
2537        // tidy.
2538        Runtime.getRuntime().gc();
2539
2540        // The initial scanning above does many calls into installd while
2541        // holding the mPackages lock, but we're mostly interested in yelling
2542        // once we have a booted system.
2543        mInstaller.setWarnIfHeld(mPackages);
2544
2545        // Expose private service for system components to use.
2546        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2547    }
2548
2549    @Override
2550    public boolean isFirstBoot() {
2551        return !mRestoredSettings;
2552    }
2553
2554    @Override
2555    public boolean isOnlyCoreApps() {
2556        return mOnlyCore;
2557    }
2558
2559    @Override
2560    public boolean isUpgrade() {
2561        return mIsUpgrade;
2562    }
2563
2564    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2565        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2566
2567        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2568                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2569        if (matches.size() == 1) {
2570            return matches.get(0).getComponentInfo().packageName;
2571        } else {
2572            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2573            return null;
2574        }
2575    }
2576
2577    private @NonNull String getRequiredInstallerLPr() {
2578        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2579        intent.addCategory(Intent.CATEGORY_DEFAULT);
2580        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2581
2582        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2583                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2584        if (matches.size() == 1) {
2585            return matches.get(0).getComponentInfo().packageName;
2586        } else {
2587            throw new RuntimeException("There must be exactly one installer; found " + matches);
2588        }
2589    }
2590
2591    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2592        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2593
2594        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2595                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2596        ResolveInfo best = null;
2597        final int N = matches.size();
2598        for (int i = 0; i < N; i++) {
2599            final ResolveInfo cur = matches.get(i);
2600            final String packageName = cur.getComponentInfo().packageName;
2601            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2602                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2603                continue;
2604            }
2605
2606            if (best == null || cur.priority > best.priority) {
2607                best = cur;
2608            }
2609        }
2610
2611        if (best != null) {
2612            return best.getComponentInfo().getComponentName();
2613        } else {
2614            throw new RuntimeException("There must be at least one intent filter verifier");
2615        }
2616    }
2617
2618    private @Nullable ComponentName getEphemeralResolverLPr() {
2619        final String[] packageArray =
2620                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2621        if (packageArray.length == 0) {
2622            if (DEBUG_EPHEMERAL) {
2623                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2624            }
2625            return null;
2626        }
2627
2628        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2629        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2630                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2631
2632        final int N = resolvers.size();
2633        if (N == 0) {
2634            if (DEBUG_EPHEMERAL) {
2635                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2636            }
2637            return null;
2638        }
2639
2640        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2641        for (int i = 0; i < N; i++) {
2642            final ResolveInfo info = resolvers.get(i);
2643
2644            if (info.serviceInfo == null) {
2645                continue;
2646            }
2647
2648            final String packageName = info.serviceInfo.packageName;
2649            if (!possiblePackages.contains(packageName)) {
2650                if (DEBUG_EPHEMERAL) {
2651                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2652                            + " pkg: " + packageName + ", info:" + info);
2653                }
2654                continue;
2655            }
2656
2657            if (DEBUG_EPHEMERAL) {
2658                Slog.v(TAG, "Ephemeral resolver found;"
2659                        + " pkg: " + packageName + ", info:" + info);
2660            }
2661            return new ComponentName(packageName, info.serviceInfo.name);
2662        }
2663        if (DEBUG_EPHEMERAL) {
2664            Slog.v(TAG, "Ephemeral resolver NOT found");
2665        }
2666        return null;
2667    }
2668
2669    private @Nullable ComponentName getEphemeralInstallerLPr() {
2670        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2671        intent.addCategory(Intent.CATEGORY_DEFAULT);
2672        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2673
2674        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2675                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2676        if (matches.size() == 0) {
2677            return null;
2678        } else if (matches.size() == 1) {
2679            return matches.get(0).getComponentInfo().getComponentName();
2680        } else {
2681            throw new RuntimeException(
2682                    "There must be at most one ephemeral installer; found " + matches);
2683        }
2684    }
2685
2686    private void primeDomainVerificationsLPw(int userId) {
2687        if (DEBUG_DOMAIN_VERIFICATION) {
2688            Slog.d(TAG, "Priming domain verifications in user " + userId);
2689        }
2690
2691        SystemConfig systemConfig = SystemConfig.getInstance();
2692        ArraySet<String> packages = systemConfig.getLinkedApps();
2693        ArraySet<String> domains = new ArraySet<String>();
2694
2695        for (String packageName : packages) {
2696            PackageParser.Package pkg = mPackages.get(packageName);
2697            if (pkg != null) {
2698                if (!pkg.isSystemApp()) {
2699                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2700                    continue;
2701                }
2702
2703                domains.clear();
2704                for (PackageParser.Activity a : pkg.activities) {
2705                    for (ActivityIntentInfo filter : a.intents) {
2706                        if (hasValidDomains(filter)) {
2707                            domains.addAll(filter.getHostsList());
2708                        }
2709                    }
2710                }
2711
2712                if (domains.size() > 0) {
2713                    if (DEBUG_DOMAIN_VERIFICATION) {
2714                        Slog.v(TAG, "      + " + packageName);
2715                    }
2716                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2717                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2718                    // and then 'always' in the per-user state actually used for intent resolution.
2719                    final IntentFilterVerificationInfo ivi;
2720                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2721                            new ArrayList<String>(domains));
2722                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2723                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2724                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2725                } else {
2726                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2727                            + "' does not handle web links");
2728                }
2729            } else {
2730                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2731            }
2732        }
2733
2734        scheduleWritePackageRestrictionsLocked(userId);
2735        scheduleWriteSettingsLocked();
2736    }
2737
2738    private void applyFactoryDefaultBrowserLPw(int userId) {
2739        // The default browser app's package name is stored in a string resource,
2740        // with a product-specific overlay used for vendor customization.
2741        String browserPkg = mContext.getResources().getString(
2742                com.android.internal.R.string.default_browser);
2743        if (!TextUtils.isEmpty(browserPkg)) {
2744            // non-empty string => required to be a known package
2745            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2746            if (ps == null) {
2747                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2748                browserPkg = null;
2749            } else {
2750                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2751            }
2752        }
2753
2754        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2755        // default.  If there's more than one, just leave everything alone.
2756        if (browserPkg == null) {
2757            calculateDefaultBrowserLPw(userId);
2758        }
2759    }
2760
2761    private void calculateDefaultBrowserLPw(int userId) {
2762        List<String> allBrowsers = resolveAllBrowserApps(userId);
2763        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2764        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2765    }
2766
2767    private List<String> resolveAllBrowserApps(int userId) {
2768        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2769        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2770                PackageManager.MATCH_ALL, userId);
2771
2772        final int count = list.size();
2773        List<String> result = new ArrayList<String>(count);
2774        for (int i=0; i<count; i++) {
2775            ResolveInfo info = list.get(i);
2776            if (info.activityInfo == null
2777                    || !info.handleAllWebDataURI
2778                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2779                    || result.contains(info.activityInfo.packageName)) {
2780                continue;
2781            }
2782            result.add(info.activityInfo.packageName);
2783        }
2784
2785        return result;
2786    }
2787
2788    private boolean packageIsBrowser(String packageName, int userId) {
2789        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2790                PackageManager.MATCH_ALL, userId);
2791        final int N = list.size();
2792        for (int i = 0; i < N; i++) {
2793            ResolveInfo info = list.get(i);
2794            if (packageName.equals(info.activityInfo.packageName)) {
2795                return true;
2796            }
2797        }
2798        return false;
2799    }
2800
2801    private void checkDefaultBrowser() {
2802        final int myUserId = UserHandle.myUserId();
2803        final String packageName = getDefaultBrowserPackageName(myUserId);
2804        if (packageName != null) {
2805            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2806            if (info == null) {
2807                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2808                synchronized (mPackages) {
2809                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2810                }
2811            }
2812        }
2813    }
2814
2815    @Override
2816    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2817            throws RemoteException {
2818        try {
2819            return super.onTransact(code, data, reply, flags);
2820        } catch (RuntimeException e) {
2821            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2822                Slog.wtf(TAG, "Package Manager Crash", e);
2823            }
2824            throw e;
2825        }
2826    }
2827
2828    void cleanupInstallFailedPackage(PackageSetting ps) {
2829        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2830
2831        removeDataDirsLI(ps.volumeUuid, ps.name);
2832        if (ps.codePath != null) {
2833            removeCodePathLI(ps.codePath);
2834        }
2835        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2836            if (ps.resourcePath.isDirectory()) {
2837                FileUtils.deleteContents(ps.resourcePath);
2838            }
2839            ps.resourcePath.delete();
2840        }
2841        mSettings.removePackageLPw(ps.name);
2842    }
2843
2844    static int[] appendInts(int[] cur, int[] add) {
2845        if (add == null) return cur;
2846        if (cur == null) return add;
2847        final int N = add.length;
2848        for (int i=0; i<N; i++) {
2849            cur = appendInt(cur, add[i]);
2850        }
2851        return cur;
2852    }
2853
2854    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2855        if (!sUserManager.exists(userId)) return null;
2856        final PackageSetting ps = (PackageSetting) p.mExtras;
2857        if (ps == null) {
2858            return null;
2859        }
2860
2861        final PermissionsState permissionsState = ps.getPermissionsState();
2862
2863        final int[] gids = permissionsState.computeGids(userId);
2864        final Set<String> permissions = permissionsState.getPermissions(userId);
2865        final PackageUserState state = ps.readUserState(userId);
2866
2867        return PackageParser.generatePackageInfo(p, gids, flags,
2868                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2869    }
2870
2871    @Override
2872    public void checkPackageStartable(String packageName, int userId) {
2873        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2874
2875        synchronized (mPackages) {
2876            final PackageSetting ps = mSettings.mPackages.get(packageName);
2877            if (ps == null) {
2878                throw new SecurityException("Package " + packageName + " was not found!");
2879            }
2880
2881            if (mSafeMode && !ps.isSystem()) {
2882                throw new SecurityException("Package " + packageName + " not a system app!");
2883            }
2884
2885            if (ps.frozen) {
2886                throw new SecurityException("Package " + packageName + " is currently frozen!");
2887            }
2888
2889            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2890                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2891                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2892            }
2893        }
2894    }
2895
2896    @Override
2897    public boolean isPackageAvailable(String packageName, int userId) {
2898        if (!sUserManager.exists(userId)) return false;
2899        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2900                false /* requireFullPermission */, false /* checkShell */, "is package available");
2901        synchronized (mPackages) {
2902            PackageParser.Package p = mPackages.get(packageName);
2903            if (p != null) {
2904                final PackageSetting ps = (PackageSetting) p.mExtras;
2905                if (ps != null) {
2906                    final PackageUserState state = ps.readUserState(userId);
2907                    if (state != null) {
2908                        return PackageParser.isAvailable(state);
2909                    }
2910                }
2911            }
2912        }
2913        return false;
2914    }
2915
2916    @Override
2917    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2918        if (!sUserManager.exists(userId)) return null;
2919        flags = updateFlagsForPackage(flags, userId, packageName);
2920        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2921                false /* requireFullPermission */, false /* checkShell */, "get package info");
2922        // reader
2923        synchronized (mPackages) {
2924            PackageParser.Package p = mPackages.get(packageName);
2925            if (DEBUG_PACKAGE_INFO)
2926                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2927            if (p != null) {
2928                return generatePackageInfo(p, flags, userId);
2929            }
2930            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2931                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2932            }
2933        }
2934        return null;
2935    }
2936
2937    @Override
2938    public String[] currentToCanonicalPackageNames(String[] names) {
2939        String[] out = new String[names.length];
2940        // reader
2941        synchronized (mPackages) {
2942            for (int i=names.length-1; i>=0; i--) {
2943                PackageSetting ps = mSettings.mPackages.get(names[i]);
2944                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2945            }
2946        }
2947        return out;
2948    }
2949
2950    @Override
2951    public String[] canonicalToCurrentPackageNames(String[] names) {
2952        String[] out = new String[names.length];
2953        // reader
2954        synchronized (mPackages) {
2955            for (int i=names.length-1; i>=0; i--) {
2956                String cur = mSettings.mRenamedPackages.get(names[i]);
2957                out[i] = cur != null ? cur : names[i];
2958            }
2959        }
2960        return out;
2961    }
2962
2963    @Override
2964    public int getPackageUid(String packageName, int flags, int userId) {
2965        if (!sUserManager.exists(userId)) return -1;
2966        flags = updateFlagsForPackage(flags, userId, packageName);
2967        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2968                false /* requireFullPermission */, false /* checkShell */, "get package uid");
2969
2970        // reader
2971        synchronized (mPackages) {
2972            final PackageParser.Package p = mPackages.get(packageName);
2973            if (p != null && p.isMatch(flags)) {
2974                return UserHandle.getUid(userId, p.applicationInfo.uid);
2975            }
2976            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2977                final PackageSetting ps = mSettings.mPackages.get(packageName);
2978                if (ps != null && ps.isMatch(flags)) {
2979                    return UserHandle.getUid(userId, ps.appId);
2980                }
2981            }
2982        }
2983
2984        return -1;
2985    }
2986
2987    @Override
2988    public int[] getPackageGids(String packageName, int flags, int userId) {
2989        if (!sUserManager.exists(userId)) return null;
2990        flags = updateFlagsForPackage(flags, userId, packageName);
2991        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2992                false /* requireFullPermission */, false /* checkShell */,
2993                "getPackageGids");
2994
2995        // reader
2996        synchronized (mPackages) {
2997            final PackageParser.Package p = mPackages.get(packageName);
2998            if (p != null && p.isMatch(flags)) {
2999                PackageSetting ps = (PackageSetting) p.mExtras;
3000                return ps.getPermissionsState().computeGids(userId);
3001            }
3002            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3003                final PackageSetting ps = mSettings.mPackages.get(packageName);
3004                if (ps != null && ps.isMatch(flags)) {
3005                    return ps.getPermissionsState().computeGids(userId);
3006                }
3007            }
3008        }
3009
3010        return null;
3011    }
3012
3013    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3014        if (bp.perm != null) {
3015            return PackageParser.generatePermissionInfo(bp.perm, flags);
3016        }
3017        PermissionInfo pi = new PermissionInfo();
3018        pi.name = bp.name;
3019        pi.packageName = bp.sourcePackage;
3020        pi.nonLocalizedLabel = bp.name;
3021        pi.protectionLevel = bp.protectionLevel;
3022        return pi;
3023    }
3024
3025    @Override
3026    public PermissionInfo getPermissionInfo(String name, int flags) {
3027        // reader
3028        synchronized (mPackages) {
3029            final BasePermission p = mSettings.mPermissions.get(name);
3030            if (p != null) {
3031                return generatePermissionInfo(p, flags);
3032            }
3033            return null;
3034        }
3035    }
3036
3037    @Override
3038    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3039            int flags) {
3040        // reader
3041        synchronized (mPackages) {
3042            if (group != null && !mPermissionGroups.containsKey(group)) {
3043                // This is thrown as NameNotFoundException
3044                return null;
3045            }
3046
3047            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3048            for (BasePermission p : mSettings.mPermissions.values()) {
3049                if (group == null) {
3050                    if (p.perm == null || p.perm.info.group == null) {
3051                        out.add(generatePermissionInfo(p, flags));
3052                    }
3053                } else {
3054                    if (p.perm != null && group.equals(p.perm.info.group)) {
3055                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3056                    }
3057                }
3058            }
3059            return new ParceledListSlice<>(out);
3060        }
3061    }
3062
3063    @Override
3064    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3065        // reader
3066        synchronized (mPackages) {
3067            return PackageParser.generatePermissionGroupInfo(
3068                    mPermissionGroups.get(name), flags);
3069        }
3070    }
3071
3072    @Override
3073    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3074        // reader
3075        synchronized (mPackages) {
3076            final int N = mPermissionGroups.size();
3077            ArrayList<PermissionGroupInfo> out
3078                    = new ArrayList<PermissionGroupInfo>(N);
3079            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3080                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3081            }
3082            return new ParceledListSlice<>(out);
3083        }
3084    }
3085
3086    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3087            int userId) {
3088        if (!sUserManager.exists(userId)) return null;
3089        PackageSetting ps = mSettings.mPackages.get(packageName);
3090        if (ps != null) {
3091            if (ps.pkg == null) {
3092                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3093                        flags, userId);
3094                if (pInfo != null) {
3095                    return pInfo.applicationInfo;
3096                }
3097                return null;
3098            }
3099            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3100                    ps.readUserState(userId), userId);
3101        }
3102        return null;
3103    }
3104
3105    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3106            int userId) {
3107        if (!sUserManager.exists(userId)) return null;
3108        PackageSetting ps = mSettings.mPackages.get(packageName);
3109        if (ps != null) {
3110            PackageParser.Package pkg = ps.pkg;
3111            if (pkg == null) {
3112                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3113                    return null;
3114                }
3115                // Only data remains, so we aren't worried about code paths
3116                pkg = new PackageParser.Package(packageName);
3117                pkg.applicationInfo.packageName = packageName;
3118                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3119                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3120                pkg.applicationInfo.uid = ps.appId;
3121                pkg.applicationInfo.initForUser(userId);
3122                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3123                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3124            }
3125            return generatePackageInfo(pkg, flags, userId);
3126        }
3127        return null;
3128    }
3129
3130    @Override
3131    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3132        if (!sUserManager.exists(userId)) return null;
3133        flags = updateFlagsForApplication(flags, userId, packageName);
3134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3135                false /* requireFullPermission */, false /* checkShell */, "get application info");
3136        // writer
3137        synchronized (mPackages) {
3138            PackageParser.Package p = mPackages.get(packageName);
3139            if (DEBUG_PACKAGE_INFO) Log.v(
3140                    TAG, "getApplicationInfo " + packageName
3141                    + ": " + p);
3142            if (p != null) {
3143                PackageSetting ps = mSettings.mPackages.get(packageName);
3144                if (ps == null) return null;
3145                // Note: isEnabledLP() does not apply here - always return info
3146                return PackageParser.generateApplicationInfo(
3147                        p, flags, ps.readUserState(userId), userId);
3148            }
3149            if ("android".equals(packageName)||"system".equals(packageName)) {
3150                return mAndroidApplication;
3151            }
3152            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3153                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3154            }
3155        }
3156        return null;
3157    }
3158
3159    @Override
3160    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3161            final IPackageDataObserver observer) {
3162        mContext.enforceCallingOrSelfPermission(
3163                android.Manifest.permission.CLEAR_APP_CACHE, null);
3164        // Queue up an async operation since clearing cache may take a little while.
3165        mHandler.post(new Runnable() {
3166            public void run() {
3167                mHandler.removeCallbacks(this);
3168                boolean success = true;
3169                synchronized (mInstallLock) {
3170                    try {
3171                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3172                    } catch (InstallerException e) {
3173                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3174                        success = false;
3175                    }
3176                }
3177                if (observer != null) {
3178                    try {
3179                        observer.onRemoveCompleted(null, success);
3180                    } catch (RemoteException e) {
3181                        Slog.w(TAG, "RemoveException when invoking call back");
3182                    }
3183                }
3184            }
3185        });
3186    }
3187
3188    @Override
3189    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3190            final IntentSender pi) {
3191        mContext.enforceCallingOrSelfPermission(
3192                android.Manifest.permission.CLEAR_APP_CACHE, null);
3193        // Queue up an async operation since clearing cache may take a little while.
3194        mHandler.post(new Runnable() {
3195            public void run() {
3196                mHandler.removeCallbacks(this);
3197                boolean success = true;
3198                synchronized (mInstallLock) {
3199                    try {
3200                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3201                    } catch (InstallerException e) {
3202                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3203                        success = false;
3204                    }
3205                }
3206                if(pi != null) {
3207                    try {
3208                        // Callback via pending intent
3209                        int code = success ? 1 : 0;
3210                        pi.sendIntent(null, code, null,
3211                                null, null);
3212                    } catch (SendIntentException e1) {
3213                        Slog.i(TAG, "Failed to send pending intent");
3214                    }
3215                }
3216            }
3217        });
3218    }
3219
3220    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3221        synchronized (mInstallLock) {
3222            try {
3223                mInstaller.freeCache(volumeUuid, freeStorageSize);
3224            } catch (InstallerException e) {
3225                throw new IOException("Failed to free enough space", e);
3226            }
3227        }
3228    }
3229
3230    /**
3231     * Return if the user key is currently unlocked.
3232     */
3233    private boolean isUserKeyUnlocked(int userId) {
3234        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3235            final IMountService mount = IMountService.Stub
3236                    .asInterface(ServiceManager.getService("mount"));
3237            if (mount == null) {
3238                Slog.w(TAG, "Early during boot, assuming locked");
3239                return false;
3240            }
3241            final long token = Binder.clearCallingIdentity();
3242            try {
3243                return mount.isUserKeyUnlocked(userId);
3244            } catch (RemoteException e) {
3245                throw e.rethrowAsRuntimeException();
3246            } finally {
3247                Binder.restoreCallingIdentity(token);
3248            }
3249        } else {
3250            return true;
3251        }
3252    }
3253
3254    /**
3255     * Update given flags based on encryption status of current user.
3256     */
3257    private int updateFlags(int flags, int userId) {
3258        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3259                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3260            // Caller expressed an explicit opinion about what encryption
3261            // aware/unaware components they want to see, so fall through and
3262            // give them what they want
3263        } else {
3264            // Caller expressed no opinion, so match based on user state
3265            if (isUserKeyUnlocked(userId)) {
3266                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3267            } else {
3268                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3269            }
3270        }
3271        return flags;
3272    }
3273
3274    /**
3275     * Update given flags when being used to request {@link PackageInfo}.
3276     */
3277    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3278        boolean triaged = true;
3279        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3280                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3281            // Caller is asking for component details, so they'd better be
3282            // asking for specific encryption matching behavior, or be triaged
3283            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3284                    | PackageManager.MATCH_ENCRYPTION_AWARE
3285                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3286                triaged = false;
3287            }
3288        }
3289        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3290                | PackageManager.MATCH_SYSTEM_ONLY
3291                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3292            triaged = false;
3293        }
3294        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3295            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3296                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3297        }
3298        return updateFlags(flags, userId);
3299    }
3300
3301    /**
3302     * Update given flags when being used to request {@link ApplicationInfo}.
3303     */
3304    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3305        return updateFlagsForPackage(flags, userId, cookie);
3306    }
3307
3308    /**
3309     * Update given flags when being used to request {@link ComponentInfo}.
3310     */
3311    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3312        if (cookie instanceof Intent) {
3313            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3314                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3315            }
3316        }
3317
3318        boolean triaged = true;
3319        // Caller is asking for component details, so they'd better be
3320        // asking for specific encryption matching behavior, or be triaged
3321        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3322                | PackageManager.MATCH_ENCRYPTION_AWARE
3323                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3324            triaged = false;
3325        }
3326        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3327            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3328                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3329        }
3330
3331        return updateFlags(flags, userId);
3332    }
3333
3334    /**
3335     * Update given flags when being used to request {@link ResolveInfo}.
3336     */
3337    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3338        // Safe mode means we shouldn't match any third-party components
3339        if (mSafeMode) {
3340            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3341        }
3342
3343        return updateFlagsForComponent(flags, userId, cookie);
3344    }
3345
3346    @Override
3347    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3348        if (!sUserManager.exists(userId)) return null;
3349        flags = updateFlagsForComponent(flags, userId, component);
3350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3351                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3352        synchronized (mPackages) {
3353            PackageParser.Activity a = mActivities.mActivities.get(component);
3354
3355            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3356            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3357                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3358                if (ps == null) return null;
3359                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3360                        userId);
3361            }
3362            if (mResolveComponentName.equals(component)) {
3363                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3364                        new PackageUserState(), userId);
3365            }
3366        }
3367        return null;
3368    }
3369
3370    @Override
3371    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3372            String resolvedType) {
3373        synchronized (mPackages) {
3374            if (component.equals(mResolveComponentName)) {
3375                // The resolver supports EVERYTHING!
3376                return true;
3377            }
3378            PackageParser.Activity a = mActivities.mActivities.get(component);
3379            if (a == null) {
3380                return false;
3381            }
3382            for (int i=0; i<a.intents.size(); i++) {
3383                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3384                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3385                    return true;
3386                }
3387            }
3388            return false;
3389        }
3390    }
3391
3392    @Override
3393    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3394        if (!sUserManager.exists(userId)) return null;
3395        flags = updateFlagsForComponent(flags, userId, component);
3396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3397                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3398        synchronized (mPackages) {
3399            PackageParser.Activity a = mReceivers.mActivities.get(component);
3400            if (DEBUG_PACKAGE_INFO) Log.v(
3401                TAG, "getReceiverInfo " + component + ": " + a);
3402            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3403                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3404                if (ps == null) return null;
3405                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3406                        userId);
3407            }
3408        }
3409        return null;
3410    }
3411
3412    @Override
3413    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3414        if (!sUserManager.exists(userId)) return null;
3415        flags = updateFlagsForComponent(flags, userId, component);
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3417                false /* requireFullPermission */, false /* checkShell */, "get service info");
3418        synchronized (mPackages) {
3419            PackageParser.Service s = mServices.mServices.get(component);
3420            if (DEBUG_PACKAGE_INFO) Log.v(
3421                TAG, "getServiceInfo " + component + ": " + s);
3422            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3423                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3424                if (ps == null) return null;
3425                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3426                        userId);
3427            }
3428        }
3429        return null;
3430    }
3431
3432    @Override
3433    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3434        if (!sUserManager.exists(userId)) return null;
3435        flags = updateFlagsForComponent(flags, userId, component);
3436        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3437                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3438        synchronized (mPackages) {
3439            PackageParser.Provider p = mProviders.mProviders.get(component);
3440            if (DEBUG_PACKAGE_INFO) Log.v(
3441                TAG, "getProviderInfo " + component + ": " + p);
3442            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3443                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3444                if (ps == null) return null;
3445                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3446                        userId);
3447            }
3448        }
3449        return null;
3450    }
3451
3452    @Override
3453    public String[] getSystemSharedLibraryNames() {
3454        Set<String> libSet;
3455        synchronized (mPackages) {
3456            libSet = mSharedLibraries.keySet();
3457            int size = libSet.size();
3458            if (size > 0) {
3459                String[] libs = new String[size];
3460                libSet.toArray(libs);
3461                return libs;
3462            }
3463        }
3464        return null;
3465    }
3466
3467    @Override
3468    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3469        synchronized (mPackages) {
3470            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3471                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3472            if (libraryEntry != null) {
3473                return libraryEntry.apk;
3474            }
3475        }
3476        return null;
3477    }
3478
3479    @Override
3480    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3481        synchronized (mPackages) {
3482            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3483
3484            final FeatureInfo fi = new FeatureInfo();
3485            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3486                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3487            res.add(fi);
3488
3489            return new ParceledListSlice<>(res);
3490        }
3491    }
3492
3493    @Override
3494    public boolean hasSystemFeature(String name, int version) {
3495        synchronized (mPackages) {
3496            final FeatureInfo feat = mAvailableFeatures.get(name);
3497            if (feat == null) {
3498                return false;
3499            } else {
3500                return feat.version >= version;
3501            }
3502        }
3503    }
3504
3505    @Override
3506    public int checkPermission(String permName, String pkgName, int userId) {
3507        if (!sUserManager.exists(userId)) {
3508            return PackageManager.PERMISSION_DENIED;
3509        }
3510
3511        synchronized (mPackages) {
3512            final PackageParser.Package p = mPackages.get(pkgName);
3513            if (p != null && p.mExtras != null) {
3514                final PackageSetting ps = (PackageSetting) p.mExtras;
3515                final PermissionsState permissionsState = ps.getPermissionsState();
3516                if (permissionsState.hasPermission(permName, userId)) {
3517                    return PackageManager.PERMISSION_GRANTED;
3518                }
3519                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3520                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3521                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3522                    return PackageManager.PERMISSION_GRANTED;
3523                }
3524            }
3525        }
3526
3527        return PackageManager.PERMISSION_DENIED;
3528    }
3529
3530    @Override
3531    public int checkUidPermission(String permName, int uid) {
3532        final int userId = UserHandle.getUserId(uid);
3533
3534        if (!sUserManager.exists(userId)) {
3535            return PackageManager.PERMISSION_DENIED;
3536        }
3537
3538        synchronized (mPackages) {
3539            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3540            if (obj != null) {
3541                final SettingBase ps = (SettingBase) obj;
3542                final PermissionsState permissionsState = ps.getPermissionsState();
3543                if (permissionsState.hasPermission(permName, userId)) {
3544                    return PackageManager.PERMISSION_GRANTED;
3545                }
3546                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3547                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3548                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3549                    return PackageManager.PERMISSION_GRANTED;
3550                }
3551            } else {
3552                ArraySet<String> perms = mSystemPermissions.get(uid);
3553                if (perms != null) {
3554                    if (perms.contains(permName)) {
3555                        return PackageManager.PERMISSION_GRANTED;
3556                    }
3557                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3558                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3559                        return PackageManager.PERMISSION_GRANTED;
3560                    }
3561                }
3562            }
3563        }
3564
3565        return PackageManager.PERMISSION_DENIED;
3566    }
3567
3568    @Override
3569    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3570        if (UserHandle.getCallingUserId() != userId) {
3571            mContext.enforceCallingPermission(
3572                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3573                    "isPermissionRevokedByPolicy for user " + userId);
3574        }
3575
3576        if (checkPermission(permission, packageName, userId)
3577                == PackageManager.PERMISSION_GRANTED) {
3578            return false;
3579        }
3580
3581        final long identity = Binder.clearCallingIdentity();
3582        try {
3583            final int flags = getPermissionFlags(permission, packageName, userId);
3584            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3585        } finally {
3586            Binder.restoreCallingIdentity(identity);
3587        }
3588    }
3589
3590    @Override
3591    public String getPermissionControllerPackageName() {
3592        synchronized (mPackages) {
3593            return mRequiredInstallerPackage;
3594        }
3595    }
3596
3597    /**
3598     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3599     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3600     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3601     * @param message the message to log on security exception
3602     */
3603    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3604            boolean checkShell, String message) {
3605        if (userId < 0) {
3606            throw new IllegalArgumentException("Invalid userId " + userId);
3607        }
3608        if (checkShell) {
3609            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3610        }
3611        if (userId == UserHandle.getUserId(callingUid)) return;
3612        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3613            if (requireFullPermission) {
3614                mContext.enforceCallingOrSelfPermission(
3615                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3616            } else {
3617                try {
3618                    mContext.enforceCallingOrSelfPermission(
3619                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3620                } catch (SecurityException se) {
3621                    mContext.enforceCallingOrSelfPermission(
3622                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3623                }
3624            }
3625        }
3626    }
3627
3628    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3629        if (callingUid == Process.SHELL_UID) {
3630            if (userHandle >= 0
3631                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3632                throw new SecurityException("Shell does not have permission to access user "
3633                        + userHandle);
3634            } else if (userHandle < 0) {
3635                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3636                        + Debug.getCallers(3));
3637            }
3638        }
3639    }
3640
3641    private BasePermission findPermissionTreeLP(String permName) {
3642        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3643            if (permName.startsWith(bp.name) &&
3644                    permName.length() > bp.name.length() &&
3645                    permName.charAt(bp.name.length()) == '.') {
3646                return bp;
3647            }
3648        }
3649        return null;
3650    }
3651
3652    private BasePermission checkPermissionTreeLP(String permName) {
3653        if (permName != null) {
3654            BasePermission bp = findPermissionTreeLP(permName);
3655            if (bp != null) {
3656                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3657                    return bp;
3658                }
3659                throw new SecurityException("Calling uid "
3660                        + Binder.getCallingUid()
3661                        + " is not allowed to add to permission tree "
3662                        + bp.name + " owned by uid " + bp.uid);
3663            }
3664        }
3665        throw new SecurityException("No permission tree found for " + permName);
3666    }
3667
3668    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3669        if (s1 == null) {
3670            return s2 == null;
3671        }
3672        if (s2 == null) {
3673            return false;
3674        }
3675        if (s1.getClass() != s2.getClass()) {
3676            return false;
3677        }
3678        return s1.equals(s2);
3679    }
3680
3681    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3682        if (pi1.icon != pi2.icon) return false;
3683        if (pi1.logo != pi2.logo) return false;
3684        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3685        if (!compareStrings(pi1.name, pi2.name)) return false;
3686        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3687        // We'll take care of setting this one.
3688        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3689        // These are not currently stored in settings.
3690        //if (!compareStrings(pi1.group, pi2.group)) return false;
3691        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3692        //if (pi1.labelRes != pi2.labelRes) return false;
3693        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3694        return true;
3695    }
3696
3697    int permissionInfoFootprint(PermissionInfo info) {
3698        int size = info.name.length();
3699        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3700        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3701        return size;
3702    }
3703
3704    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3705        int size = 0;
3706        for (BasePermission perm : mSettings.mPermissions.values()) {
3707            if (perm.uid == tree.uid) {
3708                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3709            }
3710        }
3711        return size;
3712    }
3713
3714    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3715        // We calculate the max size of permissions defined by this uid and throw
3716        // if that plus the size of 'info' would exceed our stated maximum.
3717        if (tree.uid != Process.SYSTEM_UID) {
3718            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3719            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3720                throw new SecurityException("Permission tree size cap exceeded");
3721            }
3722        }
3723    }
3724
3725    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3726        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3727            throw new SecurityException("Label must be specified in permission");
3728        }
3729        BasePermission tree = checkPermissionTreeLP(info.name);
3730        BasePermission bp = mSettings.mPermissions.get(info.name);
3731        boolean added = bp == null;
3732        boolean changed = true;
3733        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3734        if (added) {
3735            enforcePermissionCapLocked(info, tree);
3736            bp = new BasePermission(info.name, tree.sourcePackage,
3737                    BasePermission.TYPE_DYNAMIC);
3738        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3739            throw new SecurityException(
3740                    "Not allowed to modify non-dynamic permission "
3741                    + info.name);
3742        } else {
3743            if (bp.protectionLevel == fixedLevel
3744                    && bp.perm.owner.equals(tree.perm.owner)
3745                    && bp.uid == tree.uid
3746                    && comparePermissionInfos(bp.perm.info, info)) {
3747                changed = false;
3748            }
3749        }
3750        bp.protectionLevel = fixedLevel;
3751        info = new PermissionInfo(info);
3752        info.protectionLevel = fixedLevel;
3753        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3754        bp.perm.info.packageName = tree.perm.info.packageName;
3755        bp.uid = tree.uid;
3756        if (added) {
3757            mSettings.mPermissions.put(info.name, bp);
3758        }
3759        if (changed) {
3760            if (!async) {
3761                mSettings.writeLPr();
3762            } else {
3763                scheduleWriteSettingsLocked();
3764            }
3765        }
3766        return added;
3767    }
3768
3769    @Override
3770    public boolean addPermission(PermissionInfo info) {
3771        synchronized (mPackages) {
3772            return addPermissionLocked(info, false);
3773        }
3774    }
3775
3776    @Override
3777    public boolean addPermissionAsync(PermissionInfo info) {
3778        synchronized (mPackages) {
3779            return addPermissionLocked(info, true);
3780        }
3781    }
3782
3783    @Override
3784    public void removePermission(String name) {
3785        synchronized (mPackages) {
3786            checkPermissionTreeLP(name);
3787            BasePermission bp = mSettings.mPermissions.get(name);
3788            if (bp != null) {
3789                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3790                    throw new SecurityException(
3791                            "Not allowed to modify non-dynamic permission "
3792                            + name);
3793                }
3794                mSettings.mPermissions.remove(name);
3795                mSettings.writeLPr();
3796            }
3797        }
3798    }
3799
3800    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3801            BasePermission bp) {
3802        int index = pkg.requestedPermissions.indexOf(bp.name);
3803        if (index == -1) {
3804            throw new SecurityException("Package " + pkg.packageName
3805                    + " has not requested permission " + bp.name);
3806        }
3807        if (!bp.isRuntime() && !bp.isDevelopment()) {
3808            throw new SecurityException("Permission " + bp.name
3809                    + " is not a changeable permission type");
3810        }
3811    }
3812
3813    @Override
3814    public void grantRuntimePermission(String packageName, String name, final int userId) {
3815        if (!sUserManager.exists(userId)) {
3816            Log.e(TAG, "No such user:" + userId);
3817            return;
3818        }
3819
3820        mContext.enforceCallingOrSelfPermission(
3821                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3822                "grantRuntimePermission");
3823
3824        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3825                true /* requireFullPermission */, true /* checkShell */,
3826                "grantRuntimePermission");
3827
3828        final int uid;
3829        final SettingBase sb;
3830
3831        synchronized (mPackages) {
3832            final PackageParser.Package pkg = mPackages.get(packageName);
3833            if (pkg == null) {
3834                throw new IllegalArgumentException("Unknown package: " + packageName);
3835            }
3836
3837            final BasePermission bp = mSettings.mPermissions.get(name);
3838            if (bp == null) {
3839                throw new IllegalArgumentException("Unknown permission: " + name);
3840            }
3841
3842            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3843
3844            // If a permission review is required for legacy apps we represent
3845            // their permissions as always granted runtime ones since we need
3846            // to keep the review required permission flag per user while an
3847            // install permission's state is shared across all users.
3848            if (Build.PERMISSIONS_REVIEW_REQUIRED
3849                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3850                    && bp.isRuntime()) {
3851                return;
3852            }
3853
3854            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3855            sb = (SettingBase) pkg.mExtras;
3856            if (sb == null) {
3857                throw new IllegalArgumentException("Unknown package: " + packageName);
3858            }
3859
3860            final PermissionsState permissionsState = sb.getPermissionsState();
3861
3862            final int flags = permissionsState.getPermissionFlags(name, userId);
3863            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3864                throw new SecurityException("Cannot grant system fixed permission "
3865                        + name + " for package " + packageName);
3866            }
3867
3868            if (bp.isDevelopment()) {
3869                // Development permissions must be handled specially, since they are not
3870                // normal runtime permissions.  For now they apply to all users.
3871                if (permissionsState.grantInstallPermission(bp) !=
3872                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3873                    scheduleWriteSettingsLocked();
3874                }
3875                return;
3876            }
3877
3878            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3879                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3880                return;
3881            }
3882
3883            final int result = permissionsState.grantRuntimePermission(bp, userId);
3884            switch (result) {
3885                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3886                    return;
3887                }
3888
3889                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3890                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3891                    mHandler.post(new Runnable() {
3892                        @Override
3893                        public void run() {
3894                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3895                        }
3896                    });
3897                }
3898                break;
3899            }
3900
3901            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3902
3903            // Not critical if that is lost - app has to request again.
3904            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3905        }
3906
3907        // Only need to do this if user is initialized. Otherwise it's a new user
3908        // and there are no processes running as the user yet and there's no need
3909        // to make an expensive call to remount processes for the changed permissions.
3910        if (READ_EXTERNAL_STORAGE.equals(name)
3911                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3912            final long token = Binder.clearCallingIdentity();
3913            try {
3914                if (sUserManager.isInitialized(userId)) {
3915                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3916                            MountServiceInternal.class);
3917                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3918                }
3919            } finally {
3920                Binder.restoreCallingIdentity(token);
3921            }
3922        }
3923    }
3924
3925    @Override
3926    public void revokeRuntimePermission(String packageName, String name, int userId) {
3927        if (!sUserManager.exists(userId)) {
3928            Log.e(TAG, "No such user:" + userId);
3929            return;
3930        }
3931
3932        mContext.enforceCallingOrSelfPermission(
3933                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3934                "revokeRuntimePermission");
3935
3936        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3937                true /* requireFullPermission */, true /* checkShell */,
3938                "revokeRuntimePermission");
3939
3940        final int appId;
3941
3942        synchronized (mPackages) {
3943            final PackageParser.Package pkg = mPackages.get(packageName);
3944            if (pkg == null) {
3945                throw new IllegalArgumentException("Unknown package: " + packageName);
3946            }
3947
3948            final BasePermission bp = mSettings.mPermissions.get(name);
3949            if (bp == null) {
3950                throw new IllegalArgumentException("Unknown permission: " + name);
3951            }
3952
3953            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3954
3955            // If a permission review is required for legacy apps we represent
3956            // their permissions as always granted runtime ones since we need
3957            // to keep the review required permission flag per user while an
3958            // install permission's state is shared across all users.
3959            if (Build.PERMISSIONS_REVIEW_REQUIRED
3960                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3961                    && bp.isRuntime()) {
3962                return;
3963            }
3964
3965            SettingBase sb = (SettingBase) pkg.mExtras;
3966            if (sb == null) {
3967                throw new IllegalArgumentException("Unknown package: " + packageName);
3968            }
3969
3970            final PermissionsState permissionsState = sb.getPermissionsState();
3971
3972            final int flags = permissionsState.getPermissionFlags(name, userId);
3973            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3974                throw new SecurityException("Cannot revoke system fixed permission "
3975                        + name + " for package " + packageName);
3976            }
3977
3978            if (bp.isDevelopment()) {
3979                // Development permissions must be handled specially, since they are not
3980                // normal runtime permissions.  For now they apply to all users.
3981                if (permissionsState.revokeInstallPermission(bp) !=
3982                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3983                    scheduleWriteSettingsLocked();
3984                }
3985                return;
3986            }
3987
3988            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3989                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3990                return;
3991            }
3992
3993            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3994
3995            // Critical, after this call app should never have the permission.
3996            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3997
3998            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3999        }
4000
4001        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4002    }
4003
4004    @Override
4005    public void resetRuntimePermissions() {
4006        mContext.enforceCallingOrSelfPermission(
4007                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4008                "revokeRuntimePermission");
4009
4010        int callingUid = Binder.getCallingUid();
4011        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4012            mContext.enforceCallingOrSelfPermission(
4013                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4014                    "resetRuntimePermissions");
4015        }
4016
4017        synchronized (mPackages) {
4018            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4019            for (int userId : UserManagerService.getInstance().getUserIds()) {
4020                final int packageCount = mPackages.size();
4021                for (int i = 0; i < packageCount; i++) {
4022                    PackageParser.Package pkg = mPackages.valueAt(i);
4023                    if (!(pkg.mExtras instanceof PackageSetting)) {
4024                        continue;
4025                    }
4026                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4027                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4028                }
4029            }
4030        }
4031    }
4032
4033    @Override
4034    public int getPermissionFlags(String name, String packageName, int userId) {
4035        if (!sUserManager.exists(userId)) {
4036            return 0;
4037        }
4038
4039        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4040
4041        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4042                true /* requireFullPermission */, false /* checkShell */,
4043                "getPermissionFlags");
4044
4045        synchronized (mPackages) {
4046            final PackageParser.Package pkg = mPackages.get(packageName);
4047            if (pkg == null) {
4048                throw new IllegalArgumentException("Unknown package: " + packageName);
4049            }
4050
4051            final BasePermission bp = mSettings.mPermissions.get(name);
4052            if (bp == null) {
4053                throw new IllegalArgumentException("Unknown permission: " + name);
4054            }
4055
4056            SettingBase sb = (SettingBase) pkg.mExtras;
4057            if (sb == null) {
4058                throw new IllegalArgumentException("Unknown package: " + packageName);
4059            }
4060
4061            PermissionsState permissionsState = sb.getPermissionsState();
4062            return permissionsState.getPermissionFlags(name, userId);
4063        }
4064    }
4065
4066    @Override
4067    public void updatePermissionFlags(String name, String packageName, int flagMask,
4068            int flagValues, int userId) {
4069        if (!sUserManager.exists(userId)) {
4070            return;
4071        }
4072
4073        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4074
4075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4076                true /* requireFullPermission */, true /* checkShell */,
4077                "updatePermissionFlags");
4078
4079        // Only the system can change these flags and nothing else.
4080        if (getCallingUid() != Process.SYSTEM_UID) {
4081            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4082            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4083            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4084            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4085            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4086        }
4087
4088        synchronized (mPackages) {
4089            final PackageParser.Package pkg = mPackages.get(packageName);
4090            if (pkg == null) {
4091                throw new IllegalArgumentException("Unknown package: " + packageName);
4092            }
4093
4094            final BasePermission bp = mSettings.mPermissions.get(name);
4095            if (bp == null) {
4096                throw new IllegalArgumentException("Unknown permission: " + name);
4097            }
4098
4099            SettingBase sb = (SettingBase) pkg.mExtras;
4100            if (sb == null) {
4101                throw new IllegalArgumentException("Unknown package: " + packageName);
4102            }
4103
4104            PermissionsState permissionsState = sb.getPermissionsState();
4105
4106            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4107
4108            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4109                // Install and runtime permissions are stored in different places,
4110                // so figure out what permission changed and persist the change.
4111                if (permissionsState.getInstallPermissionState(name) != null) {
4112                    scheduleWriteSettingsLocked();
4113                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4114                        || hadState) {
4115                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4116                }
4117            }
4118        }
4119    }
4120
4121    /**
4122     * Update the permission flags for all packages and runtime permissions of a user in order
4123     * to allow device or profile owner to remove POLICY_FIXED.
4124     */
4125    @Override
4126    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4127        if (!sUserManager.exists(userId)) {
4128            return;
4129        }
4130
4131        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4132
4133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4134                true /* requireFullPermission */, true /* checkShell */,
4135                "updatePermissionFlagsForAllApps");
4136
4137        // Only the system can change system fixed flags.
4138        if (getCallingUid() != Process.SYSTEM_UID) {
4139            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4140            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4141        }
4142
4143        synchronized (mPackages) {
4144            boolean changed = false;
4145            final int packageCount = mPackages.size();
4146            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4147                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4148                SettingBase sb = (SettingBase) pkg.mExtras;
4149                if (sb == null) {
4150                    continue;
4151                }
4152                PermissionsState permissionsState = sb.getPermissionsState();
4153                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4154                        userId, flagMask, flagValues);
4155            }
4156            if (changed) {
4157                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4158            }
4159        }
4160    }
4161
4162    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4163        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4164                != PackageManager.PERMISSION_GRANTED
4165            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4166                != PackageManager.PERMISSION_GRANTED) {
4167            throw new SecurityException(message + " requires "
4168                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4169                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4170        }
4171    }
4172
4173    @Override
4174    public boolean shouldShowRequestPermissionRationale(String permissionName,
4175            String packageName, int userId) {
4176        if (UserHandle.getCallingUserId() != userId) {
4177            mContext.enforceCallingPermission(
4178                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4179                    "canShowRequestPermissionRationale for user " + userId);
4180        }
4181
4182        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4183        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4184            return false;
4185        }
4186
4187        if (checkPermission(permissionName, packageName, userId)
4188                == PackageManager.PERMISSION_GRANTED) {
4189            return false;
4190        }
4191
4192        final int flags;
4193
4194        final long identity = Binder.clearCallingIdentity();
4195        try {
4196            flags = getPermissionFlags(permissionName,
4197                    packageName, userId);
4198        } finally {
4199            Binder.restoreCallingIdentity(identity);
4200        }
4201
4202        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4203                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4204                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4205
4206        if ((flags & fixedFlags) != 0) {
4207            return false;
4208        }
4209
4210        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4211    }
4212
4213    @Override
4214    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4215        mContext.enforceCallingOrSelfPermission(
4216                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4217                "addOnPermissionsChangeListener");
4218
4219        synchronized (mPackages) {
4220            mOnPermissionChangeListeners.addListenerLocked(listener);
4221        }
4222    }
4223
4224    @Override
4225    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4226        synchronized (mPackages) {
4227            mOnPermissionChangeListeners.removeListenerLocked(listener);
4228        }
4229    }
4230
4231    @Override
4232    public boolean isProtectedBroadcast(String actionName) {
4233        synchronized (mPackages) {
4234            if (mProtectedBroadcasts.contains(actionName)) {
4235                return true;
4236            } else if (actionName != null) {
4237                // TODO: remove these terrible hacks
4238                if (actionName.startsWith("android.net.netmon.lingerExpired")
4239                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4240                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4241                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4242                    return true;
4243                }
4244            }
4245        }
4246        return false;
4247    }
4248
4249    @Override
4250    public int checkSignatures(String pkg1, String pkg2) {
4251        synchronized (mPackages) {
4252            final PackageParser.Package p1 = mPackages.get(pkg1);
4253            final PackageParser.Package p2 = mPackages.get(pkg2);
4254            if (p1 == null || p1.mExtras == null
4255                    || p2 == null || p2.mExtras == null) {
4256                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4257            }
4258            return compareSignatures(p1.mSignatures, p2.mSignatures);
4259        }
4260    }
4261
4262    @Override
4263    public int checkUidSignatures(int uid1, int uid2) {
4264        // Map to base uids.
4265        uid1 = UserHandle.getAppId(uid1);
4266        uid2 = UserHandle.getAppId(uid2);
4267        // reader
4268        synchronized (mPackages) {
4269            Signature[] s1;
4270            Signature[] s2;
4271            Object obj = mSettings.getUserIdLPr(uid1);
4272            if (obj != null) {
4273                if (obj instanceof SharedUserSetting) {
4274                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4275                } else if (obj instanceof PackageSetting) {
4276                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4277                } else {
4278                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4279                }
4280            } else {
4281                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4282            }
4283            obj = mSettings.getUserIdLPr(uid2);
4284            if (obj != null) {
4285                if (obj instanceof SharedUserSetting) {
4286                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4287                } else if (obj instanceof PackageSetting) {
4288                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4289                } else {
4290                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4291                }
4292            } else {
4293                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4294            }
4295            return compareSignatures(s1, s2);
4296        }
4297    }
4298
4299    private void killUid(int appId, int userId, String reason) {
4300        final long identity = Binder.clearCallingIdentity();
4301        try {
4302            IActivityManager am = ActivityManagerNative.getDefault();
4303            if (am != null) {
4304                try {
4305                    am.killUid(appId, userId, reason);
4306                } catch (RemoteException e) {
4307                    /* ignore - same process */
4308                }
4309            }
4310        } finally {
4311            Binder.restoreCallingIdentity(identity);
4312        }
4313    }
4314
4315    /**
4316     * Compares two sets of signatures. Returns:
4317     * <br />
4318     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4319     * <br />
4320     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4321     * <br />
4322     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4323     * <br />
4324     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4325     * <br />
4326     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4327     */
4328    static int compareSignatures(Signature[] s1, Signature[] s2) {
4329        if (s1 == null) {
4330            return s2 == null
4331                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4332                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4333        }
4334
4335        if (s2 == null) {
4336            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4337        }
4338
4339        if (s1.length != s2.length) {
4340            return PackageManager.SIGNATURE_NO_MATCH;
4341        }
4342
4343        // Since both signature sets are of size 1, we can compare without HashSets.
4344        if (s1.length == 1) {
4345            return s1[0].equals(s2[0]) ?
4346                    PackageManager.SIGNATURE_MATCH :
4347                    PackageManager.SIGNATURE_NO_MATCH;
4348        }
4349
4350        ArraySet<Signature> set1 = new ArraySet<Signature>();
4351        for (Signature sig : s1) {
4352            set1.add(sig);
4353        }
4354        ArraySet<Signature> set2 = new ArraySet<Signature>();
4355        for (Signature sig : s2) {
4356            set2.add(sig);
4357        }
4358        // Make sure s2 contains all signatures in s1.
4359        if (set1.equals(set2)) {
4360            return PackageManager.SIGNATURE_MATCH;
4361        }
4362        return PackageManager.SIGNATURE_NO_MATCH;
4363    }
4364
4365    /**
4366     * If the database version for this type of package (internal storage or
4367     * external storage) is less than the version where package signatures
4368     * were updated, return true.
4369     */
4370    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4371        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4372        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4373    }
4374
4375    /**
4376     * Used for backward compatibility to make sure any packages with
4377     * certificate chains get upgraded to the new style. {@code existingSigs}
4378     * will be in the old format (since they were stored on disk from before the
4379     * system upgrade) and {@code scannedSigs} will be in the newer format.
4380     */
4381    private int compareSignaturesCompat(PackageSignatures existingSigs,
4382            PackageParser.Package scannedPkg) {
4383        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4384            return PackageManager.SIGNATURE_NO_MATCH;
4385        }
4386
4387        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4388        for (Signature sig : existingSigs.mSignatures) {
4389            existingSet.add(sig);
4390        }
4391        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4392        for (Signature sig : scannedPkg.mSignatures) {
4393            try {
4394                Signature[] chainSignatures = sig.getChainSignatures();
4395                for (Signature chainSig : chainSignatures) {
4396                    scannedCompatSet.add(chainSig);
4397                }
4398            } catch (CertificateEncodingException e) {
4399                scannedCompatSet.add(sig);
4400            }
4401        }
4402        /*
4403         * Make sure the expanded scanned set contains all signatures in the
4404         * existing one.
4405         */
4406        if (scannedCompatSet.equals(existingSet)) {
4407            // Migrate the old signatures to the new scheme.
4408            existingSigs.assignSignatures(scannedPkg.mSignatures);
4409            // The new KeySets will be re-added later in the scanning process.
4410            synchronized (mPackages) {
4411                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4412            }
4413            return PackageManager.SIGNATURE_MATCH;
4414        }
4415        return PackageManager.SIGNATURE_NO_MATCH;
4416    }
4417
4418    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4419        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4420        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4421    }
4422
4423    private int compareSignaturesRecover(PackageSignatures existingSigs,
4424            PackageParser.Package scannedPkg) {
4425        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4426            return PackageManager.SIGNATURE_NO_MATCH;
4427        }
4428
4429        String msg = null;
4430        try {
4431            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4432                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4433                        + scannedPkg.packageName);
4434                return PackageManager.SIGNATURE_MATCH;
4435            }
4436        } catch (CertificateException e) {
4437            msg = e.getMessage();
4438        }
4439
4440        logCriticalInfo(Log.INFO,
4441                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4442        return PackageManager.SIGNATURE_NO_MATCH;
4443    }
4444
4445    @Override
4446    public List<String> getAllPackages() {
4447        synchronized (mPackages) {
4448            return new ArrayList<String>(mPackages.keySet());
4449        }
4450    }
4451
4452    @Override
4453    public String[] getPackagesForUid(int uid) {
4454        uid = UserHandle.getAppId(uid);
4455        // reader
4456        synchronized (mPackages) {
4457            Object obj = mSettings.getUserIdLPr(uid);
4458            if (obj instanceof SharedUserSetting) {
4459                final SharedUserSetting sus = (SharedUserSetting) obj;
4460                final int N = sus.packages.size();
4461                final String[] res = new String[N];
4462                final Iterator<PackageSetting> it = sus.packages.iterator();
4463                int i = 0;
4464                while (it.hasNext()) {
4465                    res[i++] = it.next().name;
4466                }
4467                return res;
4468            } else if (obj instanceof PackageSetting) {
4469                final PackageSetting ps = (PackageSetting) obj;
4470                return new String[] { ps.name };
4471            }
4472        }
4473        return null;
4474    }
4475
4476    @Override
4477    public String getNameForUid(int uid) {
4478        // reader
4479        synchronized (mPackages) {
4480            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4481            if (obj instanceof SharedUserSetting) {
4482                final SharedUserSetting sus = (SharedUserSetting) obj;
4483                return sus.name + ":" + sus.userId;
4484            } else if (obj instanceof PackageSetting) {
4485                final PackageSetting ps = (PackageSetting) obj;
4486                return ps.name;
4487            }
4488        }
4489        return null;
4490    }
4491
4492    @Override
4493    public int getUidForSharedUser(String sharedUserName) {
4494        if(sharedUserName == null) {
4495            return -1;
4496        }
4497        // reader
4498        synchronized (mPackages) {
4499            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4500            if (suid == null) {
4501                return -1;
4502            }
4503            return suid.userId;
4504        }
4505    }
4506
4507    @Override
4508    public int getFlagsForUid(int uid) {
4509        synchronized (mPackages) {
4510            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4511            if (obj instanceof SharedUserSetting) {
4512                final SharedUserSetting sus = (SharedUserSetting) obj;
4513                return sus.pkgFlags;
4514            } else if (obj instanceof PackageSetting) {
4515                final PackageSetting ps = (PackageSetting) obj;
4516                return ps.pkgFlags;
4517            }
4518        }
4519        return 0;
4520    }
4521
4522    @Override
4523    public int getPrivateFlagsForUid(int uid) {
4524        synchronized (mPackages) {
4525            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4526            if (obj instanceof SharedUserSetting) {
4527                final SharedUserSetting sus = (SharedUserSetting) obj;
4528                return sus.pkgPrivateFlags;
4529            } else if (obj instanceof PackageSetting) {
4530                final PackageSetting ps = (PackageSetting) obj;
4531                return ps.pkgPrivateFlags;
4532            }
4533        }
4534        return 0;
4535    }
4536
4537    @Override
4538    public boolean isUidPrivileged(int uid) {
4539        uid = UserHandle.getAppId(uid);
4540        // reader
4541        synchronized (mPackages) {
4542            Object obj = mSettings.getUserIdLPr(uid);
4543            if (obj instanceof SharedUserSetting) {
4544                final SharedUserSetting sus = (SharedUserSetting) obj;
4545                final Iterator<PackageSetting> it = sus.packages.iterator();
4546                while (it.hasNext()) {
4547                    if (it.next().isPrivileged()) {
4548                        return true;
4549                    }
4550                }
4551            } else if (obj instanceof PackageSetting) {
4552                final PackageSetting ps = (PackageSetting) obj;
4553                return ps.isPrivileged();
4554            }
4555        }
4556        return false;
4557    }
4558
4559    @Override
4560    public String[] getAppOpPermissionPackages(String permissionName) {
4561        synchronized (mPackages) {
4562            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4563            if (pkgs == null) {
4564                return null;
4565            }
4566            return pkgs.toArray(new String[pkgs.size()]);
4567        }
4568    }
4569
4570    @Override
4571    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4572            int flags, int userId) {
4573        if (!sUserManager.exists(userId)) return null;
4574        flags = updateFlagsForResolve(flags, userId, intent);
4575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4576                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4577        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4578                userId);
4579        final ResolveInfo bestChoice =
4580                chooseBestActivity(intent, resolvedType, flags, query, userId);
4581
4582        if (isEphemeralAllowed(intent, query, userId)) {
4583            final EphemeralResolveInfo ai =
4584                    getEphemeralResolveInfo(intent, resolvedType, userId);
4585            if (ai != null) {
4586                if (DEBUG_EPHEMERAL) {
4587                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4588                }
4589                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4590                bestChoice.ephemeralResolveInfo = ai;
4591            }
4592        }
4593        return bestChoice;
4594    }
4595
4596    @Override
4597    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4598            IntentFilter filter, int match, ComponentName activity) {
4599        final int userId = UserHandle.getCallingUserId();
4600        if (DEBUG_PREFERRED) {
4601            Log.v(TAG, "setLastChosenActivity intent=" + intent
4602                + " resolvedType=" + resolvedType
4603                + " flags=" + flags
4604                + " filter=" + filter
4605                + " match=" + match
4606                + " activity=" + activity);
4607            filter.dump(new PrintStreamPrinter(System.out), "    ");
4608        }
4609        intent.setComponent(null);
4610        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4611                userId);
4612        // Find any earlier preferred or last chosen entries and nuke them
4613        findPreferredActivity(intent, resolvedType,
4614                flags, query, 0, false, true, false, userId);
4615        // Add the new activity as the last chosen for this filter
4616        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4617                "Setting last chosen");
4618    }
4619
4620    @Override
4621    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4622        final int userId = UserHandle.getCallingUserId();
4623        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4624        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4625                userId);
4626        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4627                false, false, false, userId);
4628    }
4629
4630
4631    private boolean isEphemeralAllowed(
4632            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4633        // Short circuit and return early if possible.
4634        if (DISABLE_EPHEMERAL_APPS) {
4635            return false;
4636        }
4637        final int callingUser = UserHandle.getCallingUserId();
4638        if (callingUser != UserHandle.USER_SYSTEM) {
4639            return false;
4640        }
4641        if (mEphemeralResolverConnection == null) {
4642            return false;
4643        }
4644        if (intent.getComponent() != null) {
4645            return false;
4646        }
4647        if (intent.getPackage() != null) {
4648            return false;
4649        }
4650        final boolean isWebUri = hasWebURI(intent);
4651        if (!isWebUri) {
4652            return false;
4653        }
4654        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4655        synchronized (mPackages) {
4656            final int count = resolvedActivites.size();
4657            for (int n = 0; n < count; n++) {
4658                ResolveInfo info = resolvedActivites.get(n);
4659                String packageName = info.activityInfo.packageName;
4660                PackageSetting ps = mSettings.mPackages.get(packageName);
4661                if (ps != null) {
4662                    // Try to get the status from User settings first
4663                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4664                    int status = (int) (packedStatus >> 32);
4665                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4666                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4667                        if (DEBUG_EPHEMERAL) {
4668                            Slog.v(TAG, "DENY ephemeral apps;"
4669                                + " pkg: " + packageName + ", status: " + status);
4670                        }
4671                        return false;
4672                    }
4673                }
4674            }
4675        }
4676        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4677        return true;
4678    }
4679
4680    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4681            int userId) {
4682        MessageDigest digest = null;
4683        try {
4684            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4685        } catch (NoSuchAlgorithmException e) {
4686            // If we can't create a digest, ignore ephemeral apps.
4687            return null;
4688        }
4689
4690        final byte[] hostBytes = intent.getData().getHost().getBytes();
4691        final byte[] digestBytes = digest.digest(hostBytes);
4692        int shaPrefix =
4693                digestBytes[0] << 24
4694                | digestBytes[1] << 16
4695                | digestBytes[2] << 8
4696                | digestBytes[3] << 0;
4697        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4698                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4699        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4700            // No hash prefix match; there are no ephemeral apps for this domain.
4701            return null;
4702        }
4703        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4704            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4705            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4706                continue;
4707            }
4708            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4709            // No filters; this should never happen.
4710            if (filters.isEmpty()) {
4711                continue;
4712            }
4713            // We have a domain match; resolve the filters to see if anything matches.
4714            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4715            for (int j = filters.size() - 1; j >= 0; --j) {
4716                final EphemeralResolveIntentInfo intentInfo =
4717                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4718                ephemeralResolver.addFilter(intentInfo);
4719            }
4720            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4721                    intent, resolvedType, false /*defaultOnly*/, userId);
4722            if (!matchedResolveInfoList.isEmpty()) {
4723                return matchedResolveInfoList.get(0);
4724            }
4725        }
4726        // Hash or filter mis-match; no ephemeral apps for this domain.
4727        return null;
4728    }
4729
4730    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4731            int flags, List<ResolveInfo> query, int userId) {
4732        if (query != null) {
4733            final int N = query.size();
4734            if (N == 1) {
4735                return query.get(0);
4736            } else if (N > 1) {
4737                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4738                // If there is more than one activity with the same priority,
4739                // then let the user decide between them.
4740                ResolveInfo r0 = query.get(0);
4741                ResolveInfo r1 = query.get(1);
4742                if (DEBUG_INTENT_MATCHING || debug) {
4743                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4744                            + r1.activityInfo.name + "=" + r1.priority);
4745                }
4746                // If the first activity has a higher priority, or a different
4747                // default, then it is always desirable to pick it.
4748                if (r0.priority != r1.priority
4749                        || r0.preferredOrder != r1.preferredOrder
4750                        || r0.isDefault != r1.isDefault) {
4751                    return query.get(0);
4752                }
4753                // If we have saved a preference for a preferred activity for
4754                // this Intent, use that.
4755                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4756                        flags, query, r0.priority, true, false, debug, userId);
4757                if (ri != null) {
4758                    return ri;
4759                }
4760                ri = new ResolveInfo(mResolveInfo);
4761                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4762                ri.activityInfo.applicationInfo = new ApplicationInfo(
4763                        ri.activityInfo.applicationInfo);
4764                if (userId != 0) {
4765                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4766                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4767                }
4768                // Make sure that the resolver is displayable in car mode
4769                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4770                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4771                return ri;
4772            }
4773        }
4774        return null;
4775    }
4776
4777    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4778            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4779        final int N = query.size();
4780        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4781                .get(userId);
4782        // Get the list of persistent preferred activities that handle the intent
4783        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4784        List<PersistentPreferredActivity> pprefs = ppir != null
4785                ? ppir.queryIntent(intent, resolvedType,
4786                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4787                : null;
4788        if (pprefs != null && pprefs.size() > 0) {
4789            final int M = pprefs.size();
4790            for (int i=0; i<M; i++) {
4791                final PersistentPreferredActivity ppa = pprefs.get(i);
4792                if (DEBUG_PREFERRED || debug) {
4793                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4794                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4795                            + "\n  component=" + ppa.mComponent);
4796                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4797                }
4798                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4799                        flags | MATCH_DISABLED_COMPONENTS, userId);
4800                if (DEBUG_PREFERRED || debug) {
4801                    Slog.v(TAG, "Found persistent preferred activity:");
4802                    if (ai != null) {
4803                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4804                    } else {
4805                        Slog.v(TAG, "  null");
4806                    }
4807                }
4808                if (ai == null) {
4809                    // This previously registered persistent preferred activity
4810                    // component is no longer known. Ignore it and do NOT remove it.
4811                    continue;
4812                }
4813                for (int j=0; j<N; j++) {
4814                    final ResolveInfo ri = query.get(j);
4815                    if (!ri.activityInfo.applicationInfo.packageName
4816                            .equals(ai.applicationInfo.packageName)) {
4817                        continue;
4818                    }
4819                    if (!ri.activityInfo.name.equals(ai.name)) {
4820                        continue;
4821                    }
4822                    //  Found a persistent preference that can handle the intent.
4823                    if (DEBUG_PREFERRED || debug) {
4824                        Slog.v(TAG, "Returning persistent preferred activity: " +
4825                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4826                    }
4827                    return ri;
4828                }
4829            }
4830        }
4831        return null;
4832    }
4833
4834    // TODO: handle preferred activities missing while user has amnesia
4835    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4836            List<ResolveInfo> query, int priority, boolean always,
4837            boolean removeMatches, boolean debug, int userId) {
4838        if (!sUserManager.exists(userId)) return null;
4839        flags = updateFlagsForResolve(flags, userId, intent);
4840        // writer
4841        synchronized (mPackages) {
4842            if (intent.getSelector() != null) {
4843                intent = intent.getSelector();
4844            }
4845            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4846
4847            // Try to find a matching persistent preferred activity.
4848            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4849                    debug, userId);
4850
4851            // If a persistent preferred activity matched, use it.
4852            if (pri != null) {
4853                return pri;
4854            }
4855
4856            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4857            // Get the list of preferred activities that handle the intent
4858            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4859            List<PreferredActivity> prefs = pir != null
4860                    ? pir.queryIntent(intent, resolvedType,
4861                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4862                    : null;
4863            if (prefs != null && prefs.size() > 0) {
4864                boolean changed = false;
4865                try {
4866                    // First figure out how good the original match set is.
4867                    // We will only allow preferred activities that came
4868                    // from the same match quality.
4869                    int match = 0;
4870
4871                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4872
4873                    final int N = query.size();
4874                    for (int j=0; j<N; j++) {
4875                        final ResolveInfo ri = query.get(j);
4876                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4877                                + ": 0x" + Integer.toHexString(match));
4878                        if (ri.match > match) {
4879                            match = ri.match;
4880                        }
4881                    }
4882
4883                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4884                            + Integer.toHexString(match));
4885
4886                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4887                    final int M = prefs.size();
4888                    for (int i=0; i<M; i++) {
4889                        final PreferredActivity pa = prefs.get(i);
4890                        if (DEBUG_PREFERRED || debug) {
4891                            Slog.v(TAG, "Checking PreferredActivity ds="
4892                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4893                                    + "\n  component=" + pa.mPref.mComponent);
4894                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4895                        }
4896                        if (pa.mPref.mMatch != match) {
4897                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4898                                    + Integer.toHexString(pa.mPref.mMatch));
4899                            continue;
4900                        }
4901                        // If it's not an "always" type preferred activity and that's what we're
4902                        // looking for, skip it.
4903                        if (always && !pa.mPref.mAlways) {
4904                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4905                            continue;
4906                        }
4907                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4908                                flags | MATCH_DISABLED_COMPONENTS, userId);
4909                        if (DEBUG_PREFERRED || debug) {
4910                            Slog.v(TAG, "Found preferred activity:");
4911                            if (ai != null) {
4912                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4913                            } else {
4914                                Slog.v(TAG, "  null");
4915                            }
4916                        }
4917                        if (ai == null) {
4918                            // This previously registered preferred activity
4919                            // component is no longer known.  Most likely an update
4920                            // to the app was installed and in the new version this
4921                            // component no longer exists.  Clean it up by removing
4922                            // it from the preferred activities list, and skip it.
4923                            Slog.w(TAG, "Removing dangling preferred activity: "
4924                                    + pa.mPref.mComponent);
4925                            pir.removeFilter(pa);
4926                            changed = true;
4927                            continue;
4928                        }
4929                        for (int j=0; j<N; j++) {
4930                            final ResolveInfo ri = query.get(j);
4931                            if (!ri.activityInfo.applicationInfo.packageName
4932                                    .equals(ai.applicationInfo.packageName)) {
4933                                continue;
4934                            }
4935                            if (!ri.activityInfo.name.equals(ai.name)) {
4936                                continue;
4937                            }
4938
4939                            if (removeMatches) {
4940                                pir.removeFilter(pa);
4941                                changed = true;
4942                                if (DEBUG_PREFERRED) {
4943                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4944                                }
4945                                break;
4946                            }
4947
4948                            // Okay we found a previously set preferred or last chosen app.
4949                            // If the result set is different from when this
4950                            // was created, we need to clear it and re-ask the
4951                            // user their preference, if we're looking for an "always" type entry.
4952                            if (always && !pa.mPref.sameSet(query)) {
4953                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4954                                        + intent + " type " + resolvedType);
4955                                if (DEBUG_PREFERRED) {
4956                                    Slog.v(TAG, "Removing preferred activity since set changed "
4957                                            + pa.mPref.mComponent);
4958                                }
4959                                pir.removeFilter(pa);
4960                                // Re-add the filter as a "last chosen" entry (!always)
4961                                PreferredActivity lastChosen = new PreferredActivity(
4962                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4963                                pir.addFilter(lastChosen);
4964                                changed = true;
4965                                return null;
4966                            }
4967
4968                            // Yay! Either the set matched or we're looking for the last chosen
4969                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4970                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4971                            return ri;
4972                        }
4973                    }
4974                } finally {
4975                    if (changed) {
4976                        if (DEBUG_PREFERRED) {
4977                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4978                        }
4979                        scheduleWritePackageRestrictionsLocked(userId);
4980                    }
4981                }
4982            }
4983        }
4984        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4985        return null;
4986    }
4987
4988    /*
4989     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4990     */
4991    @Override
4992    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4993            int targetUserId) {
4994        mContext.enforceCallingOrSelfPermission(
4995                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4996        List<CrossProfileIntentFilter> matches =
4997                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4998        if (matches != null) {
4999            int size = matches.size();
5000            for (int i = 0; i < size; i++) {
5001                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5002            }
5003        }
5004        if (hasWebURI(intent)) {
5005            // cross-profile app linking works only towards the parent.
5006            final UserInfo parent = getProfileParent(sourceUserId);
5007            synchronized(mPackages) {
5008                int flags = updateFlagsForResolve(0, parent.id, intent);
5009                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5010                        intent, resolvedType, flags, sourceUserId, parent.id);
5011                return xpDomainInfo != null;
5012            }
5013        }
5014        return false;
5015    }
5016
5017    private UserInfo getProfileParent(int userId) {
5018        final long identity = Binder.clearCallingIdentity();
5019        try {
5020            return sUserManager.getProfileParent(userId);
5021        } finally {
5022            Binder.restoreCallingIdentity(identity);
5023        }
5024    }
5025
5026    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5027            String resolvedType, int userId) {
5028        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5029        if (resolver != null) {
5030            return resolver.queryIntent(intent, resolvedType, false, userId);
5031        }
5032        return null;
5033    }
5034
5035    @Override
5036    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5037            String resolvedType, int flags, int userId) {
5038        return new ParceledListSlice<>(
5039                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5040    }
5041
5042    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5043            String resolvedType, int flags, int userId) {
5044        if (!sUserManager.exists(userId)) return Collections.emptyList();
5045        flags = updateFlagsForResolve(flags, userId, intent);
5046        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5047                false /* requireFullPermission */, false /* checkShell */,
5048                "query intent activities");
5049        ComponentName comp = intent.getComponent();
5050        if (comp == null) {
5051            if (intent.getSelector() != null) {
5052                intent = intent.getSelector();
5053                comp = intent.getComponent();
5054            }
5055        }
5056
5057        if (comp != null) {
5058            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5059            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5060            if (ai != null) {
5061                final ResolveInfo ri = new ResolveInfo();
5062                ri.activityInfo = ai;
5063                list.add(ri);
5064            }
5065            return list;
5066        }
5067
5068        // reader
5069        synchronized (mPackages) {
5070            final String pkgName = intent.getPackage();
5071            if (pkgName == null) {
5072                List<CrossProfileIntentFilter> matchingFilters =
5073                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5074                // Check for results that need to skip the current profile.
5075                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5076                        resolvedType, flags, userId);
5077                if (xpResolveInfo != null) {
5078                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5079                    result.add(xpResolveInfo);
5080                    return filterIfNotSystemUser(result, userId);
5081                }
5082
5083                // Check for results in the current profile.
5084                List<ResolveInfo> result = mActivities.queryIntent(
5085                        intent, resolvedType, flags, userId);
5086                result = filterIfNotSystemUser(result, userId);
5087
5088                // Check for cross profile results.
5089                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5090                xpResolveInfo = queryCrossProfileIntents(
5091                        matchingFilters, intent, resolvedType, flags, userId,
5092                        hasNonNegativePriorityResult);
5093                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5094                    boolean isVisibleToUser = filterIfNotSystemUser(
5095                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5096                    if (isVisibleToUser) {
5097                        result.add(xpResolveInfo);
5098                        Collections.sort(result, mResolvePrioritySorter);
5099                    }
5100                }
5101                if (hasWebURI(intent)) {
5102                    CrossProfileDomainInfo xpDomainInfo = null;
5103                    final UserInfo parent = getProfileParent(userId);
5104                    if (parent != null) {
5105                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5106                                flags, userId, parent.id);
5107                    }
5108                    if (xpDomainInfo != null) {
5109                        if (xpResolveInfo != null) {
5110                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5111                            // in the result.
5112                            result.remove(xpResolveInfo);
5113                        }
5114                        if (result.size() == 0) {
5115                            result.add(xpDomainInfo.resolveInfo);
5116                            return result;
5117                        }
5118                    } else if (result.size() <= 1) {
5119                        return result;
5120                    }
5121                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5122                            xpDomainInfo, userId);
5123                    Collections.sort(result, mResolvePrioritySorter);
5124                }
5125                return result;
5126            }
5127            final PackageParser.Package pkg = mPackages.get(pkgName);
5128            if (pkg != null) {
5129                return filterIfNotSystemUser(
5130                        mActivities.queryIntentForPackage(
5131                                intent, resolvedType, flags, pkg.activities, userId),
5132                        userId);
5133            }
5134            return new ArrayList<ResolveInfo>();
5135        }
5136    }
5137
5138    private static class CrossProfileDomainInfo {
5139        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5140        ResolveInfo resolveInfo;
5141        /* Best domain verification status of the activities found in the other profile */
5142        int bestDomainVerificationStatus;
5143    }
5144
5145    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5146            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5147        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5148                sourceUserId)) {
5149            return null;
5150        }
5151        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5152                resolvedType, flags, parentUserId);
5153
5154        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5155            return null;
5156        }
5157        CrossProfileDomainInfo result = null;
5158        int size = resultTargetUser.size();
5159        for (int i = 0; i < size; i++) {
5160            ResolveInfo riTargetUser = resultTargetUser.get(i);
5161            // Intent filter verification is only for filters that specify a host. So don't return
5162            // those that handle all web uris.
5163            if (riTargetUser.handleAllWebDataURI) {
5164                continue;
5165            }
5166            String packageName = riTargetUser.activityInfo.packageName;
5167            PackageSetting ps = mSettings.mPackages.get(packageName);
5168            if (ps == null) {
5169                continue;
5170            }
5171            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5172            int status = (int)(verificationState >> 32);
5173            if (result == null) {
5174                result = new CrossProfileDomainInfo();
5175                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5176                        sourceUserId, parentUserId);
5177                result.bestDomainVerificationStatus = status;
5178            } else {
5179                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5180                        result.bestDomainVerificationStatus);
5181            }
5182        }
5183        // Don't consider matches with status NEVER across profiles.
5184        if (result != null && result.bestDomainVerificationStatus
5185                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5186            return null;
5187        }
5188        return result;
5189    }
5190
5191    /**
5192     * Verification statuses are ordered from the worse to the best, except for
5193     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5194     */
5195    private int bestDomainVerificationStatus(int status1, int status2) {
5196        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5197            return status2;
5198        }
5199        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5200            return status1;
5201        }
5202        return (int) MathUtils.max(status1, status2);
5203    }
5204
5205    private boolean isUserEnabled(int userId) {
5206        long callingId = Binder.clearCallingIdentity();
5207        try {
5208            UserInfo userInfo = sUserManager.getUserInfo(userId);
5209            return userInfo != null && userInfo.isEnabled();
5210        } finally {
5211            Binder.restoreCallingIdentity(callingId);
5212        }
5213    }
5214
5215    /**
5216     * Filter out activities with systemUserOnly flag set, when current user is not System.
5217     *
5218     * @return filtered list
5219     */
5220    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5221        if (userId == UserHandle.USER_SYSTEM) {
5222            return resolveInfos;
5223        }
5224        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5225            ResolveInfo info = resolveInfos.get(i);
5226            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5227                resolveInfos.remove(i);
5228            }
5229        }
5230        return resolveInfos;
5231    }
5232
5233    /**
5234     * @param resolveInfos list of resolve infos in descending priority order
5235     * @return if the list contains a resolve info with non-negative priority
5236     */
5237    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5238        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5239    }
5240
5241    private static boolean hasWebURI(Intent intent) {
5242        if (intent.getData() == null) {
5243            return false;
5244        }
5245        final String scheme = intent.getScheme();
5246        if (TextUtils.isEmpty(scheme)) {
5247            return false;
5248        }
5249        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5250    }
5251
5252    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5253            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5254            int userId) {
5255        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5256
5257        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5258            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5259                    candidates.size());
5260        }
5261
5262        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5263        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5264        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5265        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5266        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5267        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5268
5269        synchronized (mPackages) {
5270            final int count = candidates.size();
5271            // First, try to use linked apps. Partition the candidates into four lists:
5272            // one for the final results, one for the "do not use ever", one for "undefined status"
5273            // and finally one for "browser app type".
5274            for (int n=0; n<count; n++) {
5275                ResolveInfo info = candidates.get(n);
5276                String packageName = info.activityInfo.packageName;
5277                PackageSetting ps = mSettings.mPackages.get(packageName);
5278                if (ps != null) {
5279                    // Add to the special match all list (Browser use case)
5280                    if (info.handleAllWebDataURI) {
5281                        matchAllList.add(info);
5282                        continue;
5283                    }
5284                    // Try to get the status from User settings first
5285                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5286                    int status = (int)(packedStatus >> 32);
5287                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5288                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5289                        if (DEBUG_DOMAIN_VERIFICATION) {
5290                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5291                                    + " : linkgen=" + linkGeneration);
5292                        }
5293                        // Use link-enabled generation as preferredOrder, i.e.
5294                        // prefer newly-enabled over earlier-enabled.
5295                        info.preferredOrder = linkGeneration;
5296                        alwaysList.add(info);
5297                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5298                        if (DEBUG_DOMAIN_VERIFICATION) {
5299                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5300                        }
5301                        neverList.add(info);
5302                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5303                        if (DEBUG_DOMAIN_VERIFICATION) {
5304                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5305                        }
5306                        alwaysAskList.add(info);
5307                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5308                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5309                        if (DEBUG_DOMAIN_VERIFICATION) {
5310                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5311                        }
5312                        undefinedList.add(info);
5313                    }
5314                }
5315            }
5316
5317            // We'll want to include browser possibilities in a few cases
5318            boolean includeBrowser = false;
5319
5320            // First try to add the "always" resolution(s) for the current user, if any
5321            if (alwaysList.size() > 0) {
5322                result.addAll(alwaysList);
5323            } else {
5324                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5325                result.addAll(undefinedList);
5326                // Maybe add one for the other profile.
5327                if (xpDomainInfo != null && (
5328                        xpDomainInfo.bestDomainVerificationStatus
5329                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5330                    result.add(xpDomainInfo.resolveInfo);
5331                }
5332                includeBrowser = true;
5333            }
5334
5335            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5336            // If there were 'always' entries their preferred order has been set, so we also
5337            // back that off to make the alternatives equivalent
5338            if (alwaysAskList.size() > 0) {
5339                for (ResolveInfo i : result) {
5340                    i.preferredOrder = 0;
5341                }
5342                result.addAll(alwaysAskList);
5343                includeBrowser = true;
5344            }
5345
5346            if (includeBrowser) {
5347                // Also add browsers (all of them or only the default one)
5348                if (DEBUG_DOMAIN_VERIFICATION) {
5349                    Slog.v(TAG, "   ...including browsers in candidate set");
5350                }
5351                if ((matchFlags & MATCH_ALL) != 0) {
5352                    result.addAll(matchAllList);
5353                } else {
5354                    // Browser/generic handling case.  If there's a default browser, go straight
5355                    // to that (but only if there is no other higher-priority match).
5356                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5357                    int maxMatchPrio = 0;
5358                    ResolveInfo defaultBrowserMatch = null;
5359                    final int numCandidates = matchAllList.size();
5360                    for (int n = 0; n < numCandidates; n++) {
5361                        ResolveInfo info = matchAllList.get(n);
5362                        // track the highest overall match priority...
5363                        if (info.priority > maxMatchPrio) {
5364                            maxMatchPrio = info.priority;
5365                        }
5366                        // ...and the highest-priority default browser match
5367                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5368                            if (defaultBrowserMatch == null
5369                                    || (defaultBrowserMatch.priority < info.priority)) {
5370                                if (debug) {
5371                                    Slog.v(TAG, "Considering default browser match " + info);
5372                                }
5373                                defaultBrowserMatch = info;
5374                            }
5375                        }
5376                    }
5377                    if (defaultBrowserMatch != null
5378                            && defaultBrowserMatch.priority >= maxMatchPrio
5379                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5380                    {
5381                        if (debug) {
5382                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5383                        }
5384                        result.add(defaultBrowserMatch);
5385                    } else {
5386                        result.addAll(matchAllList);
5387                    }
5388                }
5389
5390                // If there is nothing selected, add all candidates and remove the ones that the user
5391                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5392                if (result.size() == 0) {
5393                    result.addAll(candidates);
5394                    result.removeAll(neverList);
5395                }
5396            }
5397        }
5398        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5399            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5400                    result.size());
5401            for (ResolveInfo info : result) {
5402                Slog.v(TAG, "  + " + info.activityInfo);
5403            }
5404        }
5405        return result;
5406    }
5407
5408    // Returns a packed value as a long:
5409    //
5410    // high 'int'-sized word: link status: undefined/ask/never/always.
5411    // low 'int'-sized word: relative priority among 'always' results.
5412    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5413        long result = ps.getDomainVerificationStatusForUser(userId);
5414        // if none available, get the master status
5415        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5416            if (ps.getIntentFilterVerificationInfo() != null) {
5417                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5418            }
5419        }
5420        return result;
5421    }
5422
5423    private ResolveInfo querySkipCurrentProfileIntents(
5424            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5425            int flags, int sourceUserId) {
5426        if (matchingFilters != null) {
5427            int size = matchingFilters.size();
5428            for (int i = 0; i < size; i ++) {
5429                CrossProfileIntentFilter filter = matchingFilters.get(i);
5430                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5431                    // Checking if there are activities in the target user that can handle the
5432                    // intent.
5433                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5434                            resolvedType, flags, sourceUserId);
5435                    if (resolveInfo != null) {
5436                        return resolveInfo;
5437                    }
5438                }
5439            }
5440        }
5441        return null;
5442    }
5443
5444    // Return matching ResolveInfo in target user if any.
5445    private ResolveInfo queryCrossProfileIntents(
5446            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5447            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5448        if (matchingFilters != null) {
5449            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5450            // match the same intent. For performance reasons, it is better not to
5451            // run queryIntent twice for the same userId
5452            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5453            int size = matchingFilters.size();
5454            for (int i = 0; i < size; i++) {
5455                CrossProfileIntentFilter filter = matchingFilters.get(i);
5456                int targetUserId = filter.getTargetUserId();
5457                boolean skipCurrentProfile =
5458                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5459                boolean skipCurrentProfileIfNoMatchFound =
5460                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5461                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5462                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5463                    // Checking if there are activities in the target user that can handle the
5464                    // intent.
5465                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5466                            resolvedType, flags, sourceUserId);
5467                    if (resolveInfo != null) return resolveInfo;
5468                    alreadyTriedUserIds.put(targetUserId, true);
5469                }
5470            }
5471        }
5472        return null;
5473    }
5474
5475    /**
5476     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5477     * will forward the intent to the filter's target user.
5478     * Otherwise, returns null.
5479     */
5480    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5481            String resolvedType, int flags, int sourceUserId) {
5482        int targetUserId = filter.getTargetUserId();
5483        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5484                resolvedType, flags, targetUserId);
5485        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5486            // If all the matches in the target profile are suspended, return null.
5487            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5488                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5489                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5490                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5491                            targetUserId);
5492                }
5493            }
5494        }
5495        return null;
5496    }
5497
5498    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5499            int sourceUserId, int targetUserId) {
5500        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5501        long ident = Binder.clearCallingIdentity();
5502        boolean targetIsProfile;
5503        try {
5504            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5505        } finally {
5506            Binder.restoreCallingIdentity(ident);
5507        }
5508        String className;
5509        if (targetIsProfile) {
5510            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5511        } else {
5512            className = FORWARD_INTENT_TO_PARENT;
5513        }
5514        ComponentName forwardingActivityComponentName = new ComponentName(
5515                mAndroidApplication.packageName, className);
5516        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5517                sourceUserId);
5518        if (!targetIsProfile) {
5519            forwardingActivityInfo.showUserIcon = targetUserId;
5520            forwardingResolveInfo.noResourceId = true;
5521        }
5522        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5523        forwardingResolveInfo.priority = 0;
5524        forwardingResolveInfo.preferredOrder = 0;
5525        forwardingResolveInfo.match = 0;
5526        forwardingResolveInfo.isDefault = true;
5527        forwardingResolveInfo.filter = filter;
5528        forwardingResolveInfo.targetUserId = targetUserId;
5529        return forwardingResolveInfo;
5530    }
5531
5532    @Override
5533    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5534            Intent[] specifics, String[] specificTypes, Intent intent,
5535            String resolvedType, int flags, int userId) {
5536        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5537                specificTypes, intent, resolvedType, flags, userId));
5538    }
5539
5540    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5541            Intent[] specifics, String[] specificTypes, Intent intent,
5542            String resolvedType, int flags, int userId) {
5543        if (!sUserManager.exists(userId)) return Collections.emptyList();
5544        flags = updateFlagsForResolve(flags, userId, intent);
5545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5546                false /* requireFullPermission */, false /* checkShell */,
5547                "query intent activity options");
5548        final String resultsAction = intent.getAction();
5549
5550        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5551                | PackageManager.GET_RESOLVED_FILTER, userId);
5552
5553        if (DEBUG_INTENT_MATCHING) {
5554            Log.v(TAG, "Query " + intent + ": " + results);
5555        }
5556
5557        int specificsPos = 0;
5558        int N;
5559
5560        // todo: note that the algorithm used here is O(N^2).  This
5561        // isn't a problem in our current environment, but if we start running
5562        // into situations where we have more than 5 or 10 matches then this
5563        // should probably be changed to something smarter...
5564
5565        // First we go through and resolve each of the specific items
5566        // that were supplied, taking care of removing any corresponding
5567        // duplicate items in the generic resolve list.
5568        if (specifics != null) {
5569            for (int i=0; i<specifics.length; i++) {
5570                final Intent sintent = specifics[i];
5571                if (sintent == null) {
5572                    continue;
5573                }
5574
5575                if (DEBUG_INTENT_MATCHING) {
5576                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5577                }
5578
5579                String action = sintent.getAction();
5580                if (resultsAction != null && resultsAction.equals(action)) {
5581                    // If this action was explicitly requested, then don't
5582                    // remove things that have it.
5583                    action = null;
5584                }
5585
5586                ResolveInfo ri = null;
5587                ActivityInfo ai = null;
5588
5589                ComponentName comp = sintent.getComponent();
5590                if (comp == null) {
5591                    ri = resolveIntent(
5592                        sintent,
5593                        specificTypes != null ? specificTypes[i] : null,
5594                            flags, userId);
5595                    if (ri == null) {
5596                        continue;
5597                    }
5598                    if (ri == mResolveInfo) {
5599                        // ACK!  Must do something better with this.
5600                    }
5601                    ai = ri.activityInfo;
5602                    comp = new ComponentName(ai.applicationInfo.packageName,
5603                            ai.name);
5604                } else {
5605                    ai = getActivityInfo(comp, flags, userId);
5606                    if (ai == null) {
5607                        continue;
5608                    }
5609                }
5610
5611                // Look for any generic query activities that are duplicates
5612                // of this specific one, and remove them from the results.
5613                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5614                N = results.size();
5615                int j;
5616                for (j=specificsPos; j<N; j++) {
5617                    ResolveInfo sri = results.get(j);
5618                    if ((sri.activityInfo.name.equals(comp.getClassName())
5619                            && sri.activityInfo.applicationInfo.packageName.equals(
5620                                    comp.getPackageName()))
5621                        || (action != null && sri.filter.matchAction(action))) {
5622                        results.remove(j);
5623                        if (DEBUG_INTENT_MATCHING) Log.v(
5624                            TAG, "Removing duplicate item from " + j
5625                            + " due to specific " + specificsPos);
5626                        if (ri == null) {
5627                            ri = sri;
5628                        }
5629                        j--;
5630                        N--;
5631                    }
5632                }
5633
5634                // Add this specific item to its proper place.
5635                if (ri == null) {
5636                    ri = new ResolveInfo();
5637                    ri.activityInfo = ai;
5638                }
5639                results.add(specificsPos, ri);
5640                ri.specificIndex = i;
5641                specificsPos++;
5642            }
5643        }
5644
5645        // Now we go through the remaining generic results and remove any
5646        // duplicate actions that are found here.
5647        N = results.size();
5648        for (int i=specificsPos; i<N-1; i++) {
5649            final ResolveInfo rii = results.get(i);
5650            if (rii.filter == null) {
5651                continue;
5652            }
5653
5654            // Iterate over all of the actions of this result's intent
5655            // filter...  typically this should be just one.
5656            final Iterator<String> it = rii.filter.actionsIterator();
5657            if (it == null) {
5658                continue;
5659            }
5660            while (it.hasNext()) {
5661                final String action = it.next();
5662                if (resultsAction != null && resultsAction.equals(action)) {
5663                    // If this action was explicitly requested, then don't
5664                    // remove things that have it.
5665                    continue;
5666                }
5667                for (int j=i+1; j<N; j++) {
5668                    final ResolveInfo rij = results.get(j);
5669                    if (rij.filter != null && rij.filter.hasAction(action)) {
5670                        results.remove(j);
5671                        if (DEBUG_INTENT_MATCHING) Log.v(
5672                            TAG, "Removing duplicate item from " + j
5673                            + " due to action " + action + " at " + i);
5674                        j--;
5675                        N--;
5676                    }
5677                }
5678            }
5679
5680            // If the caller didn't request filter information, drop it now
5681            // so we don't have to marshall/unmarshall it.
5682            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5683                rii.filter = null;
5684            }
5685        }
5686
5687        // Filter out the caller activity if so requested.
5688        if (caller != null) {
5689            N = results.size();
5690            for (int i=0; i<N; i++) {
5691                ActivityInfo ainfo = results.get(i).activityInfo;
5692                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5693                        && caller.getClassName().equals(ainfo.name)) {
5694                    results.remove(i);
5695                    break;
5696                }
5697            }
5698        }
5699
5700        // If the caller didn't request filter information,
5701        // drop them now so we don't have to
5702        // marshall/unmarshall it.
5703        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5704            N = results.size();
5705            for (int i=0; i<N; i++) {
5706                results.get(i).filter = null;
5707            }
5708        }
5709
5710        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5711        return results;
5712    }
5713
5714    @Override
5715    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5716            String resolvedType, int flags, int userId) {
5717        return new ParceledListSlice<>(
5718                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5719    }
5720
5721    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5722            String resolvedType, int flags, int userId) {
5723        if (!sUserManager.exists(userId)) return Collections.emptyList();
5724        flags = updateFlagsForResolve(flags, userId, intent);
5725        ComponentName comp = intent.getComponent();
5726        if (comp == null) {
5727            if (intent.getSelector() != null) {
5728                intent = intent.getSelector();
5729                comp = intent.getComponent();
5730            }
5731        }
5732        if (comp != null) {
5733            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5734            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5735            if (ai != null) {
5736                ResolveInfo ri = new ResolveInfo();
5737                ri.activityInfo = ai;
5738                list.add(ri);
5739            }
5740            return list;
5741        }
5742
5743        // reader
5744        synchronized (mPackages) {
5745            String pkgName = intent.getPackage();
5746            if (pkgName == null) {
5747                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5748            }
5749            final PackageParser.Package pkg = mPackages.get(pkgName);
5750            if (pkg != null) {
5751                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5752                        userId);
5753            }
5754            return Collections.emptyList();
5755        }
5756    }
5757
5758    @Override
5759    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5760        if (!sUserManager.exists(userId)) return null;
5761        flags = updateFlagsForResolve(flags, userId, intent);
5762        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5763        if (query != null) {
5764            if (query.size() >= 1) {
5765                // If there is more than one service with the same priority,
5766                // just arbitrarily pick the first one.
5767                return query.get(0);
5768            }
5769        }
5770        return null;
5771    }
5772
5773    @Override
5774    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5775            String resolvedType, int flags, int userId) {
5776        return new ParceledListSlice<>(
5777                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5778    }
5779
5780    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5781            String resolvedType, int flags, int userId) {
5782        if (!sUserManager.exists(userId)) return Collections.emptyList();
5783        flags = updateFlagsForResolve(flags, userId, intent);
5784        ComponentName comp = intent.getComponent();
5785        if (comp == null) {
5786            if (intent.getSelector() != null) {
5787                intent = intent.getSelector();
5788                comp = intent.getComponent();
5789            }
5790        }
5791        if (comp != null) {
5792            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5793            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5794            if (si != null) {
5795                final ResolveInfo ri = new ResolveInfo();
5796                ri.serviceInfo = si;
5797                list.add(ri);
5798            }
5799            return list;
5800        }
5801
5802        // reader
5803        synchronized (mPackages) {
5804            String pkgName = intent.getPackage();
5805            if (pkgName == null) {
5806                return mServices.queryIntent(intent, resolvedType, flags, userId);
5807            }
5808            final PackageParser.Package pkg = mPackages.get(pkgName);
5809            if (pkg != null) {
5810                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5811                        userId);
5812            }
5813            return Collections.emptyList();
5814        }
5815    }
5816
5817    @Override
5818    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5819            String resolvedType, int flags, int userId) {
5820        return new ParceledListSlice<>(
5821                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5822    }
5823
5824    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5825            Intent intent, String resolvedType, int flags, int userId) {
5826        if (!sUserManager.exists(userId)) return Collections.emptyList();
5827        flags = updateFlagsForResolve(flags, userId, intent);
5828        ComponentName comp = intent.getComponent();
5829        if (comp == null) {
5830            if (intent.getSelector() != null) {
5831                intent = intent.getSelector();
5832                comp = intent.getComponent();
5833            }
5834        }
5835        if (comp != null) {
5836            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5837            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5838            if (pi != null) {
5839                final ResolveInfo ri = new ResolveInfo();
5840                ri.providerInfo = pi;
5841                list.add(ri);
5842            }
5843            return list;
5844        }
5845
5846        // reader
5847        synchronized (mPackages) {
5848            String pkgName = intent.getPackage();
5849            if (pkgName == null) {
5850                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5851            }
5852            final PackageParser.Package pkg = mPackages.get(pkgName);
5853            if (pkg != null) {
5854                return mProviders.queryIntentForPackage(
5855                        intent, resolvedType, flags, pkg.providers, userId);
5856            }
5857            return Collections.emptyList();
5858        }
5859    }
5860
5861    @Override
5862    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5863        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5864        flags = updateFlagsForPackage(flags, userId, null);
5865        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5866        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5867                true /* requireFullPermission */, false /* checkShell */,
5868                "get installed packages");
5869
5870        // writer
5871        synchronized (mPackages) {
5872            ArrayList<PackageInfo> list;
5873            if (listUninstalled) {
5874                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5875                for (PackageSetting ps : mSettings.mPackages.values()) {
5876                    PackageInfo pi;
5877                    if (ps.pkg != null) {
5878                        pi = generatePackageInfo(ps.pkg, flags, userId);
5879                    } else {
5880                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5881                    }
5882                    if (pi != null) {
5883                        list.add(pi);
5884                    }
5885                }
5886            } else {
5887                list = new ArrayList<PackageInfo>(mPackages.size());
5888                for (PackageParser.Package p : mPackages.values()) {
5889                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5890                    if (pi != null) {
5891                        list.add(pi);
5892                    }
5893                }
5894            }
5895
5896            return new ParceledListSlice<PackageInfo>(list);
5897        }
5898    }
5899
5900    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5901            String[] permissions, boolean[] tmp, int flags, int userId) {
5902        int numMatch = 0;
5903        final PermissionsState permissionsState = ps.getPermissionsState();
5904        for (int i=0; i<permissions.length; i++) {
5905            final String permission = permissions[i];
5906            if (permissionsState.hasPermission(permission, userId)) {
5907                tmp[i] = true;
5908                numMatch++;
5909            } else {
5910                tmp[i] = false;
5911            }
5912        }
5913        if (numMatch == 0) {
5914            return;
5915        }
5916        PackageInfo pi;
5917        if (ps.pkg != null) {
5918            pi = generatePackageInfo(ps.pkg, flags, userId);
5919        } else {
5920            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5921        }
5922        // The above might return null in cases of uninstalled apps or install-state
5923        // skew across users/profiles.
5924        if (pi != null) {
5925            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5926                if (numMatch == permissions.length) {
5927                    pi.requestedPermissions = permissions;
5928                } else {
5929                    pi.requestedPermissions = new String[numMatch];
5930                    numMatch = 0;
5931                    for (int i=0; i<permissions.length; i++) {
5932                        if (tmp[i]) {
5933                            pi.requestedPermissions[numMatch] = permissions[i];
5934                            numMatch++;
5935                        }
5936                    }
5937                }
5938            }
5939            list.add(pi);
5940        }
5941    }
5942
5943    @Override
5944    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5945            String[] permissions, int flags, int userId) {
5946        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5947        flags = updateFlagsForPackage(flags, userId, permissions);
5948        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5949
5950        // writer
5951        synchronized (mPackages) {
5952            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5953            boolean[] tmpBools = new boolean[permissions.length];
5954            if (listUninstalled) {
5955                for (PackageSetting ps : mSettings.mPackages.values()) {
5956                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5957                }
5958            } else {
5959                for (PackageParser.Package pkg : mPackages.values()) {
5960                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5961                    if (ps != null) {
5962                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5963                                userId);
5964                    }
5965                }
5966            }
5967
5968            return new ParceledListSlice<PackageInfo>(list);
5969        }
5970    }
5971
5972    @Override
5973    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5974        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5975        flags = updateFlagsForApplication(flags, userId, null);
5976        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5977
5978        // writer
5979        synchronized (mPackages) {
5980            ArrayList<ApplicationInfo> list;
5981            if (listUninstalled) {
5982                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5983                for (PackageSetting ps : mSettings.mPackages.values()) {
5984                    ApplicationInfo ai;
5985                    if (ps.pkg != null) {
5986                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5987                                ps.readUserState(userId), userId);
5988                    } else {
5989                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5990                    }
5991                    if (ai != null) {
5992                        list.add(ai);
5993                    }
5994                }
5995            } else {
5996                list = new ArrayList<ApplicationInfo>(mPackages.size());
5997                for (PackageParser.Package p : mPackages.values()) {
5998                    if (p.mExtras != null) {
5999                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6000                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6001                        if (ai != null) {
6002                            list.add(ai);
6003                        }
6004                    }
6005                }
6006            }
6007
6008            return new ParceledListSlice<ApplicationInfo>(list);
6009        }
6010    }
6011
6012    @Override
6013    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6014        if (DISABLE_EPHEMERAL_APPS) {
6015            return null;
6016        }
6017
6018        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6019                "getEphemeralApplications");
6020        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6021                true /* requireFullPermission */, false /* checkShell */,
6022                "getEphemeralApplications");
6023        synchronized (mPackages) {
6024            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6025                    .getEphemeralApplicationsLPw(userId);
6026            if (ephemeralApps != null) {
6027                return new ParceledListSlice<>(ephemeralApps);
6028            }
6029        }
6030        return null;
6031    }
6032
6033    @Override
6034    public boolean isEphemeralApplication(String packageName, int userId) {
6035        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6036                true /* requireFullPermission */, false /* checkShell */,
6037                "isEphemeral");
6038        if (DISABLE_EPHEMERAL_APPS) {
6039            return false;
6040        }
6041
6042        if (!isCallerSameApp(packageName)) {
6043            return false;
6044        }
6045        synchronized (mPackages) {
6046            PackageParser.Package pkg = mPackages.get(packageName);
6047            if (pkg != null) {
6048                return pkg.applicationInfo.isEphemeralApp();
6049            }
6050        }
6051        return false;
6052    }
6053
6054    @Override
6055    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6056        if (DISABLE_EPHEMERAL_APPS) {
6057            return null;
6058        }
6059
6060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6061                true /* requireFullPermission */, false /* checkShell */,
6062                "getCookie");
6063        if (!isCallerSameApp(packageName)) {
6064            return null;
6065        }
6066        synchronized (mPackages) {
6067            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6068                    packageName, userId);
6069        }
6070    }
6071
6072    @Override
6073    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6074        if (DISABLE_EPHEMERAL_APPS) {
6075            return true;
6076        }
6077
6078        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6079                true /* requireFullPermission */, true /* checkShell */,
6080                "setCookie");
6081        if (!isCallerSameApp(packageName)) {
6082            return false;
6083        }
6084        synchronized (mPackages) {
6085            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6086                    packageName, cookie, userId);
6087        }
6088    }
6089
6090    @Override
6091    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6092        if (DISABLE_EPHEMERAL_APPS) {
6093            return null;
6094        }
6095
6096        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6097                "getEphemeralApplicationIcon");
6098        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6099                true /* requireFullPermission */, false /* checkShell */,
6100                "getEphemeralApplicationIcon");
6101        synchronized (mPackages) {
6102            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6103                    packageName, userId);
6104        }
6105    }
6106
6107    private boolean isCallerSameApp(String packageName) {
6108        PackageParser.Package pkg = mPackages.get(packageName);
6109        return pkg != null
6110                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6111    }
6112
6113    @Override
6114    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6115        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6116    }
6117
6118    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6119        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6120
6121        // reader
6122        synchronized (mPackages) {
6123            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6124            final int userId = UserHandle.getCallingUserId();
6125            while (i.hasNext()) {
6126                final PackageParser.Package p = i.next();
6127                if (p.applicationInfo == null) continue;
6128
6129                final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0)
6130                        && !p.applicationInfo.isEncryptionAware();
6131                final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0)
6132                        && p.applicationInfo.isEncryptionAware();
6133
6134                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6135                        && (!mSafeMode || isSystemApp(p))
6136                        && (matchesUnaware || matchesAware)) {
6137                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6138                    if (ps != null) {
6139                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6140                                ps.readUserState(userId), userId);
6141                        if (ai != null) {
6142                            finalList.add(ai);
6143                        }
6144                    }
6145                }
6146            }
6147        }
6148
6149        return finalList;
6150    }
6151
6152    @Override
6153    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6154        if (!sUserManager.exists(userId)) return null;
6155        flags = updateFlagsForComponent(flags, userId, name);
6156        // reader
6157        synchronized (mPackages) {
6158            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6159            PackageSetting ps = provider != null
6160                    ? mSettings.mPackages.get(provider.owner.packageName)
6161                    : null;
6162            return ps != null
6163                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6164                    ? PackageParser.generateProviderInfo(provider, flags,
6165                            ps.readUserState(userId), userId)
6166                    : null;
6167        }
6168    }
6169
6170    /**
6171     * @deprecated
6172     */
6173    @Deprecated
6174    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6175        // reader
6176        synchronized (mPackages) {
6177            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6178                    .entrySet().iterator();
6179            final int userId = UserHandle.getCallingUserId();
6180            while (i.hasNext()) {
6181                Map.Entry<String, PackageParser.Provider> entry = i.next();
6182                PackageParser.Provider p = entry.getValue();
6183                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6184
6185                if (ps != null && p.syncable
6186                        && (!mSafeMode || (p.info.applicationInfo.flags
6187                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6188                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6189                            ps.readUserState(userId), userId);
6190                    if (info != null) {
6191                        outNames.add(entry.getKey());
6192                        outInfo.add(info);
6193                    }
6194                }
6195            }
6196        }
6197    }
6198
6199    @Override
6200    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6201            int uid, int flags) {
6202        final int userId = processName != null ? UserHandle.getUserId(uid)
6203                : UserHandle.getCallingUserId();
6204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6205        flags = updateFlagsForComponent(flags, userId, processName);
6206
6207        ArrayList<ProviderInfo> finalList = null;
6208        // reader
6209        synchronized (mPackages) {
6210            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6211            while (i.hasNext()) {
6212                final PackageParser.Provider p = i.next();
6213                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6214                if (ps != null && p.info.authority != null
6215                        && (processName == null
6216                                || (p.info.processName.equals(processName)
6217                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6218                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6219                    if (finalList == null) {
6220                        finalList = new ArrayList<ProviderInfo>(3);
6221                    }
6222                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6223                            ps.readUserState(userId), userId);
6224                    if (info != null) {
6225                        finalList.add(info);
6226                    }
6227                }
6228            }
6229        }
6230
6231        if (finalList != null) {
6232            Collections.sort(finalList, mProviderInitOrderSorter);
6233            return new ParceledListSlice<ProviderInfo>(finalList);
6234        }
6235
6236        return ParceledListSlice.emptyList();
6237    }
6238
6239    @Override
6240    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6241        // reader
6242        synchronized (mPackages) {
6243            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6244            return PackageParser.generateInstrumentationInfo(i, flags);
6245        }
6246    }
6247
6248    @Override
6249    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6250            String targetPackage, int flags) {
6251        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6252    }
6253
6254    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6255            int flags) {
6256        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6257
6258        // reader
6259        synchronized (mPackages) {
6260            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6261            while (i.hasNext()) {
6262                final PackageParser.Instrumentation p = i.next();
6263                if (targetPackage == null
6264                        || targetPackage.equals(p.info.targetPackage)) {
6265                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6266                            flags);
6267                    if (ii != null) {
6268                        finalList.add(ii);
6269                    }
6270                }
6271            }
6272        }
6273
6274        return finalList;
6275    }
6276
6277    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6278        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6279        if (overlays == null) {
6280            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6281            return;
6282        }
6283        for (PackageParser.Package opkg : overlays.values()) {
6284            // Not much to do if idmap fails: we already logged the error
6285            // and we certainly don't want to abort installation of pkg simply
6286            // because an overlay didn't fit properly. For these reasons,
6287            // ignore the return value of createIdmapForPackagePairLI.
6288            createIdmapForPackagePairLI(pkg, opkg);
6289        }
6290    }
6291
6292    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6293            PackageParser.Package opkg) {
6294        if (!opkg.mTrustedOverlay) {
6295            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6296                    opkg.baseCodePath + ": overlay not trusted");
6297            return false;
6298        }
6299        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6300        if (overlaySet == null) {
6301            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6302                    opkg.baseCodePath + " but target package has no known overlays");
6303            return false;
6304        }
6305        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6306        // TODO: generate idmap for split APKs
6307        try {
6308            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6309        } catch (InstallerException e) {
6310            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6311                    + opkg.baseCodePath);
6312            return false;
6313        }
6314        PackageParser.Package[] overlayArray =
6315            overlaySet.values().toArray(new PackageParser.Package[0]);
6316        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6317            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6318                return p1.mOverlayPriority - p2.mOverlayPriority;
6319            }
6320        };
6321        Arrays.sort(overlayArray, cmp);
6322
6323        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6324        int i = 0;
6325        for (PackageParser.Package p : overlayArray) {
6326            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6327        }
6328        return true;
6329    }
6330
6331    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6332        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6333        try {
6334            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6335        } finally {
6336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6337        }
6338    }
6339
6340    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6341        final File[] files = dir.listFiles();
6342        if (ArrayUtils.isEmpty(files)) {
6343            Log.d(TAG, "No files in app dir " + dir);
6344            return;
6345        }
6346
6347        if (DEBUG_PACKAGE_SCANNING) {
6348            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6349                    + " flags=0x" + Integer.toHexString(parseFlags));
6350        }
6351
6352        for (File file : files) {
6353            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6354                    && !PackageInstallerService.isStageName(file.getName());
6355            if (!isPackage) {
6356                // Ignore entries which are not packages
6357                continue;
6358            }
6359            try {
6360                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6361                        scanFlags, currentTime, null);
6362            } catch (PackageManagerException e) {
6363                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6364
6365                // Delete invalid userdata apps
6366                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6367                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6368                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6369                    removeCodePathLI(file);
6370                }
6371            }
6372        }
6373    }
6374
6375    private static File getSettingsProblemFile() {
6376        File dataDir = Environment.getDataDirectory();
6377        File systemDir = new File(dataDir, "system");
6378        File fname = new File(systemDir, "uiderrors.txt");
6379        return fname;
6380    }
6381
6382    static void reportSettingsProblem(int priority, String msg) {
6383        logCriticalInfo(priority, msg);
6384    }
6385
6386    static void logCriticalInfo(int priority, String msg) {
6387        Slog.println(priority, TAG, msg);
6388        EventLogTags.writePmCriticalInfo(msg);
6389        try {
6390            File fname = getSettingsProblemFile();
6391            FileOutputStream out = new FileOutputStream(fname, true);
6392            PrintWriter pw = new FastPrintWriter(out);
6393            SimpleDateFormat formatter = new SimpleDateFormat();
6394            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6395            pw.println(dateString + ": " + msg);
6396            pw.close();
6397            FileUtils.setPermissions(
6398                    fname.toString(),
6399                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6400                    -1, -1);
6401        } catch (java.io.IOException e) {
6402        }
6403    }
6404
6405    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6406            int parseFlags) throws PackageManagerException {
6407        if (ps != null
6408                && ps.codePath.equals(srcFile)
6409                && ps.timeStamp == srcFile.lastModified()
6410                && !isCompatSignatureUpdateNeeded(pkg)
6411                && !isRecoverSignatureUpdateNeeded(pkg)) {
6412            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6413            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6414            ArraySet<PublicKey> signingKs;
6415            synchronized (mPackages) {
6416                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6417            }
6418            if (ps.signatures.mSignatures != null
6419                    && ps.signatures.mSignatures.length != 0
6420                    && signingKs != null) {
6421                // Optimization: reuse the existing cached certificates
6422                // if the package appears to be unchanged.
6423                pkg.mSignatures = ps.signatures.mSignatures;
6424                pkg.mSigningKeys = signingKs;
6425                return;
6426            }
6427
6428            Slog.w(TAG, "PackageSetting for " + ps.name
6429                    + " is missing signatures.  Collecting certs again to recover them.");
6430        } else {
6431            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6432        }
6433
6434        try {
6435            PackageParser.collectCertificates(pkg, parseFlags);
6436        } catch (PackageParserException e) {
6437            throw PackageManagerException.from(e);
6438        }
6439    }
6440
6441    /**
6442     *  Traces a package scan.
6443     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6444     */
6445    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6446            long currentTime, UserHandle user) throws PackageManagerException {
6447        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6448        try {
6449            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6450        } finally {
6451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6452        }
6453    }
6454
6455    /**
6456     *  Scans a package and returns the newly parsed package.
6457     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6458     */
6459    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6460            long currentTime, UserHandle user) throws PackageManagerException {
6461        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6462        parseFlags |= mDefParseFlags;
6463        PackageParser pp = new PackageParser();
6464        pp.setSeparateProcesses(mSeparateProcesses);
6465        pp.setOnlyCoreApps(mOnlyCore);
6466        pp.setDisplayMetrics(mMetrics);
6467
6468        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6469            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6470        }
6471
6472        final PackageParser.Package pkg;
6473        try {
6474            pkg = pp.parsePackage(scanFile, parseFlags);
6475        } catch (PackageParserException e) {
6476            throw PackageManagerException.from(e);
6477        }
6478
6479        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6480    }
6481
6482    /**
6483     *  Scans a package and returns the newly parsed package.
6484     *  @throws PackageManagerException on a parse error.
6485     */
6486    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6487            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6488            throws PackageManagerException {
6489        // If the package has children and this is the first dive in the function
6490        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6491        // packages (parent and children) would be successfully scanned before the
6492        // actual scan since scanning mutates internal state and we want to atomically
6493        // install the package and its children.
6494        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6495            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6496                scanFlags |= SCAN_CHECK_ONLY;
6497            }
6498        } else {
6499            scanFlags &= ~SCAN_CHECK_ONLY;
6500        }
6501
6502        // Scan the parent
6503        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6504                scanFlags, currentTime, user);
6505
6506        // Scan the children
6507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6508        for (int i = 0; i < childCount; i++) {
6509            PackageParser.Package childPackage = pkg.childPackages.get(i);
6510            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6511                    currentTime, user);
6512        }
6513
6514
6515        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6516            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6517        }
6518
6519        return scannedPkg;
6520    }
6521
6522    /**
6523     *  Scans a package and returns the newly parsed package.
6524     *  @throws PackageManagerException on a parse error.
6525     */
6526    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6527            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6528            throws PackageManagerException {
6529        PackageSetting ps = null;
6530        PackageSetting updatedPkg;
6531        // reader
6532        synchronized (mPackages) {
6533            // Look to see if we already know about this package.
6534            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6535            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6536                // This package has been renamed to its original name.  Let's
6537                // use that.
6538                ps = mSettings.peekPackageLPr(oldName);
6539            }
6540            // If there was no original package, see one for the real package name.
6541            if (ps == null) {
6542                ps = mSettings.peekPackageLPr(pkg.packageName);
6543            }
6544            // Check to see if this package could be hiding/updating a system
6545            // package.  Must look for it either under the original or real
6546            // package name depending on our state.
6547            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6548            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6549
6550            // If this is a package we don't know about on the system partition, we
6551            // may need to remove disabled child packages on the system partition
6552            // or may need to not add child packages if the parent apk is updated
6553            // on the data partition and no longer defines this child package.
6554            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6555                // If this is a parent package for an updated system app and this system
6556                // app got an OTA update which no longer defines some of the child packages
6557                // we have to prune them from the disabled system packages.
6558                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6559                if (disabledPs != null) {
6560                    final int scannedChildCount = (pkg.childPackages != null)
6561                            ? pkg.childPackages.size() : 0;
6562                    final int disabledChildCount = disabledPs.childPackageNames != null
6563                            ? disabledPs.childPackageNames.size() : 0;
6564                    for (int i = 0; i < disabledChildCount; i++) {
6565                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6566                        boolean disabledPackageAvailable = false;
6567                        for (int j = 0; j < scannedChildCount; j++) {
6568                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6569                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6570                                disabledPackageAvailable = true;
6571                                break;
6572                            }
6573                         }
6574                         if (!disabledPackageAvailable) {
6575                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6576                         }
6577                    }
6578                }
6579            }
6580        }
6581
6582        boolean updatedPkgBetter = false;
6583        // First check if this is a system package that may involve an update
6584        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6585            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6586            // it needs to drop FLAG_PRIVILEGED.
6587            if (locationIsPrivileged(scanFile)) {
6588                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6589            } else {
6590                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6591            }
6592
6593            if (ps != null && !ps.codePath.equals(scanFile)) {
6594                // The path has changed from what was last scanned...  check the
6595                // version of the new path against what we have stored to determine
6596                // what to do.
6597                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6598                if (pkg.mVersionCode <= ps.versionCode) {
6599                    // The system package has been updated and the code path does not match
6600                    // Ignore entry. Skip it.
6601                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6602                            + " ignored: updated version " + ps.versionCode
6603                            + " better than this " + pkg.mVersionCode);
6604                    if (!updatedPkg.codePath.equals(scanFile)) {
6605                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6606                                + ps.name + " changing from " + updatedPkg.codePathString
6607                                + " to " + scanFile);
6608                        updatedPkg.codePath = scanFile;
6609                        updatedPkg.codePathString = scanFile.toString();
6610                        updatedPkg.resourcePath = scanFile;
6611                        updatedPkg.resourcePathString = scanFile.toString();
6612                    }
6613                    updatedPkg.pkg = pkg;
6614                    updatedPkg.versionCode = pkg.mVersionCode;
6615
6616                    // Update the disabled system child packages to point to the package too.
6617                    final int childCount = updatedPkg.childPackageNames != null
6618                            ? updatedPkg.childPackageNames.size() : 0;
6619                    for (int i = 0; i < childCount; i++) {
6620                        String childPackageName = updatedPkg.childPackageNames.get(i);
6621                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6622                                childPackageName);
6623                        if (updatedChildPkg != null) {
6624                            updatedChildPkg.pkg = pkg;
6625                            updatedChildPkg.versionCode = pkg.mVersionCode;
6626                        }
6627                    }
6628
6629                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6630                            + scanFile + " ignored: updated version " + ps.versionCode
6631                            + " better than this " + pkg.mVersionCode);
6632                } else {
6633                    // The current app on the system partition is better than
6634                    // what we have updated to on the data partition; switch
6635                    // back to the system partition version.
6636                    // At this point, its safely assumed that package installation for
6637                    // apps in system partition will go through. If not there won't be a working
6638                    // version of the app
6639                    // writer
6640                    synchronized (mPackages) {
6641                        // Just remove the loaded entries from package lists.
6642                        mPackages.remove(ps.name);
6643                    }
6644
6645                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6646                            + " reverting from " + ps.codePathString
6647                            + ": new version " + pkg.mVersionCode
6648                            + " better than installed " + ps.versionCode);
6649
6650                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6651                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6652                    synchronized (mInstallLock) {
6653                        args.cleanUpResourcesLI();
6654                    }
6655                    synchronized (mPackages) {
6656                        mSettings.enableSystemPackageLPw(ps.name);
6657                    }
6658                    updatedPkgBetter = true;
6659                }
6660            }
6661        }
6662
6663        if (updatedPkg != null) {
6664            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6665            // initially
6666            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6667
6668            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6669            // flag set initially
6670            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6671                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6672            }
6673        }
6674
6675        // Verify certificates against what was last scanned
6676        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6677
6678        /*
6679         * A new system app appeared, but we already had a non-system one of the
6680         * same name installed earlier.
6681         */
6682        boolean shouldHideSystemApp = false;
6683        if (updatedPkg == null && ps != null
6684                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6685            /*
6686             * Check to make sure the signatures match first. If they don't,
6687             * wipe the installed application and its data.
6688             */
6689            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6690                    != PackageManager.SIGNATURE_MATCH) {
6691                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6692                        + " signatures don't match existing userdata copy; removing");
6693                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6694                ps = null;
6695            } else {
6696                /*
6697                 * If the newly-added system app is an older version than the
6698                 * already installed version, hide it. It will be scanned later
6699                 * and re-added like an update.
6700                 */
6701                if (pkg.mVersionCode <= ps.versionCode) {
6702                    shouldHideSystemApp = true;
6703                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6704                            + " but new version " + pkg.mVersionCode + " better than installed "
6705                            + ps.versionCode + "; hiding system");
6706                } else {
6707                    /*
6708                     * The newly found system app is a newer version that the
6709                     * one previously installed. Simply remove the
6710                     * already-installed application and replace it with our own
6711                     * while keeping the application data.
6712                     */
6713                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6714                            + " reverting from " + ps.codePathString + ": new version "
6715                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6716                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6717                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6718                    synchronized (mInstallLock) {
6719                        args.cleanUpResourcesLI();
6720                    }
6721                }
6722            }
6723        }
6724
6725        // The apk is forward locked (not public) if its code and resources
6726        // are kept in different files. (except for app in either system or
6727        // vendor path).
6728        // TODO grab this value from PackageSettings
6729        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6730            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6731                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6732            }
6733        }
6734
6735        // TODO: extend to support forward-locked splits
6736        String resourcePath = null;
6737        String baseResourcePath = null;
6738        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6739            if (ps != null && ps.resourcePathString != null) {
6740                resourcePath = ps.resourcePathString;
6741                baseResourcePath = ps.resourcePathString;
6742            } else {
6743                // Should not happen at all. Just log an error.
6744                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6745            }
6746        } else {
6747            resourcePath = pkg.codePath;
6748            baseResourcePath = pkg.baseCodePath;
6749        }
6750
6751        // Set application objects path explicitly.
6752        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6753        pkg.setApplicationInfoCodePath(pkg.codePath);
6754        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6755        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6756        pkg.setApplicationInfoResourcePath(resourcePath);
6757        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6758        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6759
6760        // Note that we invoke the following method only if we are about to unpack an application
6761        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6762                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6763
6764        /*
6765         * If the system app should be overridden by a previously installed
6766         * data, hide the system app now and let the /data/app scan pick it up
6767         * again.
6768         */
6769        if (shouldHideSystemApp) {
6770            synchronized (mPackages) {
6771                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6772            }
6773        }
6774
6775        return scannedPkg;
6776    }
6777
6778    private static String fixProcessName(String defProcessName,
6779            String processName, int uid) {
6780        if (processName == null) {
6781            return defProcessName;
6782        }
6783        return processName;
6784    }
6785
6786    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6787            throws PackageManagerException {
6788        if (pkgSetting.signatures.mSignatures != null) {
6789            // Already existing package. Make sure signatures match
6790            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6791                    == PackageManager.SIGNATURE_MATCH;
6792            if (!match) {
6793                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6794                        == PackageManager.SIGNATURE_MATCH;
6795            }
6796            if (!match) {
6797                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6798                        == PackageManager.SIGNATURE_MATCH;
6799            }
6800            if (!match) {
6801                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6802                        + pkg.packageName + " signatures do not match the "
6803                        + "previously installed version; ignoring!");
6804            }
6805        }
6806
6807        // Check for shared user signatures
6808        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6809            // Already existing package. Make sure signatures match
6810            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6811                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6812            if (!match) {
6813                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6814                        == PackageManager.SIGNATURE_MATCH;
6815            }
6816            if (!match) {
6817                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6818                        == PackageManager.SIGNATURE_MATCH;
6819            }
6820            if (!match) {
6821                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6822                        "Package " + pkg.packageName
6823                        + " has no signatures that match those in shared user "
6824                        + pkgSetting.sharedUser.name + "; ignoring!");
6825            }
6826        }
6827    }
6828
6829    /**
6830     * Enforces that only the system UID or root's UID can call a method exposed
6831     * via Binder.
6832     *
6833     * @param message used as message if SecurityException is thrown
6834     * @throws SecurityException if the caller is not system or root
6835     */
6836    private static final void enforceSystemOrRoot(String message) {
6837        final int uid = Binder.getCallingUid();
6838        if (uid != Process.SYSTEM_UID && uid != 0) {
6839            throw new SecurityException(message);
6840        }
6841    }
6842
6843    @Override
6844    public void performFstrimIfNeeded() {
6845        enforceSystemOrRoot("Only the system can request fstrim");
6846
6847        // Before everything else, see whether we need to fstrim.
6848        try {
6849            IMountService ms = PackageHelper.getMountService();
6850            if (ms != null) {
6851                final boolean isUpgrade = isUpgrade();
6852                boolean doTrim = isUpgrade;
6853                if (doTrim) {
6854                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6855                } else {
6856                    final long interval = android.provider.Settings.Global.getLong(
6857                            mContext.getContentResolver(),
6858                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6859                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6860                    if (interval > 0) {
6861                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6862                        if (timeSinceLast > interval) {
6863                            doTrim = true;
6864                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6865                                    + "; running immediately");
6866                        }
6867                    }
6868                }
6869                if (doTrim) {
6870                    if (!isFirstBoot()) {
6871                        try {
6872                            ActivityManagerNative.getDefault().showBootMessage(
6873                                    mContext.getResources().getString(
6874                                            R.string.android_upgrading_fstrim), true);
6875                        } catch (RemoteException e) {
6876                        }
6877                    }
6878                    ms.runMaintenance();
6879                }
6880            } else {
6881                Slog.e(TAG, "Mount service unavailable!");
6882            }
6883        } catch (RemoteException e) {
6884            // Can't happen; MountService is local
6885        }
6886    }
6887
6888    @Override
6889    public void extractPackagesIfNeeded() {
6890        enforceSystemOrRoot("Only the system can request package extraction");
6891
6892        // Extract pacakges only if profile-guided compilation is enabled because
6893        // otherwise BackgroundDexOptService will not dexopt them later.
6894        boolean prunedCache = VMRuntime.didPruneDalvikCache();
6895        if (!isUpgrade() && !prunedCache) {
6896            return;
6897        }
6898
6899        List<PackageParser.Package> pkgs;
6900        synchronized (mPackages) {
6901            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6902        }
6903
6904        int curr = 0;
6905        int total = pkgs.size();
6906        for (PackageParser.Package pkg : pkgs) {
6907            curr++;
6908
6909            if (DEBUG_DEXOPT) {
6910                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6911            }
6912
6913            if (!isFirstBoot()) {
6914                try {
6915                    ActivityManagerNative.getDefault().showBootMessage(
6916                            mContext.getResources().getString(R.string.android_upgrading_apk,
6917                                    curr, total), true);
6918                } catch (RemoteException e) {
6919                }
6920            }
6921
6922            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6923                // If the cache was pruned, any compiled odex files will likely be out of date
6924                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
6925                // Instead, force the extraction in this case.
6926                performDexOpt(pkg.packageName, null /* instructionSet */,
6927                         false /* useProfiles */, true /* extractOnly */, prunedCache);
6928            }
6929        }
6930    }
6931
6932    @Override
6933    public void notifyPackageUse(String packageName) {
6934        synchronized (mPackages) {
6935            PackageParser.Package p = mPackages.get(packageName);
6936            if (p == null) {
6937                return;
6938            }
6939            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6940        }
6941    }
6942
6943    // TODO: this is not used nor needed. Delete it.
6944    @Override
6945    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6946        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6947                false /* extractOnly */, false /* force */);
6948    }
6949
6950    @Override
6951    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6952            boolean extractOnly, boolean force) {
6953        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6954    }
6955
6956    private boolean performDexOptTraced(String packageName, String instructionSet,
6957                boolean useProfiles, boolean extractOnly, boolean force) {
6958        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6959        try {
6960            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6961                    force);
6962        } finally {
6963            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6964        }
6965    }
6966
6967    private boolean performDexOptInternal(String packageName, String instructionSet,
6968                boolean useProfiles, boolean extractOnly, boolean force) {
6969        PackageParser.Package p;
6970        final String targetInstructionSet;
6971        synchronized (mPackages) {
6972            p = mPackages.get(packageName);
6973            if (p == null) {
6974                return false;
6975            }
6976            mPackageUsage.write(false);
6977
6978            targetInstructionSet = instructionSet != null ? instructionSet :
6979                    getPrimaryInstructionSet(p.applicationInfo);
6980        }
6981        long callingId = Binder.clearCallingIdentity();
6982        try {
6983            synchronized (mInstallLock) {
6984                final String[] instructionSets = new String[] { targetInstructionSet };
6985                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6986                        useProfiles, extractOnly, force);
6987                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6988            }
6989        } finally {
6990            Binder.restoreCallingIdentity(callingId);
6991        }
6992    }
6993
6994    public ArraySet<String> getOptimizablePackages() {
6995        ArraySet<String> pkgs = new ArraySet<String>();
6996        synchronized (mPackages) {
6997            for (PackageParser.Package p : mPackages.values()) {
6998                if (PackageDexOptimizer.canOptimizePackage(p)) {
6999                    pkgs.add(p.packageName);
7000                }
7001            }
7002        }
7003        return pkgs;
7004    }
7005
7006    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7007            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
7008        // Select the dex optimizer based on the force parameter.
7009        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7010        //       allocate an object here.
7011        PackageDexOptimizer pdo = force
7012                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7013                : mPackageDexOptimizer;
7014
7015        // Optimize all dependencies first. Note: we ignore the return value and march on
7016        // on errors.
7017        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7018        if (!deps.isEmpty()) {
7019            for (PackageParser.Package depPackage : deps) {
7020                // TODO: Analyze and investigate if we (should) profile libraries.
7021                // Currently this will do a full compilation of the library.
7022                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
7023                        false /* extractOnly */);
7024            }
7025        }
7026
7027        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
7028    }
7029
7030    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7031        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7032            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7033            Set<String> collectedNames = new HashSet<>();
7034            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7035
7036            retValue.remove(p);
7037
7038            return retValue;
7039        } else {
7040            return Collections.emptyList();
7041        }
7042    }
7043
7044    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7045            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7046        if (!collectedNames.contains(p.packageName)) {
7047            collectedNames.add(p.packageName);
7048            collected.add(p);
7049
7050            if (p.usesLibraries != null) {
7051                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7052            }
7053            if (p.usesOptionalLibraries != null) {
7054                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7055                        collectedNames);
7056            }
7057        }
7058    }
7059
7060    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7061            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7062        for (String libName : libs) {
7063            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7064            if (libPkg != null) {
7065                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7066            }
7067        }
7068    }
7069
7070    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7071        synchronized (mPackages) {
7072            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7073            if (lib != null && lib.apk != null) {
7074                return mPackages.get(lib.apk);
7075            }
7076        }
7077        return null;
7078    }
7079
7080    public void shutdown() {
7081        mPackageUsage.write(true);
7082    }
7083
7084    @Override
7085    public void forceDexOpt(String packageName) {
7086        enforceSystemOrRoot("forceDexOpt");
7087
7088        PackageParser.Package pkg;
7089        synchronized (mPackages) {
7090            pkg = mPackages.get(packageName);
7091            if (pkg == null) {
7092                throw new IllegalArgumentException("Unknown package: " + packageName);
7093            }
7094        }
7095
7096        synchronized (mInstallLock) {
7097            final String[] instructionSets = new String[] {
7098                    getPrimaryInstructionSet(pkg.applicationInfo) };
7099
7100            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7101
7102            // Whoever is calling forceDexOpt wants a fully compiled package.
7103            // Don't use profiles since that may cause compilation to be skipped.
7104            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7105                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7106
7107            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7108            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7109                throw new IllegalStateException("Failed to dexopt: " + res);
7110            }
7111        }
7112    }
7113
7114    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7115        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7116            Slog.w(TAG, "Unable to update from " + oldPkg.name
7117                    + " to " + newPkg.packageName
7118                    + ": old package not in system partition");
7119            return false;
7120        } else if (mPackages.get(oldPkg.name) != null) {
7121            Slog.w(TAG, "Unable to update from " + oldPkg.name
7122                    + " to " + newPkg.packageName
7123                    + ": old package still exists");
7124            return false;
7125        }
7126        return true;
7127    }
7128
7129    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7130        // TODO: triage flags as part of 26466827
7131        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7132
7133        boolean res = true;
7134        final int[] users = sUserManager.getUserIds();
7135        for (int user : users) {
7136            try {
7137                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7138            } catch (InstallerException e) {
7139                Slog.w(TAG, "Failed to delete data directory", e);
7140                res = false;
7141            }
7142        }
7143        return res;
7144    }
7145
7146    void removeCodePathLI(File codePath) {
7147        if (codePath.isDirectory()) {
7148            try {
7149                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7150            } catch (InstallerException e) {
7151                Slog.w(TAG, "Failed to remove code path", e);
7152            }
7153        } else {
7154            codePath.delete();
7155        }
7156    }
7157
7158    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7159        try {
7160            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7161        } catch (InstallerException e) {
7162            Slog.w(TAG, "Failed to destroy app data", e);
7163        }
7164    }
7165
7166    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7167            int appId, String seinfo) {
7168        try {
7169            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7170        } catch (InstallerException e) {
7171            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7172        }
7173    }
7174
7175    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7176        final PackageParser.Package pkg;
7177        synchronized (mPackages) {
7178            pkg = mPackages.get(packageName);
7179        }
7180        if (pkg == null) {
7181            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7182            return;
7183        }
7184        deleteCodeCacheDirsLI(pkg);
7185    }
7186
7187    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7188        // TODO: triage flags as part of 26466827
7189        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7190
7191        int[] users = sUserManager.getUserIds();
7192        int res = 0;
7193        for (int user : users) {
7194            // Remove the parent code cache
7195            try {
7196                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7197                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7198            } catch (InstallerException e) {
7199                Slog.w(TAG, "Failed to delete code cache directory", e);
7200            }
7201            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7202            for (int i = 0; i < childCount; i++) {
7203                PackageParser.Package childPkg = pkg.childPackages.get(i);
7204                // Remove the child code cache
7205                try {
7206                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7207                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7208                } catch (InstallerException e) {
7209                    Slog.w(TAG, "Failed to delete code cache directory", e);
7210                }
7211            }
7212        }
7213    }
7214
7215    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7216            long lastUpdateTime) {
7217        // Set parent install/update time
7218        PackageSetting ps = (PackageSetting) pkg.mExtras;
7219        if (ps != null) {
7220            ps.firstInstallTime = firstInstallTime;
7221            ps.lastUpdateTime = lastUpdateTime;
7222        }
7223        // Set children install/update time
7224        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7225        for (int i = 0; i < childCount; i++) {
7226            PackageParser.Package childPkg = pkg.childPackages.get(i);
7227            ps = (PackageSetting) childPkg.mExtras;
7228            if (ps != null) {
7229                ps.firstInstallTime = firstInstallTime;
7230                ps.lastUpdateTime = lastUpdateTime;
7231            }
7232        }
7233    }
7234
7235    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7236            PackageParser.Package changingLib) {
7237        if (file.path != null) {
7238            usesLibraryFiles.add(file.path);
7239            return;
7240        }
7241        PackageParser.Package p = mPackages.get(file.apk);
7242        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7243            // If we are doing this while in the middle of updating a library apk,
7244            // then we need to make sure to use that new apk for determining the
7245            // dependencies here.  (We haven't yet finished committing the new apk
7246            // to the package manager state.)
7247            if (p == null || p.packageName.equals(changingLib.packageName)) {
7248                p = changingLib;
7249            }
7250        }
7251        if (p != null) {
7252            usesLibraryFiles.addAll(p.getAllCodePaths());
7253        }
7254    }
7255
7256    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7257            PackageParser.Package changingLib) throws PackageManagerException {
7258        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7259            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7260            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7261            for (int i=0; i<N; i++) {
7262                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7263                if (file == null) {
7264                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7265                            "Package " + pkg.packageName + " requires unavailable shared library "
7266                            + pkg.usesLibraries.get(i) + "; failing!");
7267                }
7268                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7269            }
7270            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7271            for (int i=0; i<N; i++) {
7272                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7273                if (file == null) {
7274                    Slog.w(TAG, "Package " + pkg.packageName
7275                            + " desires unavailable shared library "
7276                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7277                } else {
7278                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7279                }
7280            }
7281            N = usesLibraryFiles.size();
7282            if (N > 0) {
7283                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7284            } else {
7285                pkg.usesLibraryFiles = null;
7286            }
7287        }
7288    }
7289
7290    private static boolean hasString(List<String> list, List<String> which) {
7291        if (list == null) {
7292            return false;
7293        }
7294        for (int i=list.size()-1; i>=0; i--) {
7295            for (int j=which.size()-1; j>=0; j--) {
7296                if (which.get(j).equals(list.get(i))) {
7297                    return true;
7298                }
7299            }
7300        }
7301        return false;
7302    }
7303
7304    private void updateAllSharedLibrariesLPw() {
7305        for (PackageParser.Package pkg : mPackages.values()) {
7306            try {
7307                updateSharedLibrariesLPw(pkg, null);
7308            } catch (PackageManagerException e) {
7309                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7310            }
7311        }
7312    }
7313
7314    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7315            PackageParser.Package changingPkg) {
7316        ArrayList<PackageParser.Package> res = null;
7317        for (PackageParser.Package pkg : mPackages.values()) {
7318            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7319                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7320                if (res == null) {
7321                    res = new ArrayList<PackageParser.Package>();
7322                }
7323                res.add(pkg);
7324                try {
7325                    updateSharedLibrariesLPw(pkg, changingPkg);
7326                } catch (PackageManagerException e) {
7327                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7328                }
7329            }
7330        }
7331        return res;
7332    }
7333
7334    /**
7335     * Derive the value of the {@code cpuAbiOverride} based on the provided
7336     * value and an optional stored value from the package settings.
7337     */
7338    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7339        String cpuAbiOverride = null;
7340
7341        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7342            cpuAbiOverride = null;
7343        } else if (abiOverride != null) {
7344            cpuAbiOverride = abiOverride;
7345        } else if (settings != null) {
7346            cpuAbiOverride = settings.cpuAbiOverrideString;
7347        }
7348
7349        return cpuAbiOverride;
7350    }
7351
7352    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7353            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7354        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7355        // If the package has children and this is the first dive in the function
7356        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7357        // whether all packages (parent and children) would be successfully scanned
7358        // before the actual scan since scanning mutates internal state and we want
7359        // to atomically install the package and its children.
7360        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7361            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7362                scanFlags |= SCAN_CHECK_ONLY;
7363            }
7364        } else {
7365            scanFlags &= ~SCAN_CHECK_ONLY;
7366        }
7367
7368        final PackageParser.Package scannedPkg;
7369        try {
7370            // Scan the parent
7371            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7372            // Scan the children
7373            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7374            for (int i = 0; i < childCount; i++) {
7375                PackageParser.Package childPkg = pkg.childPackages.get(i);
7376                scanPackageLI(childPkg, parseFlags,
7377                        scanFlags, currentTime, user);
7378            }
7379        } finally {
7380            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7381        }
7382
7383        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7384            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7385        }
7386
7387        return scannedPkg;
7388    }
7389
7390    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7391            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7392        boolean success = false;
7393        try {
7394            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7395                    currentTime, user);
7396            success = true;
7397            return res;
7398        } finally {
7399            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7400                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7401            }
7402        }
7403    }
7404
7405    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7406            int scanFlags, long currentTime, UserHandle user)
7407            throws PackageManagerException {
7408        final File scanFile = new File(pkg.codePath);
7409        if (pkg.applicationInfo.getCodePath() == null ||
7410                pkg.applicationInfo.getResourcePath() == null) {
7411            // Bail out. The resource and code paths haven't been set.
7412            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7413                    "Code and resource paths haven't been set correctly");
7414        }
7415
7416        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7417            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7418        } else {
7419            // Only allow system apps to be flagged as core apps.
7420            pkg.coreApp = false;
7421        }
7422
7423        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7424            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7425        }
7426
7427        if (mCustomResolverComponentName != null &&
7428                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7429            setUpCustomResolverActivity(pkg);
7430        }
7431
7432        if (pkg.packageName.equals("android")) {
7433            synchronized (mPackages) {
7434                if (mAndroidApplication != null) {
7435                    Slog.w(TAG, "*************************************************");
7436                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7437                    Slog.w(TAG, " file=" + scanFile);
7438                    Slog.w(TAG, "*************************************************");
7439                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7440                            "Core android package being redefined.  Skipping.");
7441                }
7442
7443                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7444                    // Set up information for our fall-back user intent resolution activity.
7445                    mPlatformPackage = pkg;
7446                    pkg.mVersionCode = mSdkVersion;
7447                    mAndroidApplication = pkg.applicationInfo;
7448
7449                    if (!mResolverReplaced) {
7450                        mResolveActivity.applicationInfo = mAndroidApplication;
7451                        mResolveActivity.name = ResolverActivity.class.getName();
7452                        mResolveActivity.packageName = mAndroidApplication.packageName;
7453                        mResolveActivity.processName = "system:ui";
7454                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7455                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7456                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7457                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7458                        mResolveActivity.exported = true;
7459                        mResolveActivity.enabled = true;
7460                        mResolveInfo.activityInfo = mResolveActivity;
7461                        mResolveInfo.priority = 0;
7462                        mResolveInfo.preferredOrder = 0;
7463                        mResolveInfo.match = 0;
7464                        mResolveComponentName = new ComponentName(
7465                                mAndroidApplication.packageName, mResolveActivity.name);
7466                    }
7467                }
7468            }
7469        }
7470
7471        if (DEBUG_PACKAGE_SCANNING) {
7472            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7473                Log.d(TAG, "Scanning package " + pkg.packageName);
7474        }
7475
7476        synchronized (mPackages) {
7477            if (mPackages.containsKey(pkg.packageName)
7478                    || mSharedLibraries.containsKey(pkg.packageName)) {
7479                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7480                        "Application package " + pkg.packageName
7481                                + " already installed.  Skipping duplicate.");
7482            }
7483
7484            // If we're only installing presumed-existing packages, require that the
7485            // scanned APK is both already known and at the path previously established
7486            // for it.  Previously unknown packages we pick up normally, but if we have an
7487            // a priori expectation about this package's install presence, enforce it.
7488            // With a singular exception for new system packages. When an OTA contains
7489            // a new system package, we allow the codepath to change from a system location
7490            // to the user-installed location. If we don't allow this change, any newer,
7491            // user-installed version of the application will be ignored.
7492            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7493                if (mExpectingBetter.containsKey(pkg.packageName)) {
7494                    logCriticalInfo(Log.WARN,
7495                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7496                } else {
7497                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7498                    if (known != null) {
7499                        if (DEBUG_PACKAGE_SCANNING) {
7500                            Log.d(TAG, "Examining " + pkg.codePath
7501                                    + " and requiring known paths " + known.codePathString
7502                                    + " & " + known.resourcePathString);
7503                        }
7504                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7505                                || !pkg.applicationInfo.getResourcePath().equals(
7506                                known.resourcePathString)) {
7507                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7508                                    "Application package " + pkg.packageName
7509                                            + " found at " + pkg.applicationInfo.getCodePath()
7510                                            + " but expected at " + known.codePathString
7511                                            + "; ignoring.");
7512                        }
7513                    }
7514                }
7515            }
7516        }
7517
7518        // Initialize package source and resource directories
7519        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7520        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7521
7522        SharedUserSetting suid = null;
7523        PackageSetting pkgSetting = null;
7524
7525        if (!isSystemApp(pkg)) {
7526            // Only system apps can use these features.
7527            pkg.mOriginalPackages = null;
7528            pkg.mRealPackage = null;
7529            pkg.mAdoptPermissions = null;
7530        }
7531
7532        // Getting the package setting may have a side-effect, so if we
7533        // are only checking if scan would succeed, stash a copy of the
7534        // old setting to restore at the end.
7535        PackageSetting nonMutatedPs = null;
7536
7537        // writer
7538        synchronized (mPackages) {
7539            if (pkg.mSharedUserId != null) {
7540                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7541                if (suid == null) {
7542                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7543                            "Creating application package " + pkg.packageName
7544                            + " for shared user failed");
7545                }
7546                if (DEBUG_PACKAGE_SCANNING) {
7547                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7548                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7549                                + "): packages=" + suid.packages);
7550                }
7551            }
7552
7553            // Check if we are renaming from an original package name.
7554            PackageSetting origPackage = null;
7555            String realName = null;
7556            if (pkg.mOriginalPackages != null) {
7557                // This package may need to be renamed to a previously
7558                // installed name.  Let's check on that...
7559                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7560                if (pkg.mOriginalPackages.contains(renamed)) {
7561                    // This package had originally been installed as the
7562                    // original name, and we have already taken care of
7563                    // transitioning to the new one.  Just update the new
7564                    // one to continue using the old name.
7565                    realName = pkg.mRealPackage;
7566                    if (!pkg.packageName.equals(renamed)) {
7567                        // Callers into this function may have already taken
7568                        // care of renaming the package; only do it here if
7569                        // it is not already done.
7570                        pkg.setPackageName(renamed);
7571                    }
7572
7573                } else {
7574                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7575                        if ((origPackage = mSettings.peekPackageLPr(
7576                                pkg.mOriginalPackages.get(i))) != null) {
7577                            // We do have the package already installed under its
7578                            // original name...  should we use it?
7579                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7580                                // New package is not compatible with original.
7581                                origPackage = null;
7582                                continue;
7583                            } else if (origPackage.sharedUser != null) {
7584                                // Make sure uid is compatible between packages.
7585                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7586                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7587                                            + " to " + pkg.packageName + ": old uid "
7588                                            + origPackage.sharedUser.name
7589                                            + " differs from " + pkg.mSharedUserId);
7590                                    origPackage = null;
7591                                    continue;
7592                                }
7593                            } else {
7594                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7595                                        + pkg.packageName + " to old name " + origPackage.name);
7596                            }
7597                            break;
7598                        }
7599                    }
7600                }
7601            }
7602
7603            if (mTransferedPackages.contains(pkg.packageName)) {
7604                Slog.w(TAG, "Package " + pkg.packageName
7605                        + " was transferred to another, but its .apk remains");
7606            }
7607
7608            // See comments in nonMutatedPs declaration
7609            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7610                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7611                if (foundPs != null) {
7612                    nonMutatedPs = new PackageSetting(foundPs);
7613                }
7614            }
7615
7616            // Just create the setting, don't add it yet. For already existing packages
7617            // the PkgSetting exists already and doesn't have to be created.
7618            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7619                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7620                    pkg.applicationInfo.primaryCpuAbi,
7621                    pkg.applicationInfo.secondaryCpuAbi,
7622                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7623                    user, false);
7624            if (pkgSetting == null) {
7625                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7626                        "Creating application package " + pkg.packageName + " failed");
7627            }
7628
7629            if (pkgSetting.origPackage != null) {
7630                // If we are first transitioning from an original package,
7631                // fix up the new package's name now.  We need to do this after
7632                // looking up the package under its new name, so getPackageLP
7633                // can take care of fiddling things correctly.
7634                pkg.setPackageName(origPackage.name);
7635
7636                // File a report about this.
7637                String msg = "New package " + pkgSetting.realName
7638                        + " renamed to replace old package " + pkgSetting.name;
7639                reportSettingsProblem(Log.WARN, msg);
7640
7641                // Make a note of it.
7642                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7643                    mTransferedPackages.add(origPackage.name);
7644                }
7645
7646                // No longer need to retain this.
7647                pkgSetting.origPackage = null;
7648            }
7649
7650            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7651                // Make a note of it.
7652                mTransferedPackages.add(pkg.packageName);
7653            }
7654
7655            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7656                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7657            }
7658
7659            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7660                // Check all shared libraries and map to their actual file path.
7661                // We only do this here for apps not on a system dir, because those
7662                // are the only ones that can fail an install due to this.  We
7663                // will take care of the system apps by updating all of their
7664                // library paths after the scan is done.
7665                updateSharedLibrariesLPw(pkg, null);
7666            }
7667
7668            if (mFoundPolicyFile) {
7669                SELinuxMMAC.assignSeinfoValue(pkg);
7670            }
7671
7672            pkg.applicationInfo.uid = pkgSetting.appId;
7673            pkg.mExtras = pkgSetting;
7674            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7675                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7676                    // We just determined the app is signed correctly, so bring
7677                    // over the latest parsed certs.
7678                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7679                } else {
7680                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7681                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7682                                "Package " + pkg.packageName + " upgrade keys do not match the "
7683                                + "previously installed version");
7684                    } else {
7685                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7686                        String msg = "System package " + pkg.packageName
7687                            + " signature changed; retaining data.";
7688                        reportSettingsProblem(Log.WARN, msg);
7689                    }
7690                }
7691            } else {
7692                try {
7693                    verifySignaturesLP(pkgSetting, pkg);
7694                    // We just determined the app is signed correctly, so bring
7695                    // over the latest parsed certs.
7696                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7697                } catch (PackageManagerException e) {
7698                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7699                        throw e;
7700                    }
7701                    // The signature has changed, but this package is in the system
7702                    // image...  let's recover!
7703                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7704                    // However...  if this package is part of a shared user, but it
7705                    // doesn't match the signature of the shared user, let's fail.
7706                    // What this means is that you can't change the signatures
7707                    // associated with an overall shared user, which doesn't seem all
7708                    // that unreasonable.
7709                    if (pkgSetting.sharedUser != null) {
7710                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7711                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7712                            throw new PackageManagerException(
7713                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7714                                            "Signature mismatch for shared user: "
7715                                            + pkgSetting.sharedUser);
7716                        }
7717                    }
7718                    // File a report about this.
7719                    String msg = "System package " + pkg.packageName
7720                        + " signature changed; retaining data.";
7721                    reportSettingsProblem(Log.WARN, msg);
7722                }
7723            }
7724            // Verify that this new package doesn't have any content providers
7725            // that conflict with existing packages.  Only do this if the
7726            // package isn't already installed, since we don't want to break
7727            // things that are installed.
7728            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7729                final int N = pkg.providers.size();
7730                int i;
7731                for (i=0; i<N; i++) {
7732                    PackageParser.Provider p = pkg.providers.get(i);
7733                    if (p.info.authority != null) {
7734                        String names[] = p.info.authority.split(";");
7735                        for (int j = 0; j < names.length; j++) {
7736                            if (mProvidersByAuthority.containsKey(names[j])) {
7737                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7738                                final String otherPackageName =
7739                                        ((other != null && other.getComponentName() != null) ?
7740                                                other.getComponentName().getPackageName() : "?");
7741                                throw new PackageManagerException(
7742                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7743                                                "Can't install because provider name " + names[j]
7744                                                + " (in package " + pkg.applicationInfo.packageName
7745                                                + ") is already used by " + otherPackageName);
7746                            }
7747                        }
7748                    }
7749                }
7750            }
7751
7752            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7753                // This package wants to adopt ownership of permissions from
7754                // another package.
7755                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7756                    final String origName = pkg.mAdoptPermissions.get(i);
7757                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7758                    if (orig != null) {
7759                        if (verifyPackageUpdateLPr(orig, pkg)) {
7760                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7761                                    + pkg.packageName);
7762                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7763                        }
7764                    }
7765                }
7766            }
7767        }
7768
7769        final String pkgName = pkg.packageName;
7770
7771        final long scanFileTime = scanFile.lastModified();
7772        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7773        pkg.applicationInfo.processName = fixProcessName(
7774                pkg.applicationInfo.packageName,
7775                pkg.applicationInfo.processName,
7776                pkg.applicationInfo.uid);
7777
7778        if (pkg != mPlatformPackage) {
7779            // Get all of our default paths setup
7780            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7781        }
7782
7783        final String path = scanFile.getPath();
7784        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7785
7786        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7787            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7788
7789            // Some system apps still use directory structure for native libraries
7790            // in which case we might end up not detecting abi solely based on apk
7791            // structure. Try to detect abi based on directory structure.
7792            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7793                    pkg.applicationInfo.primaryCpuAbi == null) {
7794                setBundledAppAbisAndRoots(pkg, pkgSetting);
7795                setNativeLibraryPaths(pkg);
7796            }
7797
7798        } else {
7799            if ((scanFlags & SCAN_MOVE) != 0) {
7800                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7801                // but we already have this packages package info in the PackageSetting. We just
7802                // use that and derive the native library path based on the new codepath.
7803                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7804                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7805            }
7806
7807            // Set native library paths again. For moves, the path will be updated based on the
7808            // ABIs we've determined above. For non-moves, the path will be updated based on the
7809            // ABIs we determined during compilation, but the path will depend on the final
7810            // package path (after the rename away from the stage path).
7811            setNativeLibraryPaths(pkg);
7812        }
7813
7814        // This is a special case for the "system" package, where the ABI is
7815        // dictated by the zygote configuration (and init.rc). We should keep track
7816        // of this ABI so that we can deal with "normal" applications that run under
7817        // the same UID correctly.
7818        if (mPlatformPackage == pkg) {
7819            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7820                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7821        }
7822
7823        // If there's a mismatch between the abi-override in the package setting
7824        // and the abiOverride specified for the install. Warn about this because we
7825        // would've already compiled the app without taking the package setting into
7826        // account.
7827        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7828            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7829                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7830                        " for package " + pkg.packageName);
7831            }
7832        }
7833
7834        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7835        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7836        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7837
7838        // Copy the derived override back to the parsed package, so that we can
7839        // update the package settings accordingly.
7840        pkg.cpuAbiOverride = cpuAbiOverride;
7841
7842        if (DEBUG_ABI_SELECTION) {
7843            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7844                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7845                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7846        }
7847
7848        // Push the derived path down into PackageSettings so we know what to
7849        // clean up at uninstall time.
7850        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7851
7852        if (DEBUG_ABI_SELECTION) {
7853            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7854                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7855                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7856        }
7857
7858        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7859            // We don't do this here during boot because we can do it all
7860            // at once after scanning all existing packages.
7861            //
7862            // We also do this *before* we perform dexopt on this package, so that
7863            // we can avoid redundant dexopts, and also to make sure we've got the
7864            // code and package path correct.
7865            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7866                    pkg, true /* boot complete */);
7867        }
7868
7869        if (mFactoryTest && pkg.requestedPermissions.contains(
7870                android.Manifest.permission.FACTORY_TEST)) {
7871            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7872        }
7873
7874        ArrayList<PackageParser.Package> clientLibPkgs = null;
7875
7876        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7877            if (nonMutatedPs != null) {
7878                synchronized (mPackages) {
7879                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7880                }
7881            }
7882            return pkg;
7883        }
7884
7885        // Only privileged apps and updated privileged apps can add child packages.
7886        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7887            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7888                throw new PackageManagerException("Only privileged apps and updated "
7889                        + "privileged apps can add child packages. Ignoring package "
7890                        + pkg.packageName);
7891            }
7892            final int childCount = pkg.childPackages.size();
7893            for (int i = 0; i < childCount; i++) {
7894                PackageParser.Package childPkg = pkg.childPackages.get(i);
7895                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7896                        childPkg.packageName)) {
7897                    throw new PackageManagerException("Cannot override a child package of "
7898                            + "another disabled system app. Ignoring package " + pkg.packageName);
7899                }
7900            }
7901        }
7902
7903        // writer
7904        synchronized (mPackages) {
7905            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7906                // Only system apps can add new shared libraries.
7907                if (pkg.libraryNames != null) {
7908                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7909                        String name = pkg.libraryNames.get(i);
7910                        boolean allowed = false;
7911                        if (pkg.isUpdatedSystemApp()) {
7912                            // New library entries can only be added through the
7913                            // system image.  This is important to get rid of a lot
7914                            // of nasty edge cases: for example if we allowed a non-
7915                            // system update of the app to add a library, then uninstalling
7916                            // the update would make the library go away, and assumptions
7917                            // we made such as through app install filtering would now
7918                            // have allowed apps on the device which aren't compatible
7919                            // with it.  Better to just have the restriction here, be
7920                            // conservative, and create many fewer cases that can negatively
7921                            // impact the user experience.
7922                            final PackageSetting sysPs = mSettings
7923                                    .getDisabledSystemPkgLPr(pkg.packageName);
7924                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7925                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7926                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7927                                        allowed = true;
7928                                        break;
7929                                    }
7930                                }
7931                            }
7932                        } else {
7933                            allowed = true;
7934                        }
7935                        if (allowed) {
7936                            if (!mSharedLibraries.containsKey(name)) {
7937                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7938                            } else if (!name.equals(pkg.packageName)) {
7939                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7940                                        + name + " already exists; skipping");
7941                            }
7942                        } else {
7943                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7944                                    + name + " that is not declared on system image; skipping");
7945                        }
7946                    }
7947                    if ((scanFlags & SCAN_BOOTING) == 0) {
7948                        // If we are not booting, we need to update any applications
7949                        // that are clients of our shared library.  If we are booting,
7950                        // this will all be done once the scan is complete.
7951                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7952                    }
7953                }
7954            }
7955        }
7956
7957        // Request the ActivityManager to kill the process(only for existing packages)
7958        // so that we do not end up in a confused state while the user is still using the older
7959        // version of the application while the new one gets installed.
7960        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
7961        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
7962        if (killApp) {
7963            if (isReplacing) {
7964                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7965
7966                killApplication(pkg.applicationInfo.packageName,
7967                            pkg.applicationInfo.uid, "replace pkg");
7968
7969                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7970            }
7971        }
7972
7973        // Also need to kill any apps that are dependent on the library.
7974        if (clientLibPkgs != null) {
7975            for (int i=0; i<clientLibPkgs.size(); i++) {
7976                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7977                killApplication(clientPkg.applicationInfo.packageName,
7978                        clientPkg.applicationInfo.uid, "update lib");
7979            }
7980        }
7981
7982        // Make sure we're not adding any bogus keyset info
7983        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7984        ksms.assertScannedPackageValid(pkg);
7985
7986        // writer
7987        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7988
7989        boolean createIdmapFailed = false;
7990        synchronized (mPackages) {
7991            // We don't expect installation to fail beyond this point
7992
7993            // Add the new setting to mSettings
7994            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7995            // Add the new setting to mPackages
7996            mPackages.put(pkg.applicationInfo.packageName, pkg);
7997            // Make sure we don't accidentally delete its data.
7998            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7999            while (iter.hasNext()) {
8000                PackageCleanItem item = iter.next();
8001                if (pkgName.equals(item.packageName)) {
8002                    iter.remove();
8003                }
8004            }
8005
8006            // Take care of first install / last update times.
8007            if (currentTime != 0) {
8008                if (pkgSetting.firstInstallTime == 0) {
8009                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8010                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8011                    pkgSetting.lastUpdateTime = currentTime;
8012                }
8013            } else if (pkgSetting.firstInstallTime == 0) {
8014                // We need *something*.  Take time time stamp of the file.
8015                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8016            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8017                if (scanFileTime != pkgSetting.timeStamp) {
8018                    // A package on the system image has changed; consider this
8019                    // to be an update.
8020                    pkgSetting.lastUpdateTime = scanFileTime;
8021                }
8022            }
8023
8024            // Add the package's KeySets to the global KeySetManagerService
8025            ksms.addScannedPackageLPw(pkg);
8026
8027            int N = pkg.providers.size();
8028            StringBuilder r = null;
8029            int i;
8030            for (i=0; i<N; i++) {
8031                PackageParser.Provider p = pkg.providers.get(i);
8032                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8033                        p.info.processName, pkg.applicationInfo.uid);
8034                mProviders.addProvider(p);
8035                p.syncable = p.info.isSyncable;
8036                if (p.info.authority != null) {
8037                    String names[] = p.info.authority.split(";");
8038                    p.info.authority = null;
8039                    for (int j = 0; j < names.length; j++) {
8040                        if (j == 1 && p.syncable) {
8041                            // We only want the first authority for a provider to possibly be
8042                            // syncable, so if we already added this provider using a different
8043                            // authority clear the syncable flag. We copy the provider before
8044                            // changing it because the mProviders object contains a reference
8045                            // to a provider that we don't want to change.
8046                            // Only do this for the second authority since the resulting provider
8047                            // object can be the same for all future authorities for this provider.
8048                            p = new PackageParser.Provider(p);
8049                            p.syncable = false;
8050                        }
8051                        if (!mProvidersByAuthority.containsKey(names[j])) {
8052                            mProvidersByAuthority.put(names[j], p);
8053                            if (p.info.authority == null) {
8054                                p.info.authority = names[j];
8055                            } else {
8056                                p.info.authority = p.info.authority + ";" + names[j];
8057                            }
8058                            if (DEBUG_PACKAGE_SCANNING) {
8059                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8060                                    Log.d(TAG, "Registered content provider: " + names[j]
8061                                            + ", className = " + p.info.name + ", isSyncable = "
8062                                            + p.info.isSyncable);
8063                            }
8064                        } else {
8065                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8066                            Slog.w(TAG, "Skipping provider name " + names[j] +
8067                                    " (in package " + pkg.applicationInfo.packageName +
8068                                    "): name already used by "
8069                                    + ((other != null && other.getComponentName() != null)
8070                                            ? other.getComponentName().getPackageName() : "?"));
8071                        }
8072                    }
8073                }
8074                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8075                    if (r == null) {
8076                        r = new StringBuilder(256);
8077                    } else {
8078                        r.append(' ');
8079                    }
8080                    r.append(p.info.name);
8081                }
8082            }
8083            if (r != null) {
8084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8085            }
8086
8087            N = pkg.services.size();
8088            r = null;
8089            for (i=0; i<N; i++) {
8090                PackageParser.Service s = pkg.services.get(i);
8091                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8092                        s.info.processName, pkg.applicationInfo.uid);
8093                mServices.addService(s);
8094                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8095                    if (r == null) {
8096                        r = new StringBuilder(256);
8097                    } else {
8098                        r.append(' ');
8099                    }
8100                    r.append(s.info.name);
8101                }
8102            }
8103            if (r != null) {
8104                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8105            }
8106
8107            N = pkg.receivers.size();
8108            r = null;
8109            for (i=0; i<N; i++) {
8110                PackageParser.Activity a = pkg.receivers.get(i);
8111                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8112                        a.info.processName, pkg.applicationInfo.uid);
8113                mReceivers.addActivity(a, "receiver");
8114                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8115                    if (r == null) {
8116                        r = new StringBuilder(256);
8117                    } else {
8118                        r.append(' ');
8119                    }
8120                    r.append(a.info.name);
8121                }
8122            }
8123            if (r != null) {
8124                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8125            }
8126
8127            N = pkg.activities.size();
8128            r = null;
8129            for (i=0; i<N; i++) {
8130                PackageParser.Activity a = pkg.activities.get(i);
8131                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8132                        a.info.processName, pkg.applicationInfo.uid);
8133                mActivities.addActivity(a, "activity");
8134                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8135                    if (r == null) {
8136                        r = new StringBuilder(256);
8137                    } else {
8138                        r.append(' ');
8139                    }
8140                    r.append(a.info.name);
8141                }
8142            }
8143            if (r != null) {
8144                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8145            }
8146
8147            N = pkg.permissionGroups.size();
8148            r = null;
8149            for (i=0; i<N; i++) {
8150                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8151                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8152                if (cur == null) {
8153                    mPermissionGroups.put(pg.info.name, pg);
8154                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8155                        if (r == null) {
8156                            r = new StringBuilder(256);
8157                        } else {
8158                            r.append(' ');
8159                        }
8160                        r.append(pg.info.name);
8161                    }
8162                } else {
8163                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8164                            + pg.info.packageName + " ignored: original from "
8165                            + cur.info.packageName);
8166                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8167                        if (r == null) {
8168                            r = new StringBuilder(256);
8169                        } else {
8170                            r.append(' ');
8171                        }
8172                        r.append("DUP:");
8173                        r.append(pg.info.name);
8174                    }
8175                }
8176            }
8177            if (r != null) {
8178                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8179            }
8180
8181            N = pkg.permissions.size();
8182            r = null;
8183            for (i=0; i<N; i++) {
8184                PackageParser.Permission p = pkg.permissions.get(i);
8185
8186                // Assume by default that we did not install this permission into the system.
8187                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8188
8189                // Now that permission groups have a special meaning, we ignore permission
8190                // groups for legacy apps to prevent unexpected behavior. In particular,
8191                // permissions for one app being granted to someone just becase they happen
8192                // to be in a group defined by another app (before this had no implications).
8193                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8194                    p.group = mPermissionGroups.get(p.info.group);
8195                    // Warn for a permission in an unknown group.
8196                    if (p.info.group != null && p.group == null) {
8197                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8198                                + p.info.packageName + " in an unknown group " + p.info.group);
8199                    }
8200                }
8201
8202                ArrayMap<String, BasePermission> permissionMap =
8203                        p.tree ? mSettings.mPermissionTrees
8204                                : mSettings.mPermissions;
8205                BasePermission bp = permissionMap.get(p.info.name);
8206
8207                // Allow system apps to redefine non-system permissions
8208                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8209                    final boolean currentOwnerIsSystem = (bp.perm != null
8210                            && isSystemApp(bp.perm.owner));
8211                    if (isSystemApp(p.owner)) {
8212                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8213                            // It's a built-in permission and no owner, take ownership now
8214                            bp.packageSetting = pkgSetting;
8215                            bp.perm = p;
8216                            bp.uid = pkg.applicationInfo.uid;
8217                            bp.sourcePackage = p.info.packageName;
8218                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8219                        } else if (!currentOwnerIsSystem) {
8220                            String msg = "New decl " + p.owner + " of permission  "
8221                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8222                            reportSettingsProblem(Log.WARN, msg);
8223                            bp = null;
8224                        }
8225                    }
8226                }
8227
8228                if (bp == null) {
8229                    bp = new BasePermission(p.info.name, p.info.packageName,
8230                            BasePermission.TYPE_NORMAL);
8231                    permissionMap.put(p.info.name, bp);
8232                }
8233
8234                if (bp.perm == null) {
8235                    if (bp.sourcePackage == null
8236                            || bp.sourcePackage.equals(p.info.packageName)) {
8237                        BasePermission tree = findPermissionTreeLP(p.info.name);
8238                        if (tree == null
8239                                || tree.sourcePackage.equals(p.info.packageName)) {
8240                            bp.packageSetting = pkgSetting;
8241                            bp.perm = p;
8242                            bp.uid = pkg.applicationInfo.uid;
8243                            bp.sourcePackage = p.info.packageName;
8244                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8245                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8246                                if (r == null) {
8247                                    r = new StringBuilder(256);
8248                                } else {
8249                                    r.append(' ');
8250                                }
8251                                r.append(p.info.name);
8252                            }
8253                        } else {
8254                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8255                                    + p.info.packageName + " ignored: base tree "
8256                                    + tree.name + " is from package "
8257                                    + tree.sourcePackage);
8258                        }
8259                    } else {
8260                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8261                                + p.info.packageName + " ignored: original from "
8262                                + bp.sourcePackage);
8263                    }
8264                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8265                    if (r == null) {
8266                        r = new StringBuilder(256);
8267                    } else {
8268                        r.append(' ');
8269                    }
8270                    r.append("DUP:");
8271                    r.append(p.info.name);
8272                }
8273                if (bp.perm == p) {
8274                    bp.protectionLevel = p.info.protectionLevel;
8275                }
8276            }
8277
8278            if (r != null) {
8279                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8280            }
8281
8282            N = pkg.instrumentation.size();
8283            r = null;
8284            for (i=0; i<N; i++) {
8285                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8286                a.info.packageName = pkg.applicationInfo.packageName;
8287                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8288                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8289                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8290                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8291                a.info.dataDir = pkg.applicationInfo.dataDir;
8292                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8293                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8294
8295                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8296                // need other information about the application, like the ABI and what not ?
8297                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8298                mInstrumentation.put(a.getComponentName(), a);
8299                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8300                    if (r == null) {
8301                        r = new StringBuilder(256);
8302                    } else {
8303                        r.append(' ');
8304                    }
8305                    r.append(a.info.name);
8306                }
8307            }
8308            if (r != null) {
8309                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8310            }
8311
8312            if (pkg.protectedBroadcasts != null) {
8313                N = pkg.protectedBroadcasts.size();
8314                for (i=0; i<N; i++) {
8315                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8316                }
8317            }
8318
8319            pkgSetting.setTimeStamp(scanFileTime);
8320
8321            // Create idmap files for pairs of (packages, overlay packages).
8322            // Note: "android", ie framework-res.apk, is handled by native layers.
8323            if (pkg.mOverlayTarget != null) {
8324                // This is an overlay package.
8325                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8326                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8327                        mOverlays.put(pkg.mOverlayTarget,
8328                                new ArrayMap<String, PackageParser.Package>());
8329                    }
8330                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8331                    map.put(pkg.packageName, pkg);
8332                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8333                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8334                        createIdmapFailed = true;
8335                    }
8336                }
8337            } else if (mOverlays.containsKey(pkg.packageName) &&
8338                    !pkg.packageName.equals("android")) {
8339                // This is a regular package, with one or more known overlay packages.
8340                createIdmapsForPackageLI(pkg);
8341            }
8342        }
8343
8344        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8345
8346        if (createIdmapFailed) {
8347            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8348                    "scanPackageLI failed to createIdmap");
8349        }
8350        return pkg;
8351    }
8352
8353    /**
8354     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8355     * is derived purely on the basis of the contents of {@code scanFile} and
8356     * {@code cpuAbiOverride}.
8357     *
8358     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8359     */
8360    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8361                                 String cpuAbiOverride, boolean extractLibs)
8362            throws PackageManagerException {
8363        // TODO: We can probably be smarter about this stuff. For installed apps,
8364        // we can calculate this information at install time once and for all. For
8365        // system apps, we can probably assume that this information doesn't change
8366        // after the first boot scan. As things stand, we do lots of unnecessary work.
8367
8368        // Give ourselves some initial paths; we'll come back for another
8369        // pass once we've determined ABI below.
8370        setNativeLibraryPaths(pkg);
8371
8372        // We would never need to extract libs for forward-locked and external packages,
8373        // since the container service will do it for us. We shouldn't attempt to
8374        // extract libs from system app when it was not updated.
8375        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8376                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8377            extractLibs = false;
8378        }
8379
8380        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8381        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8382
8383        NativeLibraryHelper.Handle handle = null;
8384        try {
8385            handle = NativeLibraryHelper.Handle.create(pkg);
8386            // TODO(multiArch): This can be null for apps that didn't go through the
8387            // usual installation process. We can calculate it again, like we
8388            // do during install time.
8389            //
8390            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8391            // unnecessary.
8392            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8393
8394            // Null out the abis so that they can be recalculated.
8395            pkg.applicationInfo.primaryCpuAbi = null;
8396            pkg.applicationInfo.secondaryCpuAbi = null;
8397            if (isMultiArch(pkg.applicationInfo)) {
8398                // Warn if we've set an abiOverride for multi-lib packages..
8399                // By definition, we need to copy both 32 and 64 bit libraries for
8400                // such packages.
8401                if (pkg.cpuAbiOverride != null
8402                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8403                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8404                }
8405
8406                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8407                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8408                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8409                    if (extractLibs) {
8410                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8411                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8412                                useIsaSpecificSubdirs);
8413                    } else {
8414                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8415                    }
8416                }
8417
8418                maybeThrowExceptionForMultiArchCopy(
8419                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8420
8421                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8422                    if (extractLibs) {
8423                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8424                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8425                                useIsaSpecificSubdirs);
8426                    } else {
8427                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8428                    }
8429                }
8430
8431                maybeThrowExceptionForMultiArchCopy(
8432                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8433
8434                if (abi64 >= 0) {
8435                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8436                }
8437
8438                if (abi32 >= 0) {
8439                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8440                    if (abi64 >= 0) {
8441                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8442                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8443                            pkg.applicationInfo.primaryCpuAbi = abi;
8444                        } else {
8445                            pkg.applicationInfo.secondaryCpuAbi = abi;
8446                        }
8447                    } else {
8448                        pkg.applicationInfo.primaryCpuAbi = abi;
8449                    }
8450                }
8451
8452            } else {
8453                String[] abiList = (cpuAbiOverride != null) ?
8454                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8455
8456                // Enable gross and lame hacks for apps that are built with old
8457                // SDK tools. We must scan their APKs for renderscript bitcode and
8458                // not launch them if it's present. Don't bother checking on devices
8459                // that don't have 64 bit support.
8460                boolean needsRenderScriptOverride = false;
8461                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8462                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8463                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8464                    needsRenderScriptOverride = true;
8465                }
8466
8467                final int copyRet;
8468                if (extractLibs) {
8469                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8470                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8471                } else {
8472                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8473                }
8474
8475                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8476                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8477                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8478                }
8479
8480                if (copyRet >= 0) {
8481                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8482                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8483                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8484                } else if (needsRenderScriptOverride) {
8485                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8486                }
8487            }
8488        } catch (IOException ioe) {
8489            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8490        } finally {
8491            IoUtils.closeQuietly(handle);
8492        }
8493
8494        // Now that we've calculated the ABIs and determined if it's an internal app,
8495        // we will go ahead and populate the nativeLibraryPath.
8496        setNativeLibraryPaths(pkg);
8497    }
8498
8499    /**
8500     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8501     * i.e, so that all packages can be run inside a single process if required.
8502     *
8503     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8504     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8505     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8506     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8507     * updating a package that belongs to a shared user.
8508     *
8509     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8510     * adds unnecessary complexity.
8511     */
8512    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8513            PackageParser.Package scannedPackage, boolean bootComplete) {
8514        String requiredInstructionSet = null;
8515        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8516            requiredInstructionSet = VMRuntime.getInstructionSet(
8517                     scannedPackage.applicationInfo.primaryCpuAbi);
8518        }
8519
8520        PackageSetting requirer = null;
8521        for (PackageSetting ps : packagesForUser) {
8522            // If packagesForUser contains scannedPackage, we skip it. This will happen
8523            // when scannedPackage is an update of an existing package. Without this check,
8524            // we will never be able to change the ABI of any package belonging to a shared
8525            // user, even if it's compatible with other packages.
8526            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8527                if (ps.primaryCpuAbiString == null) {
8528                    continue;
8529                }
8530
8531                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8532                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8533                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8534                    // this but there's not much we can do.
8535                    String errorMessage = "Instruction set mismatch, "
8536                            + ((requirer == null) ? "[caller]" : requirer)
8537                            + " requires " + requiredInstructionSet + " whereas " + ps
8538                            + " requires " + instructionSet;
8539                    Slog.w(TAG, errorMessage);
8540                }
8541
8542                if (requiredInstructionSet == null) {
8543                    requiredInstructionSet = instructionSet;
8544                    requirer = ps;
8545                }
8546            }
8547        }
8548
8549        if (requiredInstructionSet != null) {
8550            String adjustedAbi;
8551            if (requirer != null) {
8552                // requirer != null implies that either scannedPackage was null or that scannedPackage
8553                // did not require an ABI, in which case we have to adjust scannedPackage to match
8554                // the ABI of the set (which is the same as requirer's ABI)
8555                adjustedAbi = requirer.primaryCpuAbiString;
8556                if (scannedPackage != null) {
8557                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8558                }
8559            } else {
8560                // requirer == null implies that we're updating all ABIs in the set to
8561                // match scannedPackage.
8562                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8563            }
8564
8565            for (PackageSetting ps : packagesForUser) {
8566                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8567                    if (ps.primaryCpuAbiString != null) {
8568                        continue;
8569                    }
8570
8571                    ps.primaryCpuAbiString = adjustedAbi;
8572                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8573                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8574                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8575                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8576                                + " (requirer="
8577                                + (requirer == null ? "null" : requirer.pkg.packageName)
8578                                + ", scannedPackage="
8579                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8580                                + ")");
8581                        try {
8582                            mInstaller.rmdex(ps.codePathString,
8583                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8584                        } catch (InstallerException ignored) {
8585                        }
8586                    }
8587                }
8588            }
8589        }
8590    }
8591
8592    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8593        synchronized (mPackages) {
8594            mResolverReplaced = true;
8595            // Set up information for custom user intent resolution activity.
8596            mResolveActivity.applicationInfo = pkg.applicationInfo;
8597            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8598            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8599            mResolveActivity.processName = pkg.applicationInfo.packageName;
8600            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8601            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8602                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8603            mResolveActivity.theme = 0;
8604            mResolveActivity.exported = true;
8605            mResolveActivity.enabled = true;
8606            mResolveInfo.activityInfo = mResolveActivity;
8607            mResolveInfo.priority = 0;
8608            mResolveInfo.preferredOrder = 0;
8609            mResolveInfo.match = 0;
8610            mResolveComponentName = mCustomResolverComponentName;
8611            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8612                    mResolveComponentName);
8613        }
8614    }
8615
8616    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8617        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8618
8619        // Set up information for ephemeral installer activity
8620        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8621        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8622        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8623        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8624        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8625        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8626                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8627        mEphemeralInstallerActivity.theme = 0;
8628        mEphemeralInstallerActivity.exported = true;
8629        mEphemeralInstallerActivity.enabled = true;
8630        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8631        mEphemeralInstallerInfo.priority = 0;
8632        mEphemeralInstallerInfo.preferredOrder = 0;
8633        mEphemeralInstallerInfo.match = 0;
8634
8635        if (DEBUG_EPHEMERAL) {
8636            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8637        }
8638    }
8639
8640    private static String calculateBundledApkRoot(final String codePathString) {
8641        final File codePath = new File(codePathString);
8642        final File codeRoot;
8643        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8644            codeRoot = Environment.getRootDirectory();
8645        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8646            codeRoot = Environment.getOemDirectory();
8647        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8648            codeRoot = Environment.getVendorDirectory();
8649        } else {
8650            // Unrecognized code path; take its top real segment as the apk root:
8651            // e.g. /something/app/blah.apk => /something
8652            try {
8653                File f = codePath.getCanonicalFile();
8654                File parent = f.getParentFile();    // non-null because codePath is a file
8655                File tmp;
8656                while ((tmp = parent.getParentFile()) != null) {
8657                    f = parent;
8658                    parent = tmp;
8659                }
8660                codeRoot = f;
8661                Slog.w(TAG, "Unrecognized code path "
8662                        + codePath + " - using " + codeRoot);
8663            } catch (IOException e) {
8664                // Can't canonicalize the code path -- shenanigans?
8665                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8666                return Environment.getRootDirectory().getPath();
8667            }
8668        }
8669        return codeRoot.getPath();
8670    }
8671
8672    /**
8673     * Derive and set the location of native libraries for the given package,
8674     * which varies depending on where and how the package was installed.
8675     */
8676    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8677        final ApplicationInfo info = pkg.applicationInfo;
8678        final String codePath = pkg.codePath;
8679        final File codeFile = new File(codePath);
8680        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8681        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8682
8683        info.nativeLibraryRootDir = null;
8684        info.nativeLibraryRootRequiresIsa = false;
8685        info.nativeLibraryDir = null;
8686        info.secondaryNativeLibraryDir = null;
8687
8688        if (isApkFile(codeFile)) {
8689            // Monolithic install
8690            if (bundledApp) {
8691                // If "/system/lib64/apkname" exists, assume that is the per-package
8692                // native library directory to use; otherwise use "/system/lib/apkname".
8693                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8694                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8695                        getPrimaryInstructionSet(info));
8696
8697                // This is a bundled system app so choose the path based on the ABI.
8698                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8699                // is just the default path.
8700                final String apkName = deriveCodePathName(codePath);
8701                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8702                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8703                        apkName).getAbsolutePath();
8704
8705                if (info.secondaryCpuAbi != null) {
8706                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8707                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8708                            secondaryLibDir, apkName).getAbsolutePath();
8709                }
8710            } else if (asecApp) {
8711                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8712                        .getAbsolutePath();
8713            } else {
8714                final String apkName = deriveCodePathName(codePath);
8715                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8716                        .getAbsolutePath();
8717            }
8718
8719            info.nativeLibraryRootRequiresIsa = false;
8720            info.nativeLibraryDir = info.nativeLibraryRootDir;
8721        } else {
8722            // Cluster install
8723            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8724            info.nativeLibraryRootRequiresIsa = true;
8725
8726            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8727                    getPrimaryInstructionSet(info)).getAbsolutePath();
8728
8729            if (info.secondaryCpuAbi != null) {
8730                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8731                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8732            }
8733        }
8734    }
8735
8736    /**
8737     * Calculate the abis and roots for a bundled app. These can uniquely
8738     * be determined from the contents of the system partition, i.e whether
8739     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8740     * of this information, and instead assume that the system was built
8741     * sensibly.
8742     */
8743    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8744                                           PackageSetting pkgSetting) {
8745        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8746
8747        // If "/system/lib64/apkname" exists, assume that is the per-package
8748        // native library directory to use; otherwise use "/system/lib/apkname".
8749        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8750        setBundledAppAbi(pkg, apkRoot, apkName);
8751        // pkgSetting might be null during rescan following uninstall of updates
8752        // to a bundled app, so accommodate that possibility.  The settings in
8753        // that case will be established later from the parsed package.
8754        //
8755        // If the settings aren't null, sync them up with what we've just derived.
8756        // note that apkRoot isn't stored in the package settings.
8757        if (pkgSetting != null) {
8758            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8759            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8760        }
8761    }
8762
8763    /**
8764     * Deduces the ABI of a bundled app and sets the relevant fields on the
8765     * parsed pkg object.
8766     *
8767     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8768     *        under which system libraries are installed.
8769     * @param apkName the name of the installed package.
8770     */
8771    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8772        final File codeFile = new File(pkg.codePath);
8773
8774        final boolean has64BitLibs;
8775        final boolean has32BitLibs;
8776        if (isApkFile(codeFile)) {
8777            // Monolithic install
8778            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8779            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8780        } else {
8781            // Cluster install
8782            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8783            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8784                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8785                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8786                has64BitLibs = (new File(rootDir, isa)).exists();
8787            } else {
8788                has64BitLibs = false;
8789            }
8790            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8791                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8792                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8793                has32BitLibs = (new File(rootDir, isa)).exists();
8794            } else {
8795                has32BitLibs = false;
8796            }
8797        }
8798
8799        if (has64BitLibs && !has32BitLibs) {
8800            // The package has 64 bit libs, but not 32 bit libs. Its primary
8801            // ABI should be 64 bit. We can safely assume here that the bundled
8802            // native libraries correspond to the most preferred ABI in the list.
8803
8804            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8805            pkg.applicationInfo.secondaryCpuAbi = null;
8806        } else if (has32BitLibs && !has64BitLibs) {
8807            // The package has 32 bit libs but not 64 bit libs. Its primary
8808            // ABI should be 32 bit.
8809
8810            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8811            pkg.applicationInfo.secondaryCpuAbi = null;
8812        } else if (has32BitLibs && has64BitLibs) {
8813            // The application has both 64 and 32 bit bundled libraries. We check
8814            // here that the app declares multiArch support, and warn if it doesn't.
8815            //
8816            // We will be lenient here and record both ABIs. The primary will be the
8817            // ABI that's higher on the list, i.e, a device that's configured to prefer
8818            // 64 bit apps will see a 64 bit primary ABI,
8819
8820            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8821                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8822            }
8823
8824            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8825                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8826                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8827            } else {
8828                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8829                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8830            }
8831        } else {
8832            pkg.applicationInfo.primaryCpuAbi = null;
8833            pkg.applicationInfo.secondaryCpuAbi = null;
8834        }
8835    }
8836
8837    private void killPackage(PackageParser.Package pkg, String reason) {
8838        // Kill the parent package
8839        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8840        // Kill the child packages
8841        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8842        for (int i = 0; i < childCount; i++) {
8843            PackageParser.Package childPkg = pkg.childPackages.get(i);
8844            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8845        }
8846    }
8847
8848    private void killApplication(String pkgName, int appId, String reason) {
8849        // Request the ActivityManager to kill the process(only for existing packages)
8850        // so that we do not end up in a confused state while the user is still using the older
8851        // version of the application while the new one gets installed.
8852        IActivityManager am = ActivityManagerNative.getDefault();
8853        if (am != null) {
8854            try {
8855                am.killApplicationWithAppId(pkgName, appId, reason);
8856            } catch (RemoteException e) {
8857            }
8858        }
8859    }
8860
8861    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8862        // Remove the parent package setting
8863        PackageSetting ps = (PackageSetting) pkg.mExtras;
8864        if (ps != null) {
8865            removePackageLI(ps, chatty);
8866        }
8867        // Remove the child package setting
8868        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8869        for (int i = 0; i < childCount; i++) {
8870            PackageParser.Package childPkg = pkg.childPackages.get(i);
8871            ps = (PackageSetting) childPkg.mExtras;
8872            if (ps != null) {
8873                removePackageLI(ps, chatty);
8874            }
8875        }
8876    }
8877
8878    void removePackageLI(PackageSetting ps, boolean chatty) {
8879        if (DEBUG_INSTALL) {
8880            if (chatty)
8881                Log.d(TAG, "Removing package " + ps.name);
8882        }
8883
8884        // writer
8885        synchronized (mPackages) {
8886            mPackages.remove(ps.name);
8887            final PackageParser.Package pkg = ps.pkg;
8888            if (pkg != null) {
8889                cleanPackageDataStructuresLILPw(pkg, chatty);
8890            }
8891        }
8892    }
8893
8894    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8895        if (DEBUG_INSTALL) {
8896            if (chatty)
8897                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8898        }
8899
8900        // writer
8901        synchronized (mPackages) {
8902            // Remove the parent package
8903            mPackages.remove(pkg.applicationInfo.packageName);
8904            cleanPackageDataStructuresLILPw(pkg, chatty);
8905
8906            // Remove the child packages
8907            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8908            for (int i = 0; i < childCount; i++) {
8909                PackageParser.Package childPkg = pkg.childPackages.get(i);
8910                mPackages.remove(childPkg.applicationInfo.packageName);
8911                cleanPackageDataStructuresLILPw(childPkg, chatty);
8912            }
8913        }
8914    }
8915
8916    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8917        int N = pkg.providers.size();
8918        StringBuilder r = null;
8919        int i;
8920        for (i=0; i<N; i++) {
8921            PackageParser.Provider p = pkg.providers.get(i);
8922            mProviders.removeProvider(p);
8923            if (p.info.authority == null) {
8924
8925                /* There was another ContentProvider with this authority when
8926                 * this app was installed so this authority is null,
8927                 * Ignore it as we don't have to unregister the provider.
8928                 */
8929                continue;
8930            }
8931            String names[] = p.info.authority.split(";");
8932            for (int j = 0; j < names.length; j++) {
8933                if (mProvidersByAuthority.get(names[j]) == p) {
8934                    mProvidersByAuthority.remove(names[j]);
8935                    if (DEBUG_REMOVE) {
8936                        if (chatty)
8937                            Log.d(TAG, "Unregistered content provider: " + names[j]
8938                                    + ", className = " + p.info.name + ", isSyncable = "
8939                                    + p.info.isSyncable);
8940                    }
8941                }
8942            }
8943            if (DEBUG_REMOVE && chatty) {
8944                if (r == null) {
8945                    r = new StringBuilder(256);
8946                } else {
8947                    r.append(' ');
8948                }
8949                r.append(p.info.name);
8950            }
8951        }
8952        if (r != null) {
8953            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8954        }
8955
8956        N = pkg.services.size();
8957        r = null;
8958        for (i=0; i<N; i++) {
8959            PackageParser.Service s = pkg.services.get(i);
8960            mServices.removeService(s);
8961            if (chatty) {
8962                if (r == null) {
8963                    r = new StringBuilder(256);
8964                } else {
8965                    r.append(' ');
8966                }
8967                r.append(s.info.name);
8968            }
8969        }
8970        if (r != null) {
8971            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8972        }
8973
8974        N = pkg.receivers.size();
8975        r = null;
8976        for (i=0; i<N; i++) {
8977            PackageParser.Activity a = pkg.receivers.get(i);
8978            mReceivers.removeActivity(a, "receiver");
8979            if (DEBUG_REMOVE && chatty) {
8980                if (r == null) {
8981                    r = new StringBuilder(256);
8982                } else {
8983                    r.append(' ');
8984                }
8985                r.append(a.info.name);
8986            }
8987        }
8988        if (r != null) {
8989            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8990        }
8991
8992        N = pkg.activities.size();
8993        r = null;
8994        for (i=0; i<N; i++) {
8995            PackageParser.Activity a = pkg.activities.get(i);
8996            mActivities.removeActivity(a, "activity");
8997            if (DEBUG_REMOVE && chatty) {
8998                if (r == null) {
8999                    r = new StringBuilder(256);
9000                } else {
9001                    r.append(' ');
9002                }
9003                r.append(a.info.name);
9004            }
9005        }
9006        if (r != null) {
9007            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9008        }
9009
9010        N = pkg.permissions.size();
9011        r = null;
9012        for (i=0; i<N; i++) {
9013            PackageParser.Permission p = pkg.permissions.get(i);
9014            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9015            if (bp == null) {
9016                bp = mSettings.mPermissionTrees.get(p.info.name);
9017            }
9018            if (bp != null && bp.perm == p) {
9019                bp.perm = null;
9020                if (DEBUG_REMOVE && chatty) {
9021                    if (r == null) {
9022                        r = new StringBuilder(256);
9023                    } else {
9024                        r.append(' ');
9025                    }
9026                    r.append(p.info.name);
9027                }
9028            }
9029            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9030                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9031                if (appOpPkgs != null) {
9032                    appOpPkgs.remove(pkg.packageName);
9033                }
9034            }
9035        }
9036        if (r != null) {
9037            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9038        }
9039
9040        N = pkg.requestedPermissions.size();
9041        r = null;
9042        for (i=0; i<N; i++) {
9043            String perm = pkg.requestedPermissions.get(i);
9044            BasePermission bp = mSettings.mPermissions.get(perm);
9045            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9046                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9047                if (appOpPkgs != null) {
9048                    appOpPkgs.remove(pkg.packageName);
9049                    if (appOpPkgs.isEmpty()) {
9050                        mAppOpPermissionPackages.remove(perm);
9051                    }
9052                }
9053            }
9054        }
9055        if (r != null) {
9056            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9057        }
9058
9059        N = pkg.instrumentation.size();
9060        r = null;
9061        for (i=0; i<N; i++) {
9062            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9063            mInstrumentation.remove(a.getComponentName());
9064            if (DEBUG_REMOVE && chatty) {
9065                if (r == null) {
9066                    r = new StringBuilder(256);
9067                } else {
9068                    r.append(' ');
9069                }
9070                r.append(a.info.name);
9071            }
9072        }
9073        if (r != null) {
9074            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9075        }
9076
9077        r = null;
9078        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9079            // Only system apps can hold shared libraries.
9080            if (pkg.libraryNames != null) {
9081                for (i=0; i<pkg.libraryNames.size(); i++) {
9082                    String name = pkg.libraryNames.get(i);
9083                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9084                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9085                        mSharedLibraries.remove(name);
9086                        if (DEBUG_REMOVE && chatty) {
9087                            if (r == null) {
9088                                r = new StringBuilder(256);
9089                            } else {
9090                                r.append(' ');
9091                            }
9092                            r.append(name);
9093                        }
9094                    }
9095                }
9096            }
9097        }
9098        if (r != null) {
9099            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9100        }
9101    }
9102
9103    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9104        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9105            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9106                return true;
9107            }
9108        }
9109        return false;
9110    }
9111
9112    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9113    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9114    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9115
9116    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9117        // Update the parent permissions
9118        updatePermissionsLPw(pkg.packageName, pkg, flags);
9119        // Update the child permissions
9120        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9121        for (int i = 0; i < childCount; i++) {
9122            PackageParser.Package childPkg = pkg.childPackages.get(i);
9123            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9124        }
9125    }
9126
9127    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9128            int flags) {
9129        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9130        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9131    }
9132
9133    private void updatePermissionsLPw(String changingPkg,
9134            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9135        // Make sure there are no dangling permission trees.
9136        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9137        while (it.hasNext()) {
9138            final BasePermission bp = it.next();
9139            if (bp.packageSetting == null) {
9140                // We may not yet have parsed the package, so just see if
9141                // we still know about its settings.
9142                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9143            }
9144            if (bp.packageSetting == null) {
9145                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9146                        + " from package " + bp.sourcePackage);
9147                it.remove();
9148            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9149                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9150                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9151                            + " from package " + bp.sourcePackage);
9152                    flags |= UPDATE_PERMISSIONS_ALL;
9153                    it.remove();
9154                }
9155            }
9156        }
9157
9158        // Make sure all dynamic permissions have been assigned to a package,
9159        // and make sure there are no dangling permissions.
9160        it = mSettings.mPermissions.values().iterator();
9161        while (it.hasNext()) {
9162            final BasePermission bp = it.next();
9163            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9164                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9165                        + bp.name + " pkg=" + bp.sourcePackage
9166                        + " info=" + bp.pendingInfo);
9167                if (bp.packageSetting == null && bp.pendingInfo != null) {
9168                    final BasePermission tree = findPermissionTreeLP(bp.name);
9169                    if (tree != null && tree.perm != null) {
9170                        bp.packageSetting = tree.packageSetting;
9171                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9172                                new PermissionInfo(bp.pendingInfo));
9173                        bp.perm.info.packageName = tree.perm.info.packageName;
9174                        bp.perm.info.name = bp.name;
9175                        bp.uid = tree.uid;
9176                    }
9177                }
9178            }
9179            if (bp.packageSetting == null) {
9180                // We may not yet have parsed the package, so just see if
9181                // we still know about its settings.
9182                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9183            }
9184            if (bp.packageSetting == null) {
9185                Slog.w(TAG, "Removing dangling permission: " + bp.name
9186                        + " from package " + bp.sourcePackage);
9187                it.remove();
9188            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9189                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9190                    Slog.i(TAG, "Removing old permission: " + bp.name
9191                            + " from package " + bp.sourcePackage);
9192                    flags |= UPDATE_PERMISSIONS_ALL;
9193                    it.remove();
9194                }
9195            }
9196        }
9197
9198        // Now update the permissions for all packages, in particular
9199        // replace the granted permissions of the system packages.
9200        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9201            for (PackageParser.Package pkg : mPackages.values()) {
9202                if (pkg != pkgInfo) {
9203                    // Only replace for packages on requested volume
9204                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9205                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9206                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9207                    grantPermissionsLPw(pkg, replace, changingPkg);
9208                }
9209            }
9210        }
9211
9212        if (pkgInfo != null) {
9213            // Only replace for packages on requested volume
9214            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9215            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9216                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9217            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9218        }
9219    }
9220
9221    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9222            String packageOfInterest) {
9223        // IMPORTANT: There are two types of permissions: install and runtime.
9224        // Install time permissions are granted when the app is installed to
9225        // all device users and users added in the future. Runtime permissions
9226        // are granted at runtime explicitly to specific users. Normal and signature
9227        // protected permissions are install time permissions. Dangerous permissions
9228        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9229        // otherwise they are runtime permissions. This function does not manage
9230        // runtime permissions except for the case an app targeting Lollipop MR1
9231        // being upgraded to target a newer SDK, in which case dangerous permissions
9232        // are transformed from install time to runtime ones.
9233
9234        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9235        if (ps == null) {
9236            return;
9237        }
9238
9239        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9240
9241        PermissionsState permissionsState = ps.getPermissionsState();
9242        PermissionsState origPermissions = permissionsState;
9243
9244        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9245
9246        boolean runtimePermissionsRevoked = false;
9247        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9248
9249        boolean changedInstallPermission = false;
9250
9251        if (replace) {
9252            ps.installPermissionsFixed = false;
9253            if (!ps.isSharedUser()) {
9254                origPermissions = new PermissionsState(permissionsState);
9255                permissionsState.reset();
9256            } else {
9257                // We need to know only about runtime permission changes since the
9258                // calling code always writes the install permissions state but
9259                // the runtime ones are written only if changed. The only cases of
9260                // changed runtime permissions here are promotion of an install to
9261                // runtime and revocation of a runtime from a shared user.
9262                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9263                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9264                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9265                    runtimePermissionsRevoked = true;
9266                }
9267            }
9268        }
9269
9270        permissionsState.setGlobalGids(mGlobalGids);
9271
9272        final int N = pkg.requestedPermissions.size();
9273        for (int i=0; i<N; i++) {
9274            final String name = pkg.requestedPermissions.get(i);
9275            final BasePermission bp = mSettings.mPermissions.get(name);
9276
9277            if (DEBUG_INSTALL) {
9278                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9279            }
9280
9281            if (bp == null || bp.packageSetting == null) {
9282                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9283                    Slog.w(TAG, "Unknown permission " + name
9284                            + " in package " + pkg.packageName);
9285                }
9286                continue;
9287            }
9288
9289            final String perm = bp.name;
9290            boolean allowedSig = false;
9291            int grant = GRANT_DENIED;
9292
9293            // Keep track of app op permissions.
9294            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9295                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9296                if (pkgs == null) {
9297                    pkgs = new ArraySet<>();
9298                    mAppOpPermissionPackages.put(bp.name, pkgs);
9299                }
9300                pkgs.add(pkg.packageName);
9301            }
9302
9303            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9304            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9305                    >= Build.VERSION_CODES.M;
9306            switch (level) {
9307                case PermissionInfo.PROTECTION_NORMAL: {
9308                    // For all apps normal permissions are install time ones.
9309                    grant = GRANT_INSTALL;
9310                } break;
9311
9312                case PermissionInfo.PROTECTION_DANGEROUS: {
9313                    // If a permission review is required for legacy apps we represent
9314                    // their permissions as always granted runtime ones since we need
9315                    // to keep the review required permission flag per user while an
9316                    // install permission's state is shared across all users.
9317                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9318                        // For legacy apps dangerous permissions are install time ones.
9319                        grant = GRANT_INSTALL;
9320                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9321                        // For legacy apps that became modern, install becomes runtime.
9322                        grant = GRANT_UPGRADE;
9323                    } else if (mPromoteSystemApps
9324                            && isSystemApp(ps)
9325                            && mExistingSystemPackages.contains(ps.name)) {
9326                        // For legacy system apps, install becomes runtime.
9327                        // We cannot check hasInstallPermission() for system apps since those
9328                        // permissions were granted implicitly and not persisted pre-M.
9329                        grant = GRANT_UPGRADE;
9330                    } else {
9331                        // For modern apps keep runtime permissions unchanged.
9332                        grant = GRANT_RUNTIME;
9333                    }
9334                } break;
9335
9336                case PermissionInfo.PROTECTION_SIGNATURE: {
9337                    // For all apps signature permissions are install time ones.
9338                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9339                    if (allowedSig) {
9340                        grant = GRANT_INSTALL;
9341                    }
9342                } break;
9343            }
9344
9345            if (DEBUG_INSTALL) {
9346                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9347            }
9348
9349            if (grant != GRANT_DENIED) {
9350                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9351                    // If this is an existing, non-system package, then
9352                    // we can't add any new permissions to it.
9353                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9354                        // Except...  if this is a permission that was added
9355                        // to the platform (note: need to only do this when
9356                        // updating the platform).
9357                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9358                            grant = GRANT_DENIED;
9359                        }
9360                    }
9361                }
9362
9363                switch (grant) {
9364                    case GRANT_INSTALL: {
9365                        // Revoke this as runtime permission to handle the case of
9366                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9367                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9368                            if (origPermissions.getRuntimePermissionState(
9369                                    bp.name, userId) != null) {
9370                                // Revoke the runtime permission and clear the flags.
9371                                origPermissions.revokeRuntimePermission(bp, userId);
9372                                origPermissions.updatePermissionFlags(bp, userId,
9373                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9374                                // If we revoked a permission permission, we have to write.
9375                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9376                                        changedRuntimePermissionUserIds, userId);
9377                            }
9378                        }
9379                        // Grant an install permission.
9380                        if (permissionsState.grantInstallPermission(bp) !=
9381                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9382                            changedInstallPermission = true;
9383                        }
9384                    } break;
9385
9386                    case GRANT_RUNTIME: {
9387                        // Grant previously granted runtime permissions.
9388                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9389                            PermissionState permissionState = origPermissions
9390                                    .getRuntimePermissionState(bp.name, userId);
9391                            int flags = permissionState != null
9392                                    ? permissionState.getFlags() : 0;
9393                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9394                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9395                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9396                                    // If we cannot put the permission as it was, we have to write.
9397                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9398                                            changedRuntimePermissionUserIds, userId);
9399                                }
9400                                // If the app supports runtime permissions no need for a review.
9401                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9402                                        && appSupportsRuntimePermissions
9403                                        && (flags & PackageManager
9404                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9405                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9406                                    // Since we changed the flags, we have to write.
9407                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9408                                            changedRuntimePermissionUserIds, userId);
9409                                }
9410                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9411                                    && !appSupportsRuntimePermissions) {
9412                                // For legacy apps that need a permission review, every new
9413                                // runtime permission is granted but it is pending a review.
9414                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9415                                    permissionsState.grantRuntimePermission(bp, userId);
9416                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9417                                    // We changed the permission and flags, hence have to write.
9418                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9419                                            changedRuntimePermissionUserIds, userId);
9420                                }
9421                            }
9422                            // Propagate the permission flags.
9423                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9424                        }
9425                    } break;
9426
9427                    case GRANT_UPGRADE: {
9428                        // Grant runtime permissions for a previously held install permission.
9429                        PermissionState permissionState = origPermissions
9430                                .getInstallPermissionState(bp.name);
9431                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9432
9433                        if (origPermissions.revokeInstallPermission(bp)
9434                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9435                            // We will be transferring the permission flags, so clear them.
9436                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9437                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9438                            changedInstallPermission = true;
9439                        }
9440
9441                        // If the permission is not to be promoted to runtime we ignore it and
9442                        // also its other flags as they are not applicable to install permissions.
9443                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9444                            for (int userId : currentUserIds) {
9445                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9446                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9447                                    // Transfer the permission flags.
9448                                    permissionsState.updatePermissionFlags(bp, userId,
9449                                            flags, flags);
9450                                    // If we granted the permission, we have to write.
9451                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9452                                            changedRuntimePermissionUserIds, userId);
9453                                }
9454                            }
9455                        }
9456                    } break;
9457
9458                    default: {
9459                        if (packageOfInterest == null
9460                                || packageOfInterest.equals(pkg.packageName)) {
9461                            Slog.w(TAG, "Not granting permission " + perm
9462                                    + " to package " + pkg.packageName
9463                                    + " because it was previously installed without");
9464                        }
9465                    } break;
9466                }
9467            } else {
9468                if (permissionsState.revokeInstallPermission(bp) !=
9469                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9470                    // Also drop the permission flags.
9471                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9472                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9473                    changedInstallPermission = true;
9474                    Slog.i(TAG, "Un-granting permission " + perm
9475                            + " from package " + pkg.packageName
9476                            + " (protectionLevel=" + bp.protectionLevel
9477                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9478                            + ")");
9479                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9480                    // Don't print warning for app op permissions, since it is fine for them
9481                    // not to be granted, there is a UI for the user to decide.
9482                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9483                        Slog.w(TAG, "Not granting permission " + perm
9484                                + " to package " + pkg.packageName
9485                                + " (protectionLevel=" + bp.protectionLevel
9486                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9487                                + ")");
9488                    }
9489                }
9490            }
9491        }
9492
9493        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9494                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9495            // This is the first that we have heard about this package, so the
9496            // permissions we have now selected are fixed until explicitly
9497            // changed.
9498            ps.installPermissionsFixed = true;
9499        }
9500
9501        // Persist the runtime permissions state for users with changes. If permissions
9502        // were revoked because no app in the shared user declares them we have to
9503        // write synchronously to avoid losing runtime permissions state.
9504        for (int userId : changedRuntimePermissionUserIds) {
9505            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9506        }
9507
9508        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9509    }
9510
9511    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9512        boolean allowed = false;
9513        final int NP = PackageParser.NEW_PERMISSIONS.length;
9514        for (int ip=0; ip<NP; ip++) {
9515            final PackageParser.NewPermissionInfo npi
9516                    = PackageParser.NEW_PERMISSIONS[ip];
9517            if (npi.name.equals(perm)
9518                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9519                allowed = true;
9520                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9521                        + pkg.packageName);
9522                break;
9523            }
9524        }
9525        return allowed;
9526    }
9527
9528    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9529            BasePermission bp, PermissionsState origPermissions) {
9530        boolean allowed;
9531        allowed = (compareSignatures(
9532                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9533                        == PackageManager.SIGNATURE_MATCH)
9534                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9535                        == PackageManager.SIGNATURE_MATCH);
9536        if (!allowed && (bp.protectionLevel
9537                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9538            if (isSystemApp(pkg)) {
9539                // For updated system applications, a system permission
9540                // is granted only if it had been defined by the original application.
9541                if (pkg.isUpdatedSystemApp()) {
9542                    final PackageSetting sysPs = mSettings
9543                            .getDisabledSystemPkgLPr(pkg.packageName);
9544                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9545                        // If the original was granted this permission, we take
9546                        // that grant decision as read and propagate it to the
9547                        // update.
9548                        if (sysPs.isPrivileged()) {
9549                            allowed = true;
9550                        }
9551                    } else {
9552                        // The system apk may have been updated with an older
9553                        // version of the one on the data partition, but which
9554                        // granted a new system permission that it didn't have
9555                        // before.  In this case we do want to allow the app to
9556                        // now get the new permission if the ancestral apk is
9557                        // privileged to get it.
9558                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9559                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9560                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9561                                    allowed = true;
9562                                    break;
9563                                }
9564                            }
9565                        }
9566                        // Also if a privileged parent package on the system image or any of
9567                        // its children requested a privileged permission, the updated child
9568                        // packages can also get the permission.
9569                        if (pkg.parentPackage != null) {
9570                            final PackageSetting disabledSysParentPs = mSettings
9571                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9572                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9573                                    && disabledSysParentPs.isPrivileged()) {
9574                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9575                                    allowed = true;
9576                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9577                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9578                                    for (int i = 0; i < count; i++) {
9579                                        PackageParser.Package disabledSysChildPkg =
9580                                                disabledSysParentPs.pkg.childPackages.get(i);
9581                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9582                                                perm)) {
9583                                            allowed = true;
9584                                            break;
9585                                        }
9586                                    }
9587                                }
9588                            }
9589                        }
9590                    }
9591                } else {
9592                    allowed = isPrivilegedApp(pkg);
9593                }
9594            }
9595        }
9596        if (!allowed) {
9597            if (!allowed && (bp.protectionLevel
9598                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9599                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9600                // If this was a previously normal/dangerous permission that got moved
9601                // to a system permission as part of the runtime permission redesign, then
9602                // we still want to blindly grant it to old apps.
9603                allowed = true;
9604            }
9605            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9606                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9607                // If this permission is to be granted to the system installer and
9608                // this app is an installer, then it gets the permission.
9609                allowed = true;
9610            }
9611            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9612                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9613                // If this permission is to be granted to the system verifier and
9614                // this app is a verifier, then it gets the permission.
9615                allowed = true;
9616            }
9617            if (!allowed && (bp.protectionLevel
9618                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9619                    && isSystemApp(pkg)) {
9620                // Any pre-installed system app is allowed to get this permission.
9621                allowed = true;
9622            }
9623            if (!allowed && (bp.protectionLevel
9624                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9625                // For development permissions, a development permission
9626                // is granted only if it was already granted.
9627                allowed = origPermissions.hasInstallPermission(perm);
9628            }
9629        }
9630        return allowed;
9631    }
9632
9633    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9634        final int permCount = pkg.requestedPermissions.size();
9635        for (int j = 0; j < permCount; j++) {
9636            String requestedPermission = pkg.requestedPermissions.get(j);
9637            if (permission.equals(requestedPermission)) {
9638                return true;
9639            }
9640        }
9641        return false;
9642    }
9643
9644    final class ActivityIntentResolver
9645            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9646        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9647                boolean defaultOnly, int userId) {
9648            if (!sUserManager.exists(userId)) return null;
9649            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9650            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9651        }
9652
9653        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9654                int userId) {
9655            if (!sUserManager.exists(userId)) return null;
9656            mFlags = flags;
9657            return super.queryIntent(intent, resolvedType,
9658                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9659        }
9660
9661        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9662                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9663            if (!sUserManager.exists(userId)) return null;
9664            if (packageActivities == null) {
9665                return null;
9666            }
9667            mFlags = flags;
9668            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9669            final int N = packageActivities.size();
9670            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9671                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9672
9673            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9674            for (int i = 0; i < N; ++i) {
9675                intentFilters = packageActivities.get(i).intents;
9676                if (intentFilters != null && intentFilters.size() > 0) {
9677                    PackageParser.ActivityIntentInfo[] array =
9678                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9679                    intentFilters.toArray(array);
9680                    listCut.add(array);
9681                }
9682            }
9683            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9684        }
9685
9686        public final void addActivity(PackageParser.Activity a, String type) {
9687            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9688            mActivities.put(a.getComponentName(), a);
9689            if (DEBUG_SHOW_INFO)
9690                Log.v(
9691                TAG, "  " + type + " " +
9692                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9693            if (DEBUG_SHOW_INFO)
9694                Log.v(TAG, "    Class=" + a.info.name);
9695            final int NI = a.intents.size();
9696            for (int j=0; j<NI; j++) {
9697                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9698                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9699                    intent.setPriority(0);
9700                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9701                            + a.className + " with priority > 0, forcing to 0");
9702                }
9703                if (DEBUG_SHOW_INFO) {
9704                    Log.v(TAG, "    IntentFilter:");
9705                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9706                }
9707                if (!intent.debugCheck()) {
9708                    Log.w(TAG, "==> For Activity " + a.info.name);
9709                }
9710                addFilter(intent);
9711            }
9712        }
9713
9714        public final void removeActivity(PackageParser.Activity a, String type) {
9715            mActivities.remove(a.getComponentName());
9716            if (DEBUG_SHOW_INFO) {
9717                Log.v(TAG, "  " + type + " "
9718                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9719                                : a.info.name) + ":");
9720                Log.v(TAG, "    Class=" + a.info.name);
9721            }
9722            final int NI = a.intents.size();
9723            for (int j=0; j<NI; j++) {
9724                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9725                if (DEBUG_SHOW_INFO) {
9726                    Log.v(TAG, "    IntentFilter:");
9727                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9728                }
9729                removeFilter(intent);
9730            }
9731        }
9732
9733        @Override
9734        protected boolean allowFilterResult(
9735                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9736            ActivityInfo filterAi = filter.activity.info;
9737            for (int i=dest.size()-1; i>=0; i--) {
9738                ActivityInfo destAi = dest.get(i).activityInfo;
9739                if (destAi.name == filterAi.name
9740                        && destAi.packageName == filterAi.packageName) {
9741                    return false;
9742                }
9743            }
9744            return true;
9745        }
9746
9747        @Override
9748        protected ActivityIntentInfo[] newArray(int size) {
9749            return new ActivityIntentInfo[size];
9750        }
9751
9752        @Override
9753        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9754            if (!sUserManager.exists(userId)) return true;
9755            PackageParser.Package p = filter.activity.owner;
9756            if (p != null) {
9757                PackageSetting ps = (PackageSetting)p.mExtras;
9758                if (ps != null) {
9759                    // System apps are never considered stopped for purposes of
9760                    // filtering, because there may be no way for the user to
9761                    // actually re-launch them.
9762                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9763                            && ps.getStopped(userId);
9764                }
9765            }
9766            return false;
9767        }
9768
9769        @Override
9770        protected boolean isPackageForFilter(String packageName,
9771                PackageParser.ActivityIntentInfo info) {
9772            return packageName.equals(info.activity.owner.packageName);
9773        }
9774
9775        @Override
9776        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9777                int match, int userId) {
9778            if (!sUserManager.exists(userId)) return null;
9779            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9780                return null;
9781            }
9782            final PackageParser.Activity activity = info.activity;
9783            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9784            if (ps == null) {
9785                return null;
9786            }
9787            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9788                    ps.readUserState(userId), userId);
9789            if (ai == null) {
9790                return null;
9791            }
9792            final ResolveInfo res = new ResolveInfo();
9793            res.activityInfo = ai;
9794            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9795                res.filter = info;
9796            }
9797            if (info != null) {
9798                res.handleAllWebDataURI = info.handleAllWebDataURI();
9799            }
9800            res.priority = info.getPriority();
9801            res.preferredOrder = activity.owner.mPreferredOrder;
9802            //System.out.println("Result: " + res.activityInfo.className +
9803            //                   " = " + res.priority);
9804            res.match = match;
9805            res.isDefault = info.hasDefault;
9806            res.labelRes = info.labelRes;
9807            res.nonLocalizedLabel = info.nonLocalizedLabel;
9808            if (userNeedsBadging(userId)) {
9809                res.noResourceId = true;
9810            } else {
9811                res.icon = info.icon;
9812            }
9813            res.iconResourceId = info.icon;
9814            res.system = res.activityInfo.applicationInfo.isSystemApp();
9815            return res;
9816        }
9817
9818        @Override
9819        protected void sortResults(List<ResolveInfo> results) {
9820            Collections.sort(results, mResolvePrioritySorter);
9821        }
9822
9823        @Override
9824        protected void dumpFilter(PrintWriter out, String prefix,
9825                PackageParser.ActivityIntentInfo filter) {
9826            out.print(prefix); out.print(
9827                    Integer.toHexString(System.identityHashCode(filter.activity)));
9828                    out.print(' ');
9829                    filter.activity.printComponentShortName(out);
9830                    out.print(" filter ");
9831                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9832        }
9833
9834        @Override
9835        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9836            return filter.activity;
9837        }
9838
9839        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9840            PackageParser.Activity activity = (PackageParser.Activity)label;
9841            out.print(prefix); out.print(
9842                    Integer.toHexString(System.identityHashCode(activity)));
9843                    out.print(' ');
9844                    activity.printComponentShortName(out);
9845            if (count > 1) {
9846                out.print(" ("); out.print(count); out.print(" filters)");
9847            }
9848            out.println();
9849        }
9850
9851//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9852//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9853//            final List<ResolveInfo> retList = Lists.newArrayList();
9854//            while (i.hasNext()) {
9855//                final ResolveInfo resolveInfo = i.next();
9856//                if (isEnabledLP(resolveInfo.activityInfo)) {
9857//                    retList.add(resolveInfo);
9858//                }
9859//            }
9860//            return retList;
9861//        }
9862
9863        // Keys are String (activity class name), values are Activity.
9864        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9865                = new ArrayMap<ComponentName, PackageParser.Activity>();
9866        private int mFlags;
9867    }
9868
9869    private final class ServiceIntentResolver
9870            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9871        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9872                boolean defaultOnly, int userId) {
9873            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9874            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9875        }
9876
9877        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9878                int userId) {
9879            if (!sUserManager.exists(userId)) return null;
9880            mFlags = flags;
9881            return super.queryIntent(intent, resolvedType,
9882                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9883        }
9884
9885        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9886                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9887            if (!sUserManager.exists(userId)) return null;
9888            if (packageServices == null) {
9889                return null;
9890            }
9891            mFlags = flags;
9892            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9893            final int N = packageServices.size();
9894            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9895                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9896
9897            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9898            for (int i = 0; i < N; ++i) {
9899                intentFilters = packageServices.get(i).intents;
9900                if (intentFilters != null && intentFilters.size() > 0) {
9901                    PackageParser.ServiceIntentInfo[] array =
9902                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9903                    intentFilters.toArray(array);
9904                    listCut.add(array);
9905                }
9906            }
9907            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9908        }
9909
9910        public final void addService(PackageParser.Service s) {
9911            mServices.put(s.getComponentName(), s);
9912            if (DEBUG_SHOW_INFO) {
9913                Log.v(TAG, "  "
9914                        + (s.info.nonLocalizedLabel != null
9915                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9916                Log.v(TAG, "    Class=" + s.info.name);
9917            }
9918            final int NI = s.intents.size();
9919            int j;
9920            for (j=0; j<NI; j++) {
9921                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9922                if (DEBUG_SHOW_INFO) {
9923                    Log.v(TAG, "    IntentFilter:");
9924                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9925                }
9926                if (!intent.debugCheck()) {
9927                    Log.w(TAG, "==> For Service " + s.info.name);
9928                }
9929                addFilter(intent);
9930            }
9931        }
9932
9933        public final void removeService(PackageParser.Service s) {
9934            mServices.remove(s.getComponentName());
9935            if (DEBUG_SHOW_INFO) {
9936                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9937                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9938                Log.v(TAG, "    Class=" + s.info.name);
9939            }
9940            final int NI = s.intents.size();
9941            int j;
9942            for (j=0; j<NI; j++) {
9943                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9944                if (DEBUG_SHOW_INFO) {
9945                    Log.v(TAG, "    IntentFilter:");
9946                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9947                }
9948                removeFilter(intent);
9949            }
9950        }
9951
9952        @Override
9953        protected boolean allowFilterResult(
9954                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9955            ServiceInfo filterSi = filter.service.info;
9956            for (int i=dest.size()-1; i>=0; i--) {
9957                ServiceInfo destAi = dest.get(i).serviceInfo;
9958                if (destAi.name == filterSi.name
9959                        && destAi.packageName == filterSi.packageName) {
9960                    return false;
9961                }
9962            }
9963            return true;
9964        }
9965
9966        @Override
9967        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9968            return new PackageParser.ServiceIntentInfo[size];
9969        }
9970
9971        @Override
9972        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9973            if (!sUserManager.exists(userId)) return true;
9974            PackageParser.Package p = filter.service.owner;
9975            if (p != null) {
9976                PackageSetting ps = (PackageSetting)p.mExtras;
9977                if (ps != null) {
9978                    // System apps are never considered stopped for purposes of
9979                    // filtering, because there may be no way for the user to
9980                    // actually re-launch them.
9981                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9982                            && ps.getStopped(userId);
9983                }
9984            }
9985            return false;
9986        }
9987
9988        @Override
9989        protected boolean isPackageForFilter(String packageName,
9990                PackageParser.ServiceIntentInfo info) {
9991            return packageName.equals(info.service.owner.packageName);
9992        }
9993
9994        @Override
9995        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9996                int match, int userId) {
9997            if (!sUserManager.exists(userId)) return null;
9998            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9999            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10000                return null;
10001            }
10002            final PackageParser.Service service = info.service;
10003            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10004            if (ps == null) {
10005                return null;
10006            }
10007            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10008                    ps.readUserState(userId), userId);
10009            if (si == null) {
10010                return null;
10011            }
10012            final ResolveInfo res = new ResolveInfo();
10013            res.serviceInfo = si;
10014            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10015                res.filter = filter;
10016            }
10017            res.priority = info.getPriority();
10018            res.preferredOrder = service.owner.mPreferredOrder;
10019            res.match = match;
10020            res.isDefault = info.hasDefault;
10021            res.labelRes = info.labelRes;
10022            res.nonLocalizedLabel = info.nonLocalizedLabel;
10023            res.icon = info.icon;
10024            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10025            return res;
10026        }
10027
10028        @Override
10029        protected void sortResults(List<ResolveInfo> results) {
10030            Collections.sort(results, mResolvePrioritySorter);
10031        }
10032
10033        @Override
10034        protected void dumpFilter(PrintWriter out, String prefix,
10035                PackageParser.ServiceIntentInfo filter) {
10036            out.print(prefix); out.print(
10037                    Integer.toHexString(System.identityHashCode(filter.service)));
10038                    out.print(' ');
10039                    filter.service.printComponentShortName(out);
10040                    out.print(" filter ");
10041                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10042        }
10043
10044        @Override
10045        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10046            return filter.service;
10047        }
10048
10049        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10050            PackageParser.Service service = (PackageParser.Service)label;
10051            out.print(prefix); out.print(
10052                    Integer.toHexString(System.identityHashCode(service)));
10053                    out.print(' ');
10054                    service.printComponentShortName(out);
10055            if (count > 1) {
10056                out.print(" ("); out.print(count); out.print(" filters)");
10057            }
10058            out.println();
10059        }
10060
10061//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10062//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10063//            final List<ResolveInfo> retList = Lists.newArrayList();
10064//            while (i.hasNext()) {
10065//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10066//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10067//                    retList.add(resolveInfo);
10068//                }
10069//            }
10070//            return retList;
10071//        }
10072
10073        // Keys are String (activity class name), values are Activity.
10074        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10075                = new ArrayMap<ComponentName, PackageParser.Service>();
10076        private int mFlags;
10077    };
10078
10079    private final class ProviderIntentResolver
10080            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10081        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10082                boolean defaultOnly, int userId) {
10083            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10084            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10085        }
10086
10087        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10088                int userId) {
10089            if (!sUserManager.exists(userId))
10090                return null;
10091            mFlags = flags;
10092            return super.queryIntent(intent, resolvedType,
10093                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10094        }
10095
10096        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10097                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10098            if (!sUserManager.exists(userId))
10099                return null;
10100            if (packageProviders == null) {
10101                return null;
10102            }
10103            mFlags = flags;
10104            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10105            final int N = packageProviders.size();
10106            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10107                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10108
10109            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10110            for (int i = 0; i < N; ++i) {
10111                intentFilters = packageProviders.get(i).intents;
10112                if (intentFilters != null && intentFilters.size() > 0) {
10113                    PackageParser.ProviderIntentInfo[] array =
10114                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10115                    intentFilters.toArray(array);
10116                    listCut.add(array);
10117                }
10118            }
10119            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10120        }
10121
10122        public final void addProvider(PackageParser.Provider p) {
10123            if (mProviders.containsKey(p.getComponentName())) {
10124                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10125                return;
10126            }
10127
10128            mProviders.put(p.getComponentName(), p);
10129            if (DEBUG_SHOW_INFO) {
10130                Log.v(TAG, "  "
10131                        + (p.info.nonLocalizedLabel != null
10132                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10133                Log.v(TAG, "    Class=" + p.info.name);
10134            }
10135            final int NI = p.intents.size();
10136            int j;
10137            for (j = 0; j < NI; j++) {
10138                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10139                if (DEBUG_SHOW_INFO) {
10140                    Log.v(TAG, "    IntentFilter:");
10141                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10142                }
10143                if (!intent.debugCheck()) {
10144                    Log.w(TAG, "==> For Provider " + p.info.name);
10145                }
10146                addFilter(intent);
10147            }
10148        }
10149
10150        public final void removeProvider(PackageParser.Provider p) {
10151            mProviders.remove(p.getComponentName());
10152            if (DEBUG_SHOW_INFO) {
10153                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10154                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10155                Log.v(TAG, "    Class=" + p.info.name);
10156            }
10157            final int NI = p.intents.size();
10158            int j;
10159            for (j = 0; j < NI; j++) {
10160                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10161                if (DEBUG_SHOW_INFO) {
10162                    Log.v(TAG, "    IntentFilter:");
10163                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10164                }
10165                removeFilter(intent);
10166            }
10167        }
10168
10169        @Override
10170        protected boolean allowFilterResult(
10171                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10172            ProviderInfo filterPi = filter.provider.info;
10173            for (int i = dest.size() - 1; i >= 0; i--) {
10174                ProviderInfo destPi = dest.get(i).providerInfo;
10175                if (destPi.name == filterPi.name
10176                        && destPi.packageName == filterPi.packageName) {
10177                    return false;
10178                }
10179            }
10180            return true;
10181        }
10182
10183        @Override
10184        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10185            return new PackageParser.ProviderIntentInfo[size];
10186        }
10187
10188        @Override
10189        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10190            if (!sUserManager.exists(userId))
10191                return true;
10192            PackageParser.Package p = filter.provider.owner;
10193            if (p != null) {
10194                PackageSetting ps = (PackageSetting) p.mExtras;
10195                if (ps != null) {
10196                    // System apps are never considered stopped for purposes of
10197                    // filtering, because there may be no way for the user to
10198                    // actually re-launch them.
10199                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10200                            && ps.getStopped(userId);
10201                }
10202            }
10203            return false;
10204        }
10205
10206        @Override
10207        protected boolean isPackageForFilter(String packageName,
10208                PackageParser.ProviderIntentInfo info) {
10209            return packageName.equals(info.provider.owner.packageName);
10210        }
10211
10212        @Override
10213        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10214                int match, int userId) {
10215            if (!sUserManager.exists(userId))
10216                return null;
10217            final PackageParser.ProviderIntentInfo info = filter;
10218            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10219                return null;
10220            }
10221            final PackageParser.Provider provider = info.provider;
10222            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10223            if (ps == null) {
10224                return null;
10225            }
10226            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10227                    ps.readUserState(userId), userId);
10228            if (pi == null) {
10229                return null;
10230            }
10231            final ResolveInfo res = new ResolveInfo();
10232            res.providerInfo = pi;
10233            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10234                res.filter = filter;
10235            }
10236            res.priority = info.getPriority();
10237            res.preferredOrder = provider.owner.mPreferredOrder;
10238            res.match = match;
10239            res.isDefault = info.hasDefault;
10240            res.labelRes = info.labelRes;
10241            res.nonLocalizedLabel = info.nonLocalizedLabel;
10242            res.icon = info.icon;
10243            res.system = res.providerInfo.applicationInfo.isSystemApp();
10244            return res;
10245        }
10246
10247        @Override
10248        protected void sortResults(List<ResolveInfo> results) {
10249            Collections.sort(results, mResolvePrioritySorter);
10250        }
10251
10252        @Override
10253        protected void dumpFilter(PrintWriter out, String prefix,
10254                PackageParser.ProviderIntentInfo filter) {
10255            out.print(prefix);
10256            out.print(
10257                    Integer.toHexString(System.identityHashCode(filter.provider)));
10258            out.print(' ');
10259            filter.provider.printComponentShortName(out);
10260            out.print(" filter ");
10261            out.println(Integer.toHexString(System.identityHashCode(filter)));
10262        }
10263
10264        @Override
10265        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10266            return filter.provider;
10267        }
10268
10269        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10270            PackageParser.Provider provider = (PackageParser.Provider)label;
10271            out.print(prefix); out.print(
10272                    Integer.toHexString(System.identityHashCode(provider)));
10273                    out.print(' ');
10274                    provider.printComponentShortName(out);
10275            if (count > 1) {
10276                out.print(" ("); out.print(count); out.print(" filters)");
10277            }
10278            out.println();
10279        }
10280
10281        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10282                = new ArrayMap<ComponentName, PackageParser.Provider>();
10283        private int mFlags;
10284    }
10285
10286    private static final class EphemeralIntentResolver
10287            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10288        @Override
10289        protected EphemeralResolveIntentInfo[] newArray(int size) {
10290            return new EphemeralResolveIntentInfo[size];
10291        }
10292
10293        @Override
10294        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10295            return true;
10296        }
10297
10298        @Override
10299        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10300                int userId) {
10301            if (!sUserManager.exists(userId)) {
10302                return null;
10303            }
10304            return info.getEphemeralResolveInfo();
10305        }
10306    }
10307
10308    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10309            new Comparator<ResolveInfo>() {
10310        public int compare(ResolveInfo r1, ResolveInfo r2) {
10311            int v1 = r1.priority;
10312            int v2 = r2.priority;
10313            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10314            if (v1 != v2) {
10315                return (v1 > v2) ? -1 : 1;
10316            }
10317            v1 = r1.preferredOrder;
10318            v2 = r2.preferredOrder;
10319            if (v1 != v2) {
10320                return (v1 > v2) ? -1 : 1;
10321            }
10322            if (r1.isDefault != r2.isDefault) {
10323                return r1.isDefault ? -1 : 1;
10324            }
10325            v1 = r1.match;
10326            v2 = r2.match;
10327            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10328            if (v1 != v2) {
10329                return (v1 > v2) ? -1 : 1;
10330            }
10331            if (r1.system != r2.system) {
10332                return r1.system ? -1 : 1;
10333            }
10334            if (r1.activityInfo != null) {
10335                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10336            }
10337            if (r1.serviceInfo != null) {
10338                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10339            }
10340            if (r1.providerInfo != null) {
10341                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10342            }
10343            return 0;
10344        }
10345    };
10346
10347    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10348            new Comparator<ProviderInfo>() {
10349        public int compare(ProviderInfo p1, ProviderInfo p2) {
10350            final int v1 = p1.initOrder;
10351            final int v2 = p2.initOrder;
10352            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10353        }
10354    };
10355
10356    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10357            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10358            final int[] userIds) {
10359        mHandler.post(new Runnable() {
10360            @Override
10361            public void run() {
10362                try {
10363                    final IActivityManager am = ActivityManagerNative.getDefault();
10364                    if (am == null) return;
10365                    final int[] resolvedUserIds;
10366                    if (userIds == null) {
10367                        resolvedUserIds = am.getRunningUserIds();
10368                    } else {
10369                        resolvedUserIds = userIds;
10370                    }
10371                    for (int id : resolvedUserIds) {
10372                        final Intent intent = new Intent(action,
10373                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10374                        if (extras != null) {
10375                            intent.putExtras(extras);
10376                        }
10377                        if (targetPkg != null) {
10378                            intent.setPackage(targetPkg);
10379                        }
10380                        // Modify the UID when posting to other users
10381                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10382                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10383                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10384                            intent.putExtra(Intent.EXTRA_UID, uid);
10385                        }
10386                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10387                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10388                        if (DEBUG_BROADCASTS) {
10389                            RuntimeException here = new RuntimeException("here");
10390                            here.fillInStackTrace();
10391                            Slog.d(TAG, "Sending to user " + id + ": "
10392                                    + intent.toShortString(false, true, false, false)
10393                                    + " " + intent.getExtras(), here);
10394                        }
10395                        am.broadcastIntent(null, intent, null, finishedReceiver,
10396                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10397                                null, finishedReceiver != null, false, id);
10398                    }
10399                } catch (RemoteException ex) {
10400                }
10401            }
10402        });
10403    }
10404
10405    /**
10406     * Check if the external storage media is available. This is true if there
10407     * is a mounted external storage medium or if the external storage is
10408     * emulated.
10409     */
10410    private boolean isExternalMediaAvailable() {
10411        return mMediaMounted || Environment.isExternalStorageEmulated();
10412    }
10413
10414    @Override
10415    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10416        // writer
10417        synchronized (mPackages) {
10418            if (!isExternalMediaAvailable()) {
10419                // If the external storage is no longer mounted at this point,
10420                // the caller may not have been able to delete all of this
10421                // packages files and can not delete any more.  Bail.
10422                return null;
10423            }
10424            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10425            if (lastPackage != null) {
10426                pkgs.remove(lastPackage);
10427            }
10428            if (pkgs.size() > 0) {
10429                return pkgs.get(0);
10430            }
10431        }
10432        return null;
10433    }
10434
10435    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10436        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10437                userId, andCode ? 1 : 0, packageName);
10438        if (mSystemReady) {
10439            msg.sendToTarget();
10440        } else {
10441            if (mPostSystemReadyMessages == null) {
10442                mPostSystemReadyMessages = new ArrayList<>();
10443            }
10444            mPostSystemReadyMessages.add(msg);
10445        }
10446    }
10447
10448    void startCleaningPackages() {
10449        // reader
10450        synchronized (mPackages) {
10451            if (!isExternalMediaAvailable()) {
10452                return;
10453            }
10454            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10455                return;
10456            }
10457        }
10458        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10459        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10460        IActivityManager am = ActivityManagerNative.getDefault();
10461        if (am != null) {
10462            try {
10463                am.startService(null, intent, null, mContext.getOpPackageName(),
10464                        UserHandle.USER_SYSTEM);
10465            } catch (RemoteException e) {
10466            }
10467        }
10468    }
10469
10470    @Override
10471    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10472            int installFlags, String installerPackageName, int userId) {
10473        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10474
10475        final int callingUid = Binder.getCallingUid();
10476        enforceCrossUserPermission(callingUid, userId,
10477                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10478
10479        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10480            try {
10481                if (observer != null) {
10482                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10483                }
10484            } catch (RemoteException re) {
10485            }
10486            return;
10487        }
10488
10489        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10490            installFlags |= PackageManager.INSTALL_FROM_ADB;
10491
10492        } else {
10493            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10494            // about installerPackageName.
10495
10496            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10497            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10498        }
10499
10500        UserHandle user;
10501        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10502            user = UserHandle.ALL;
10503        } else {
10504            user = new UserHandle(userId);
10505        }
10506
10507        // Only system components can circumvent runtime permissions when installing.
10508        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10509                && mContext.checkCallingOrSelfPermission(Manifest.permission
10510                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10511            throw new SecurityException("You need the "
10512                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10513                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10514        }
10515
10516        final File originFile = new File(originPath);
10517        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10518
10519        final Message msg = mHandler.obtainMessage(INIT_COPY);
10520        final VerificationInfo verificationInfo = new VerificationInfo(
10521                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10522        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10523                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10524                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10525        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10526        msg.obj = params;
10527
10528        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10529                System.identityHashCode(msg.obj));
10530        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10531                System.identityHashCode(msg.obj));
10532
10533        mHandler.sendMessage(msg);
10534    }
10535
10536    void installStage(String packageName, File stagedDir, String stagedCid,
10537            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10538            String installerPackageName, int installerUid, UserHandle user) {
10539        if (DEBUG_EPHEMERAL) {
10540            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10541                Slog.d(TAG, "Ephemeral install of " + packageName);
10542            }
10543        }
10544        final VerificationInfo verificationInfo = new VerificationInfo(
10545                sessionParams.originatingUri, sessionParams.referrerUri,
10546                sessionParams.originatingUid, installerUid);
10547
10548        final OriginInfo origin;
10549        if (stagedDir != null) {
10550            origin = OriginInfo.fromStagedFile(stagedDir);
10551        } else {
10552            origin = OriginInfo.fromStagedContainer(stagedCid);
10553        }
10554
10555        final Message msg = mHandler.obtainMessage(INIT_COPY);
10556        final InstallParams params = new InstallParams(origin, null, observer,
10557                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10558                verificationInfo, user, sessionParams.abiOverride,
10559                sessionParams.grantedRuntimePermissions);
10560        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10561        msg.obj = params;
10562
10563        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10564                System.identityHashCode(msg.obj));
10565        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10566                System.identityHashCode(msg.obj));
10567
10568        mHandler.sendMessage(msg);
10569    }
10570
10571    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10572            int userId) {
10573        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10574        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10575    }
10576
10577    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10578            int appId, int userId) {
10579        Bundle extras = new Bundle(1);
10580        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10581
10582        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10583                packageName, extras, 0, null, null, new int[] {userId});
10584        try {
10585            IActivityManager am = ActivityManagerNative.getDefault();
10586            if (isSystem && am.isUserRunning(userId, 0)) {
10587                // The just-installed/enabled app is bundled on the system, so presumed
10588                // to be able to run automatically without needing an explicit launch.
10589                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10590                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10591                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10592                        .setPackage(packageName);
10593                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10594                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10595            }
10596        } catch (RemoteException e) {
10597            // shouldn't happen
10598            Slog.w(TAG, "Unable to bootstrap installed package", e);
10599        }
10600    }
10601
10602    @Override
10603    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10604            int userId) {
10605        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10606        PackageSetting pkgSetting;
10607        final int uid = Binder.getCallingUid();
10608        enforceCrossUserPermission(uid, userId,
10609                true /* requireFullPermission */, true /* checkShell */,
10610                "setApplicationHiddenSetting for user " + userId);
10611
10612        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10613            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10614            return false;
10615        }
10616
10617        long callingId = Binder.clearCallingIdentity();
10618        try {
10619            boolean sendAdded = false;
10620            boolean sendRemoved = false;
10621            // writer
10622            synchronized (mPackages) {
10623                pkgSetting = mSettings.mPackages.get(packageName);
10624                if (pkgSetting == null) {
10625                    return false;
10626                }
10627                if (pkgSetting.getHidden(userId) != hidden) {
10628                    pkgSetting.setHidden(hidden, userId);
10629                    mSettings.writePackageRestrictionsLPr(userId);
10630                    if (hidden) {
10631                        sendRemoved = true;
10632                    } else {
10633                        sendAdded = true;
10634                    }
10635                }
10636            }
10637            if (sendAdded) {
10638                sendPackageAddedForUser(packageName, pkgSetting, userId);
10639                return true;
10640            }
10641            if (sendRemoved) {
10642                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10643                        "hiding pkg");
10644                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10645                return true;
10646            }
10647        } finally {
10648            Binder.restoreCallingIdentity(callingId);
10649        }
10650        return false;
10651    }
10652
10653    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10654            int userId) {
10655        final PackageRemovedInfo info = new PackageRemovedInfo();
10656        info.removedPackage = packageName;
10657        info.removedUsers = new int[] {userId};
10658        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10659        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10660    }
10661
10662    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10663        if (pkgList.length > 0) {
10664            Bundle extras = new Bundle(1);
10665            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10666
10667            sendPackageBroadcast(
10668                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10669                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10670                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10671                    new int[] {userId});
10672        }
10673    }
10674
10675    /**
10676     * Returns true if application is not found or there was an error. Otherwise it returns
10677     * the hidden state of the package for the given user.
10678     */
10679    @Override
10680    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10682        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10683                true /* requireFullPermission */, false /* checkShell */,
10684                "getApplicationHidden for user " + userId);
10685        PackageSetting pkgSetting;
10686        long callingId = Binder.clearCallingIdentity();
10687        try {
10688            // writer
10689            synchronized (mPackages) {
10690                pkgSetting = mSettings.mPackages.get(packageName);
10691                if (pkgSetting == null) {
10692                    return true;
10693                }
10694                return pkgSetting.getHidden(userId);
10695            }
10696        } finally {
10697            Binder.restoreCallingIdentity(callingId);
10698        }
10699    }
10700
10701    /**
10702     * @hide
10703     */
10704    @Override
10705    public int installExistingPackageAsUser(String packageName, int userId) {
10706        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10707                null);
10708        PackageSetting pkgSetting;
10709        final int uid = Binder.getCallingUid();
10710        enforceCrossUserPermission(uid, userId,
10711                true /* requireFullPermission */, true /* checkShell */,
10712                "installExistingPackage for user " + userId);
10713        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10714            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10715        }
10716
10717        long callingId = Binder.clearCallingIdentity();
10718        try {
10719            boolean installed = false;
10720
10721            // writer
10722            synchronized (mPackages) {
10723                pkgSetting = mSettings.mPackages.get(packageName);
10724                if (pkgSetting == null) {
10725                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10726                }
10727                if (!pkgSetting.getInstalled(userId)) {
10728                    pkgSetting.setInstalled(true, userId);
10729                    pkgSetting.setHidden(false, userId);
10730                    mSettings.writePackageRestrictionsLPr(userId);
10731                    installed = true;
10732                }
10733            }
10734
10735            if (installed) {
10736                if (pkgSetting.pkg != null) {
10737                    prepareAppDataAfterInstall(pkgSetting.pkg);
10738                }
10739                sendPackageAddedForUser(packageName, pkgSetting, userId);
10740            }
10741        } finally {
10742            Binder.restoreCallingIdentity(callingId);
10743        }
10744
10745        return PackageManager.INSTALL_SUCCEEDED;
10746    }
10747
10748    boolean isUserRestricted(int userId, String restrictionKey) {
10749        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10750        if (restrictions.getBoolean(restrictionKey, false)) {
10751            Log.w(TAG, "User is restricted: " + restrictionKey);
10752            return true;
10753        }
10754        return false;
10755    }
10756
10757    @Override
10758    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10759            int userId) {
10760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10761        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10762                true /* requireFullPermission */, true /* checkShell */,
10763                "setPackagesSuspended for user " + userId);
10764
10765        if (ArrayUtils.isEmpty(packageNames)) {
10766            return packageNames;
10767        }
10768
10769        // List of package names for whom the suspended state has changed.
10770        List<String> changedPackages = new ArrayList<>(packageNames.length);
10771        // List of package names for whom the suspended state is not set as requested in this
10772        // method.
10773        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10774        for (int i = 0; i < packageNames.length; i++) {
10775            String packageName = packageNames[i];
10776            long callingId = Binder.clearCallingIdentity();
10777            try {
10778                boolean changed = false;
10779                final int appId;
10780                synchronized (mPackages) {
10781                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10782                    if (pkgSetting == null) {
10783                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10784                                + "\". Skipping suspending/un-suspending.");
10785                        unactionedPackages.add(packageName);
10786                        continue;
10787                    }
10788                    appId = pkgSetting.appId;
10789                    if (pkgSetting.getSuspended(userId) != suspended) {
10790                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10791                            unactionedPackages.add(packageName);
10792                            continue;
10793                        }
10794                        pkgSetting.setSuspended(suspended, userId);
10795                        mSettings.writePackageRestrictionsLPr(userId);
10796                        changed = true;
10797                        changedPackages.add(packageName);
10798                    }
10799                }
10800
10801                if (changed && suspended) {
10802                    killApplication(packageName, UserHandle.getUid(userId, appId),
10803                            "suspending package");
10804                }
10805            } finally {
10806                Binder.restoreCallingIdentity(callingId);
10807            }
10808        }
10809
10810        if (!changedPackages.isEmpty()) {
10811            sendPackagesSuspendedForUser(changedPackages.toArray(
10812                    new String[changedPackages.size()]), userId, suspended);
10813        }
10814
10815        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10816    }
10817
10818    @Override
10819    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10820        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10821                true /* requireFullPermission */, false /* checkShell */,
10822                "isPackageSuspendedForUser for user " + userId);
10823        synchronized (mPackages) {
10824            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10825            return pkgSetting != null && pkgSetting.getSuspended(userId);
10826        }
10827    }
10828
10829    /**
10830     * TODO: cache and disallow blocking the active dialer.
10831     *
10832     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
10833     */
10834    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10835        if (isPackageDeviceAdmin(packageName, userId)) {
10836            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10837                    + "\": has an active device admin");
10838            return false;
10839        }
10840
10841        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10842        if (packageName.equals(activeLauncherPackageName)) {
10843            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10844                    + "\": contains the active launcher");
10845            return false;
10846        }
10847
10848        if (packageName.equals(mRequiredInstallerPackage)) {
10849            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10850                    + "\": required for package installation");
10851            return false;
10852        }
10853
10854        if (packageName.equals(mRequiredVerifierPackage)) {
10855            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10856                    + "\": required for package verification");
10857            return false;
10858        }
10859
10860        final PackageParser.Package pkg = mPackages.get(packageName);
10861        if (pkg != null && isPrivilegedApp(pkg)) {
10862            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10863                    + "\": is a privileged app");
10864            return false;
10865        }
10866
10867        return true;
10868    }
10869
10870    private String getActiveLauncherPackageName(int userId) {
10871        Intent intent = new Intent(Intent.ACTION_MAIN);
10872        intent.addCategory(Intent.CATEGORY_HOME);
10873        ResolveInfo resolveInfo = resolveIntent(
10874                intent,
10875                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10876                PackageManager.MATCH_DEFAULT_ONLY,
10877                userId);
10878
10879        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10880    }
10881
10882    @Override
10883    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10884        mContext.enforceCallingOrSelfPermission(
10885                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10886                "Only package verification agents can verify applications");
10887
10888        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10889        final PackageVerificationResponse response = new PackageVerificationResponse(
10890                verificationCode, Binder.getCallingUid());
10891        msg.arg1 = id;
10892        msg.obj = response;
10893        mHandler.sendMessage(msg);
10894    }
10895
10896    @Override
10897    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10898            long millisecondsToDelay) {
10899        mContext.enforceCallingOrSelfPermission(
10900                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10901                "Only package verification agents can extend verification timeouts");
10902
10903        final PackageVerificationState state = mPendingVerification.get(id);
10904        final PackageVerificationResponse response = new PackageVerificationResponse(
10905                verificationCodeAtTimeout, Binder.getCallingUid());
10906
10907        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10908            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10909        }
10910        if (millisecondsToDelay < 0) {
10911            millisecondsToDelay = 0;
10912        }
10913        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10914                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10915            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10916        }
10917
10918        if ((state != null) && !state.timeoutExtended()) {
10919            state.extendTimeout();
10920
10921            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10922            msg.arg1 = id;
10923            msg.obj = response;
10924            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10925        }
10926    }
10927
10928    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10929            int verificationCode, UserHandle user) {
10930        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10931        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10932        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10933        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10934        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10935
10936        mContext.sendBroadcastAsUser(intent, user,
10937                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10938    }
10939
10940    private ComponentName matchComponentForVerifier(String packageName,
10941            List<ResolveInfo> receivers) {
10942        ActivityInfo targetReceiver = null;
10943
10944        final int NR = receivers.size();
10945        for (int i = 0; i < NR; i++) {
10946            final ResolveInfo info = receivers.get(i);
10947            if (info.activityInfo == null) {
10948                continue;
10949            }
10950
10951            if (packageName.equals(info.activityInfo.packageName)) {
10952                targetReceiver = info.activityInfo;
10953                break;
10954            }
10955        }
10956
10957        if (targetReceiver == null) {
10958            return null;
10959        }
10960
10961        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10962    }
10963
10964    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10965            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10966        if (pkgInfo.verifiers.length == 0) {
10967            return null;
10968        }
10969
10970        final int N = pkgInfo.verifiers.length;
10971        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10972        for (int i = 0; i < N; i++) {
10973            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10974
10975            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10976                    receivers);
10977            if (comp == null) {
10978                continue;
10979            }
10980
10981            final int verifierUid = getUidForVerifier(verifierInfo);
10982            if (verifierUid == -1) {
10983                continue;
10984            }
10985
10986            if (DEBUG_VERIFY) {
10987                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10988                        + " with the correct signature");
10989            }
10990            sufficientVerifiers.add(comp);
10991            verificationState.addSufficientVerifier(verifierUid);
10992        }
10993
10994        return sufficientVerifiers;
10995    }
10996
10997    private int getUidForVerifier(VerifierInfo verifierInfo) {
10998        synchronized (mPackages) {
10999            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11000            if (pkg == null) {
11001                return -1;
11002            } else if (pkg.mSignatures.length != 1) {
11003                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11004                        + " has more than one signature; ignoring");
11005                return -1;
11006            }
11007
11008            /*
11009             * If the public key of the package's signature does not match
11010             * our expected public key, then this is a different package and
11011             * we should skip.
11012             */
11013
11014            final byte[] expectedPublicKey;
11015            try {
11016                final Signature verifierSig = pkg.mSignatures[0];
11017                final PublicKey publicKey = verifierSig.getPublicKey();
11018                expectedPublicKey = publicKey.getEncoded();
11019            } catch (CertificateException e) {
11020                return -1;
11021            }
11022
11023            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11024
11025            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11026                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11027                        + " does not have the expected public key; ignoring");
11028                return -1;
11029            }
11030
11031            return pkg.applicationInfo.uid;
11032        }
11033    }
11034
11035    @Override
11036    public void finishPackageInstall(int token) {
11037        enforceSystemOrRoot("Only the system is allowed to finish installs");
11038
11039        if (DEBUG_INSTALL) {
11040            Slog.v(TAG, "BM finishing package install for " + token);
11041        }
11042        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11043
11044        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11045        mHandler.sendMessage(msg);
11046    }
11047
11048    /**
11049     * Get the verification agent timeout.
11050     *
11051     * @return verification timeout in milliseconds
11052     */
11053    private long getVerificationTimeout() {
11054        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11055                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11056                DEFAULT_VERIFICATION_TIMEOUT);
11057    }
11058
11059    /**
11060     * Get the default verification agent response code.
11061     *
11062     * @return default verification response code
11063     */
11064    private int getDefaultVerificationResponse() {
11065        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11066                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11067                DEFAULT_VERIFICATION_RESPONSE);
11068    }
11069
11070    /**
11071     * Check whether or not package verification has been enabled.
11072     *
11073     * @return true if verification should be performed
11074     */
11075    private boolean isVerificationEnabled(int userId, int installFlags) {
11076        if (!DEFAULT_VERIFY_ENABLE) {
11077            return false;
11078        }
11079        // Ephemeral apps don't get the full verification treatment
11080        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11081            if (DEBUG_EPHEMERAL) {
11082                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11083            }
11084            return false;
11085        }
11086
11087        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11088
11089        // Check if installing from ADB
11090        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11091            // Do not run verification in a test harness environment
11092            if (ActivityManager.isRunningInTestHarness()) {
11093                return false;
11094            }
11095            if (ensureVerifyAppsEnabled) {
11096                return true;
11097            }
11098            // Check if the developer does not want package verification for ADB installs
11099            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11100                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11101                return false;
11102            }
11103        }
11104
11105        if (ensureVerifyAppsEnabled) {
11106            return true;
11107        }
11108
11109        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11110                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11111    }
11112
11113    @Override
11114    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11115            throws RemoteException {
11116        mContext.enforceCallingOrSelfPermission(
11117                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11118                "Only intentfilter verification agents can verify applications");
11119
11120        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11121        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11122                Binder.getCallingUid(), verificationCode, failedDomains);
11123        msg.arg1 = id;
11124        msg.obj = response;
11125        mHandler.sendMessage(msg);
11126    }
11127
11128    @Override
11129    public int getIntentVerificationStatus(String packageName, int userId) {
11130        synchronized (mPackages) {
11131            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11132        }
11133    }
11134
11135    @Override
11136    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11137        mContext.enforceCallingOrSelfPermission(
11138                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11139
11140        boolean result = false;
11141        synchronized (mPackages) {
11142            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11143        }
11144        if (result) {
11145            scheduleWritePackageRestrictionsLocked(userId);
11146        }
11147        return result;
11148    }
11149
11150    @Override
11151    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11152            String packageName) {
11153        synchronized (mPackages) {
11154            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11155        }
11156    }
11157
11158    @Override
11159    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11160        if (TextUtils.isEmpty(packageName)) {
11161            return ParceledListSlice.emptyList();
11162        }
11163        synchronized (mPackages) {
11164            PackageParser.Package pkg = mPackages.get(packageName);
11165            if (pkg == null || pkg.activities == null) {
11166                return ParceledListSlice.emptyList();
11167            }
11168            final int count = pkg.activities.size();
11169            ArrayList<IntentFilter> result = new ArrayList<>();
11170            for (int n=0; n<count; n++) {
11171                PackageParser.Activity activity = pkg.activities.get(n);
11172                if (activity.intents != null && activity.intents.size() > 0) {
11173                    result.addAll(activity.intents);
11174                }
11175            }
11176            return new ParceledListSlice<>(result);
11177        }
11178    }
11179
11180    @Override
11181    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11182        mContext.enforceCallingOrSelfPermission(
11183                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11184
11185        synchronized (mPackages) {
11186            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11187            if (packageName != null) {
11188                result |= updateIntentVerificationStatus(packageName,
11189                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11190                        userId);
11191                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11192                        packageName, userId);
11193            }
11194            return result;
11195        }
11196    }
11197
11198    @Override
11199    public String getDefaultBrowserPackageName(int userId) {
11200        synchronized (mPackages) {
11201            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11202        }
11203    }
11204
11205    /**
11206     * Get the "allow unknown sources" setting.
11207     *
11208     * @return the current "allow unknown sources" setting
11209     */
11210    private int getUnknownSourcesSettings() {
11211        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11212                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11213                -1);
11214    }
11215
11216    @Override
11217    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11218        final int uid = Binder.getCallingUid();
11219        // writer
11220        synchronized (mPackages) {
11221            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11222            if (targetPackageSetting == null) {
11223                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11224            }
11225
11226            PackageSetting installerPackageSetting;
11227            if (installerPackageName != null) {
11228                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11229                if (installerPackageSetting == null) {
11230                    throw new IllegalArgumentException("Unknown installer package: "
11231                            + installerPackageName);
11232                }
11233            } else {
11234                installerPackageSetting = null;
11235            }
11236
11237            Signature[] callerSignature;
11238            Object obj = mSettings.getUserIdLPr(uid);
11239            if (obj != null) {
11240                if (obj instanceof SharedUserSetting) {
11241                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11242                } else if (obj instanceof PackageSetting) {
11243                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11244                } else {
11245                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11246                }
11247            } else {
11248                throw new SecurityException("Unknown calling UID: " + uid);
11249            }
11250
11251            // Verify: can't set installerPackageName to a package that is
11252            // not signed with the same cert as the caller.
11253            if (installerPackageSetting != null) {
11254                if (compareSignatures(callerSignature,
11255                        installerPackageSetting.signatures.mSignatures)
11256                        != PackageManager.SIGNATURE_MATCH) {
11257                    throw new SecurityException(
11258                            "Caller does not have same cert as new installer package "
11259                            + installerPackageName);
11260                }
11261            }
11262
11263            // Verify: if target already has an installer package, it must
11264            // be signed with the same cert as the caller.
11265            if (targetPackageSetting.installerPackageName != null) {
11266                PackageSetting setting = mSettings.mPackages.get(
11267                        targetPackageSetting.installerPackageName);
11268                // If the currently set package isn't valid, then it's always
11269                // okay to change it.
11270                if (setting != null) {
11271                    if (compareSignatures(callerSignature,
11272                            setting.signatures.mSignatures)
11273                            != PackageManager.SIGNATURE_MATCH) {
11274                        throw new SecurityException(
11275                                "Caller does not have same cert as old installer package "
11276                                + targetPackageSetting.installerPackageName);
11277                    }
11278                }
11279            }
11280
11281            // Okay!
11282            targetPackageSetting.installerPackageName = installerPackageName;
11283            scheduleWriteSettingsLocked();
11284        }
11285    }
11286
11287    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11288        // Queue up an async operation since the package installation may take a little while.
11289        mHandler.post(new Runnable() {
11290            public void run() {
11291                mHandler.removeCallbacks(this);
11292                 // Result object to be returned
11293                PackageInstalledInfo res = new PackageInstalledInfo();
11294                res.setReturnCode(currentStatus);
11295                res.uid = -1;
11296                res.pkg = null;
11297                res.removedInfo = null;
11298                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11299                    args.doPreInstall(res.returnCode);
11300                    synchronized (mInstallLock) {
11301                        installPackageTracedLI(args, res);
11302                    }
11303                    args.doPostInstall(res.returnCode, res.uid);
11304                }
11305
11306                // A restore should be performed at this point if (a) the install
11307                // succeeded, (b) the operation is not an update, and (c) the new
11308                // package has not opted out of backup participation.
11309                final boolean update = res.removedInfo != null
11310                        && res.removedInfo.removedPackage != null;
11311                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11312                boolean doRestore = !update
11313                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11314
11315                // Set up the post-install work request bookkeeping.  This will be used
11316                // and cleaned up by the post-install event handling regardless of whether
11317                // there's a restore pass performed.  Token values are >= 1.
11318                int token;
11319                if (mNextInstallToken < 0) mNextInstallToken = 1;
11320                token = mNextInstallToken++;
11321
11322                PostInstallData data = new PostInstallData(args, res);
11323                mRunningInstalls.put(token, data);
11324                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11325
11326                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11327                    // Pass responsibility to the Backup Manager.  It will perform a
11328                    // restore if appropriate, then pass responsibility back to the
11329                    // Package Manager to run the post-install observer callbacks
11330                    // and broadcasts.
11331                    IBackupManager bm = IBackupManager.Stub.asInterface(
11332                            ServiceManager.getService(Context.BACKUP_SERVICE));
11333                    if (bm != null) {
11334                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11335                                + " to BM for possible restore");
11336                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11337                        try {
11338                            // TODO: http://b/22388012
11339                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11340                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11341                            } else {
11342                                doRestore = false;
11343                            }
11344                        } catch (RemoteException e) {
11345                            // can't happen; the backup manager is local
11346                        } catch (Exception e) {
11347                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11348                            doRestore = false;
11349                        }
11350                    } else {
11351                        Slog.e(TAG, "Backup Manager not found!");
11352                        doRestore = false;
11353                    }
11354                }
11355
11356                if (!doRestore) {
11357                    // No restore possible, or the Backup Manager was mysteriously not
11358                    // available -- just fire the post-install work request directly.
11359                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11360
11361                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11362
11363                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11364                    mHandler.sendMessage(msg);
11365                }
11366            }
11367        });
11368    }
11369
11370    private abstract class HandlerParams {
11371        private static final int MAX_RETRIES = 4;
11372
11373        /**
11374         * Number of times startCopy() has been attempted and had a non-fatal
11375         * error.
11376         */
11377        private int mRetries = 0;
11378
11379        /** User handle for the user requesting the information or installation. */
11380        private final UserHandle mUser;
11381        String traceMethod;
11382        int traceCookie;
11383
11384        HandlerParams(UserHandle user) {
11385            mUser = user;
11386        }
11387
11388        UserHandle getUser() {
11389            return mUser;
11390        }
11391
11392        HandlerParams setTraceMethod(String traceMethod) {
11393            this.traceMethod = traceMethod;
11394            return this;
11395        }
11396
11397        HandlerParams setTraceCookie(int traceCookie) {
11398            this.traceCookie = traceCookie;
11399            return this;
11400        }
11401
11402        final boolean startCopy() {
11403            boolean res;
11404            try {
11405                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11406
11407                if (++mRetries > MAX_RETRIES) {
11408                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11409                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11410                    handleServiceError();
11411                    return false;
11412                } else {
11413                    handleStartCopy();
11414                    res = true;
11415                }
11416            } catch (RemoteException e) {
11417                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11418                mHandler.sendEmptyMessage(MCS_RECONNECT);
11419                res = false;
11420            }
11421            handleReturnCode();
11422            return res;
11423        }
11424
11425        final void serviceError() {
11426            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11427            handleServiceError();
11428            handleReturnCode();
11429        }
11430
11431        abstract void handleStartCopy() throws RemoteException;
11432        abstract void handleServiceError();
11433        abstract void handleReturnCode();
11434    }
11435
11436    class MeasureParams extends HandlerParams {
11437        private final PackageStats mStats;
11438        private boolean mSuccess;
11439
11440        private final IPackageStatsObserver mObserver;
11441
11442        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11443            super(new UserHandle(stats.userHandle));
11444            mObserver = observer;
11445            mStats = stats;
11446        }
11447
11448        @Override
11449        public String toString() {
11450            return "MeasureParams{"
11451                + Integer.toHexString(System.identityHashCode(this))
11452                + " " + mStats.packageName + "}";
11453        }
11454
11455        @Override
11456        void handleStartCopy() throws RemoteException {
11457            synchronized (mInstallLock) {
11458                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11459            }
11460
11461            if (mSuccess) {
11462                final boolean mounted;
11463                if (Environment.isExternalStorageEmulated()) {
11464                    mounted = true;
11465                } else {
11466                    final String status = Environment.getExternalStorageState();
11467                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11468                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11469                }
11470
11471                if (mounted) {
11472                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11473
11474                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11475                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11476
11477                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11478                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11479
11480                    // Always subtract cache size, since it's a subdirectory
11481                    mStats.externalDataSize -= mStats.externalCacheSize;
11482
11483                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11484                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11485
11486                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11487                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11488                }
11489            }
11490        }
11491
11492        @Override
11493        void handleReturnCode() {
11494            if (mObserver != null) {
11495                try {
11496                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11497                } catch (RemoteException e) {
11498                    Slog.i(TAG, "Observer no longer exists.");
11499                }
11500            }
11501        }
11502
11503        @Override
11504        void handleServiceError() {
11505            Slog.e(TAG, "Could not measure application " + mStats.packageName
11506                            + " external storage");
11507        }
11508    }
11509
11510    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11511            throws RemoteException {
11512        long result = 0;
11513        for (File path : paths) {
11514            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11515        }
11516        return result;
11517    }
11518
11519    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11520        for (File path : paths) {
11521            try {
11522                mcs.clearDirectory(path.getAbsolutePath());
11523            } catch (RemoteException e) {
11524            }
11525        }
11526    }
11527
11528    static class OriginInfo {
11529        /**
11530         * Location where install is coming from, before it has been
11531         * copied/renamed into place. This could be a single monolithic APK
11532         * file, or a cluster directory. This location may be untrusted.
11533         */
11534        final File file;
11535        final String cid;
11536
11537        /**
11538         * Flag indicating that {@link #file} or {@link #cid} has already been
11539         * staged, meaning downstream users don't need to defensively copy the
11540         * contents.
11541         */
11542        final boolean staged;
11543
11544        /**
11545         * Flag indicating that {@link #file} or {@link #cid} is an already
11546         * installed app that is being moved.
11547         */
11548        final boolean existing;
11549
11550        final String resolvedPath;
11551        final File resolvedFile;
11552
11553        static OriginInfo fromNothing() {
11554            return new OriginInfo(null, null, false, false);
11555        }
11556
11557        static OriginInfo fromUntrustedFile(File file) {
11558            return new OriginInfo(file, null, false, false);
11559        }
11560
11561        static OriginInfo fromExistingFile(File file) {
11562            return new OriginInfo(file, null, false, true);
11563        }
11564
11565        static OriginInfo fromStagedFile(File file) {
11566            return new OriginInfo(file, null, true, false);
11567        }
11568
11569        static OriginInfo fromStagedContainer(String cid) {
11570            return new OriginInfo(null, cid, true, false);
11571        }
11572
11573        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11574            this.file = file;
11575            this.cid = cid;
11576            this.staged = staged;
11577            this.existing = existing;
11578
11579            if (cid != null) {
11580                resolvedPath = PackageHelper.getSdDir(cid);
11581                resolvedFile = new File(resolvedPath);
11582            } else if (file != null) {
11583                resolvedPath = file.getAbsolutePath();
11584                resolvedFile = file;
11585            } else {
11586                resolvedPath = null;
11587                resolvedFile = null;
11588            }
11589        }
11590    }
11591
11592    static class MoveInfo {
11593        final int moveId;
11594        final String fromUuid;
11595        final String toUuid;
11596        final String packageName;
11597        final String dataAppName;
11598        final int appId;
11599        final String seinfo;
11600        final int targetSdkVersion;
11601
11602        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11603                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11604            this.moveId = moveId;
11605            this.fromUuid = fromUuid;
11606            this.toUuid = toUuid;
11607            this.packageName = packageName;
11608            this.dataAppName = dataAppName;
11609            this.appId = appId;
11610            this.seinfo = seinfo;
11611            this.targetSdkVersion = targetSdkVersion;
11612        }
11613    }
11614
11615    static class VerificationInfo {
11616        /** A constant used to indicate that a uid value is not present. */
11617        public static final int NO_UID = -1;
11618
11619        /** URI referencing where the package was downloaded from. */
11620        final Uri originatingUri;
11621
11622        /** HTTP referrer URI associated with the originatingURI. */
11623        final Uri referrer;
11624
11625        /** UID of the application that the install request originated from. */
11626        final int originatingUid;
11627
11628        /** UID of application requesting the install */
11629        final int installerUid;
11630
11631        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11632            this.originatingUri = originatingUri;
11633            this.referrer = referrer;
11634            this.originatingUid = originatingUid;
11635            this.installerUid = installerUid;
11636        }
11637    }
11638
11639    class InstallParams extends HandlerParams {
11640        final OriginInfo origin;
11641        final MoveInfo move;
11642        final IPackageInstallObserver2 observer;
11643        int installFlags;
11644        final String installerPackageName;
11645        final String volumeUuid;
11646        private InstallArgs mArgs;
11647        private int mRet;
11648        final String packageAbiOverride;
11649        final String[] grantedRuntimePermissions;
11650        final VerificationInfo verificationInfo;
11651
11652        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11653                int installFlags, String installerPackageName, String volumeUuid,
11654                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11655                String[] grantedPermissions) {
11656            super(user);
11657            this.origin = origin;
11658            this.move = move;
11659            this.observer = observer;
11660            this.installFlags = installFlags;
11661            this.installerPackageName = installerPackageName;
11662            this.volumeUuid = volumeUuid;
11663            this.verificationInfo = verificationInfo;
11664            this.packageAbiOverride = packageAbiOverride;
11665            this.grantedRuntimePermissions = grantedPermissions;
11666        }
11667
11668        @Override
11669        public String toString() {
11670            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11671                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11672        }
11673
11674        private int installLocationPolicy(PackageInfoLite pkgLite) {
11675            String packageName = pkgLite.packageName;
11676            int installLocation = pkgLite.installLocation;
11677            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11678            // reader
11679            synchronized (mPackages) {
11680                // Currently installed package which the new package is attempting to replace or
11681                // null if no such package is installed.
11682                PackageParser.Package installedPkg = mPackages.get(packageName);
11683                // Package which currently owns the data which the new package will own if installed.
11684                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11685                // will be null whereas dataOwnerPkg will contain information about the package
11686                // which was uninstalled while keeping its data.
11687                PackageParser.Package dataOwnerPkg = installedPkg;
11688                if (dataOwnerPkg  == null) {
11689                    PackageSetting ps = mSettings.mPackages.get(packageName);
11690                    if (ps != null) {
11691                        dataOwnerPkg = ps.pkg;
11692                    }
11693                }
11694
11695                if (dataOwnerPkg != null) {
11696                    // If installed, the package will get access to data left on the device by its
11697                    // predecessor. As a security measure, this is permited only if this is not a
11698                    // version downgrade or if the predecessor package is marked as debuggable and
11699                    // a downgrade is explicitly requested.
11700                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11701                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11702                        try {
11703                            checkDowngrade(dataOwnerPkg, pkgLite);
11704                        } catch (PackageManagerException e) {
11705                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11706                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11707                        }
11708                    }
11709                }
11710
11711                if (installedPkg != null) {
11712                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11713                        // Check for updated system application.
11714                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11715                            if (onSd) {
11716                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11717                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11718                            }
11719                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11720                        } else {
11721                            if (onSd) {
11722                                // Install flag overrides everything.
11723                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11724                            }
11725                            // If current upgrade specifies particular preference
11726                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11727                                // Application explicitly specified internal.
11728                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11729                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11730                                // App explictly prefers external. Let policy decide
11731                            } else {
11732                                // Prefer previous location
11733                                if (isExternal(installedPkg)) {
11734                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11735                                }
11736                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11737                            }
11738                        }
11739                    } else {
11740                        // Invalid install. Return error code
11741                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11742                    }
11743                }
11744            }
11745            // All the special cases have been taken care of.
11746            // Return result based on recommended install location.
11747            if (onSd) {
11748                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11749            }
11750            return pkgLite.recommendedInstallLocation;
11751        }
11752
11753        /*
11754         * Invoke remote method to get package information and install
11755         * location values. Override install location based on default
11756         * policy if needed and then create install arguments based
11757         * on the install location.
11758         */
11759        public void handleStartCopy() throws RemoteException {
11760            int ret = PackageManager.INSTALL_SUCCEEDED;
11761
11762            // If we're already staged, we've firmly committed to an install location
11763            if (origin.staged) {
11764                if (origin.file != null) {
11765                    installFlags |= PackageManager.INSTALL_INTERNAL;
11766                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11767                } else if (origin.cid != null) {
11768                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11769                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11770                } else {
11771                    throw new IllegalStateException("Invalid stage location");
11772                }
11773            }
11774
11775            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11776            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11777            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11778            PackageInfoLite pkgLite = null;
11779
11780            if (onInt && onSd) {
11781                // Check if both bits are set.
11782                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11783                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11784            } else if (onSd && ephemeral) {
11785                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11786                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11787            } else {
11788                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11789                        packageAbiOverride);
11790
11791                if (DEBUG_EPHEMERAL && ephemeral) {
11792                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11793                }
11794
11795                /*
11796                 * If we have too little free space, try to free cache
11797                 * before giving up.
11798                 */
11799                if (!origin.staged && pkgLite.recommendedInstallLocation
11800                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11801                    // TODO: focus freeing disk space on the target device
11802                    final StorageManager storage = StorageManager.from(mContext);
11803                    final long lowThreshold = storage.getStorageLowBytes(
11804                            Environment.getDataDirectory());
11805
11806                    final long sizeBytes = mContainerService.calculateInstalledSize(
11807                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11808
11809                    try {
11810                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11811                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11812                                installFlags, packageAbiOverride);
11813                    } catch (InstallerException e) {
11814                        Slog.w(TAG, "Failed to free cache", e);
11815                    }
11816
11817                    /*
11818                     * The cache free must have deleted the file we
11819                     * downloaded to install.
11820                     *
11821                     * TODO: fix the "freeCache" call to not delete
11822                     *       the file we care about.
11823                     */
11824                    if (pkgLite.recommendedInstallLocation
11825                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11826                        pkgLite.recommendedInstallLocation
11827                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11828                    }
11829                }
11830            }
11831
11832            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11833                int loc = pkgLite.recommendedInstallLocation;
11834                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11835                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11836                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11837                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11838                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11839                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11840                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11841                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11843                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11844                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11845                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11846                } else {
11847                    // Override with defaults if needed.
11848                    loc = installLocationPolicy(pkgLite);
11849                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11850                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11851                    } else if (!onSd && !onInt) {
11852                        // Override install location with flags
11853                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11854                            // Set the flag to install on external media.
11855                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11856                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11857                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11858                            if (DEBUG_EPHEMERAL) {
11859                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11860                            }
11861                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11862                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11863                                    |PackageManager.INSTALL_INTERNAL);
11864                        } else {
11865                            // Make sure the flag for installing on external
11866                            // media is unset
11867                            installFlags |= PackageManager.INSTALL_INTERNAL;
11868                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11869                        }
11870                    }
11871                }
11872            }
11873
11874            final InstallArgs args = createInstallArgs(this);
11875            mArgs = args;
11876
11877            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11878                // TODO: http://b/22976637
11879                // Apps installed for "all" users use the device owner to verify the app
11880                UserHandle verifierUser = getUser();
11881                if (verifierUser == UserHandle.ALL) {
11882                    verifierUser = UserHandle.SYSTEM;
11883                }
11884
11885                /*
11886                 * Determine if we have any installed package verifiers. If we
11887                 * do, then we'll defer to them to verify the packages.
11888                 */
11889                final int requiredUid = mRequiredVerifierPackage == null ? -1
11890                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11891                                verifierUser.getIdentifier());
11892                if (!origin.existing && requiredUid != -1
11893                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11894                    final Intent verification = new Intent(
11895                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11896                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11897                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11898                            PACKAGE_MIME_TYPE);
11899                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11900
11901                    // Query all live verifiers based on current user state
11902                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
11903                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11904
11905                    if (DEBUG_VERIFY) {
11906                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11907                                + verification.toString() + " with " + pkgLite.verifiers.length
11908                                + " optional verifiers");
11909                    }
11910
11911                    final int verificationId = mPendingVerificationToken++;
11912
11913                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11914
11915                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11916                            installerPackageName);
11917
11918                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11919                            installFlags);
11920
11921                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11922                            pkgLite.packageName);
11923
11924                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11925                            pkgLite.versionCode);
11926
11927                    if (verificationInfo != null) {
11928                        if (verificationInfo.originatingUri != null) {
11929                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11930                                    verificationInfo.originatingUri);
11931                        }
11932                        if (verificationInfo.referrer != null) {
11933                            verification.putExtra(Intent.EXTRA_REFERRER,
11934                                    verificationInfo.referrer);
11935                        }
11936                        if (verificationInfo.originatingUid >= 0) {
11937                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11938                                    verificationInfo.originatingUid);
11939                        }
11940                        if (verificationInfo.installerUid >= 0) {
11941                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11942                                    verificationInfo.installerUid);
11943                        }
11944                    }
11945
11946                    final PackageVerificationState verificationState = new PackageVerificationState(
11947                            requiredUid, args);
11948
11949                    mPendingVerification.append(verificationId, verificationState);
11950
11951                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11952                            receivers, verificationState);
11953
11954                    /*
11955                     * If any sufficient verifiers were listed in the package
11956                     * manifest, attempt to ask them.
11957                     */
11958                    if (sufficientVerifiers != null) {
11959                        final int N = sufficientVerifiers.size();
11960                        if (N == 0) {
11961                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11962                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11963                        } else {
11964                            for (int i = 0; i < N; i++) {
11965                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11966
11967                                final Intent sufficientIntent = new Intent(verification);
11968                                sufficientIntent.setComponent(verifierComponent);
11969                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11970                            }
11971                        }
11972                    }
11973
11974                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11975                            mRequiredVerifierPackage, receivers);
11976                    if (ret == PackageManager.INSTALL_SUCCEEDED
11977                            && mRequiredVerifierPackage != null) {
11978                        Trace.asyncTraceBegin(
11979                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11980                        /*
11981                         * Send the intent to the required verification agent,
11982                         * but only start the verification timeout after the
11983                         * target BroadcastReceivers have run.
11984                         */
11985                        verification.setComponent(requiredVerifierComponent);
11986                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11987                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11988                                new BroadcastReceiver() {
11989                                    @Override
11990                                    public void onReceive(Context context, Intent intent) {
11991                                        final Message msg = mHandler
11992                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11993                                        msg.arg1 = verificationId;
11994                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11995                                    }
11996                                }, null, 0, null, null);
11997
11998                        /*
11999                         * We don't want the copy to proceed until verification
12000                         * succeeds, so null out this field.
12001                         */
12002                        mArgs = null;
12003                    }
12004                } else {
12005                    /*
12006                     * No package verification is enabled, so immediately start
12007                     * the remote call to initiate copy using temporary file.
12008                     */
12009                    ret = args.copyApk(mContainerService, true);
12010                }
12011            }
12012
12013            mRet = ret;
12014        }
12015
12016        @Override
12017        void handleReturnCode() {
12018            // If mArgs is null, then MCS couldn't be reached. When it
12019            // reconnects, it will try again to install. At that point, this
12020            // will succeed.
12021            if (mArgs != null) {
12022                processPendingInstall(mArgs, mRet);
12023            }
12024        }
12025
12026        @Override
12027        void handleServiceError() {
12028            mArgs = createInstallArgs(this);
12029            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12030        }
12031
12032        public boolean isForwardLocked() {
12033            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12034        }
12035    }
12036
12037    /**
12038     * Used during creation of InstallArgs
12039     *
12040     * @param installFlags package installation flags
12041     * @return true if should be installed on external storage
12042     */
12043    private static boolean installOnExternalAsec(int installFlags) {
12044        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12045            return false;
12046        }
12047        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12048            return true;
12049        }
12050        return false;
12051    }
12052
12053    /**
12054     * Used during creation of InstallArgs
12055     *
12056     * @param installFlags package installation flags
12057     * @return true if should be installed as forward locked
12058     */
12059    private static boolean installForwardLocked(int installFlags) {
12060        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12061    }
12062
12063    private InstallArgs createInstallArgs(InstallParams params) {
12064        if (params.move != null) {
12065            return new MoveInstallArgs(params);
12066        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12067            return new AsecInstallArgs(params);
12068        } else {
12069            return new FileInstallArgs(params);
12070        }
12071    }
12072
12073    /**
12074     * Create args that describe an existing installed package. Typically used
12075     * when cleaning up old installs, or used as a move source.
12076     */
12077    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12078            String resourcePath, String[] instructionSets) {
12079        final boolean isInAsec;
12080        if (installOnExternalAsec(installFlags)) {
12081            /* Apps on SD card are always in ASEC containers. */
12082            isInAsec = true;
12083        } else if (installForwardLocked(installFlags)
12084                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12085            /*
12086             * Forward-locked apps are only in ASEC containers if they're the
12087             * new style
12088             */
12089            isInAsec = true;
12090        } else {
12091            isInAsec = false;
12092        }
12093
12094        if (isInAsec) {
12095            return new AsecInstallArgs(codePath, instructionSets,
12096                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12097        } else {
12098            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12099        }
12100    }
12101
12102    static abstract class InstallArgs {
12103        /** @see InstallParams#origin */
12104        final OriginInfo origin;
12105        /** @see InstallParams#move */
12106        final MoveInfo move;
12107
12108        final IPackageInstallObserver2 observer;
12109        // Always refers to PackageManager flags only
12110        final int installFlags;
12111        final String installerPackageName;
12112        final String volumeUuid;
12113        final UserHandle user;
12114        final String abiOverride;
12115        final String[] installGrantPermissions;
12116        /** If non-null, drop an async trace when the install completes */
12117        final String traceMethod;
12118        final int traceCookie;
12119
12120        // The list of instruction sets supported by this app. This is currently
12121        // only used during the rmdex() phase to clean up resources. We can get rid of this
12122        // if we move dex files under the common app path.
12123        /* nullable */ String[] instructionSets;
12124
12125        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12126                int installFlags, String installerPackageName, String volumeUuid,
12127                UserHandle user, String[] instructionSets,
12128                String abiOverride, String[] installGrantPermissions,
12129                String traceMethod, int traceCookie) {
12130            this.origin = origin;
12131            this.move = move;
12132            this.installFlags = installFlags;
12133            this.observer = observer;
12134            this.installerPackageName = installerPackageName;
12135            this.volumeUuid = volumeUuid;
12136            this.user = user;
12137            this.instructionSets = instructionSets;
12138            this.abiOverride = abiOverride;
12139            this.installGrantPermissions = installGrantPermissions;
12140            this.traceMethod = traceMethod;
12141            this.traceCookie = traceCookie;
12142        }
12143
12144        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12145        abstract int doPreInstall(int status);
12146
12147        /**
12148         * Rename package into final resting place. All paths on the given
12149         * scanned package should be updated to reflect the rename.
12150         */
12151        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12152        abstract int doPostInstall(int status, int uid);
12153
12154        /** @see PackageSettingBase#codePathString */
12155        abstract String getCodePath();
12156        /** @see PackageSettingBase#resourcePathString */
12157        abstract String getResourcePath();
12158
12159        // Need installer lock especially for dex file removal.
12160        abstract void cleanUpResourcesLI();
12161        abstract boolean doPostDeleteLI(boolean delete);
12162
12163        /**
12164         * Called before the source arguments are copied. This is used mostly
12165         * for MoveParams when it needs to read the source file to put it in the
12166         * destination.
12167         */
12168        int doPreCopy() {
12169            return PackageManager.INSTALL_SUCCEEDED;
12170        }
12171
12172        /**
12173         * Called after the source arguments are copied. This is used mostly for
12174         * MoveParams when it needs to read the source file to put it in the
12175         * destination.
12176         *
12177         * @return
12178         */
12179        int doPostCopy(int uid) {
12180            return PackageManager.INSTALL_SUCCEEDED;
12181        }
12182
12183        protected boolean isFwdLocked() {
12184            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12185        }
12186
12187        protected boolean isExternalAsec() {
12188            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12189        }
12190
12191        protected boolean isEphemeral() {
12192            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12193        }
12194
12195        UserHandle getUser() {
12196            return user;
12197        }
12198    }
12199
12200    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12201        if (!allCodePaths.isEmpty()) {
12202            if (instructionSets == null) {
12203                throw new IllegalStateException("instructionSet == null");
12204            }
12205            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12206            for (String codePath : allCodePaths) {
12207                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12208                    try {
12209                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12210                    } catch (InstallerException ignored) {
12211                    }
12212                }
12213            }
12214        }
12215    }
12216
12217    /**
12218     * Logic to handle installation of non-ASEC applications, including copying
12219     * and renaming logic.
12220     */
12221    class FileInstallArgs extends InstallArgs {
12222        private File codeFile;
12223        private File resourceFile;
12224
12225        // Example topology:
12226        // /data/app/com.example/base.apk
12227        // /data/app/com.example/split_foo.apk
12228        // /data/app/com.example/lib/arm/libfoo.so
12229        // /data/app/com.example/lib/arm64/libfoo.so
12230        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12231
12232        /** New install */
12233        FileInstallArgs(InstallParams params) {
12234            super(params.origin, params.move, params.observer, params.installFlags,
12235                    params.installerPackageName, params.volumeUuid,
12236                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12237                    params.grantedRuntimePermissions,
12238                    params.traceMethod, params.traceCookie);
12239            if (isFwdLocked()) {
12240                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12241            }
12242        }
12243
12244        /** Existing install */
12245        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12246            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12247                    null, null, null, 0);
12248            this.codeFile = (codePath != null) ? new File(codePath) : null;
12249            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12250        }
12251
12252        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12253            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12254            try {
12255                return doCopyApk(imcs, temp);
12256            } finally {
12257                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12258            }
12259        }
12260
12261        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12262            if (origin.staged) {
12263                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12264                codeFile = origin.file;
12265                resourceFile = origin.file;
12266                return PackageManager.INSTALL_SUCCEEDED;
12267            }
12268
12269            try {
12270                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12271                final File tempDir =
12272                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12273                codeFile = tempDir;
12274                resourceFile = tempDir;
12275            } catch (IOException e) {
12276                Slog.w(TAG, "Failed to create copy file: " + e);
12277                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12278            }
12279
12280            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12281                @Override
12282                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12283                    if (!FileUtils.isValidExtFilename(name)) {
12284                        throw new IllegalArgumentException("Invalid filename: " + name);
12285                    }
12286                    try {
12287                        final File file = new File(codeFile, name);
12288                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12289                                O_RDWR | O_CREAT, 0644);
12290                        Os.chmod(file.getAbsolutePath(), 0644);
12291                        return new ParcelFileDescriptor(fd);
12292                    } catch (ErrnoException e) {
12293                        throw new RemoteException("Failed to open: " + e.getMessage());
12294                    }
12295                }
12296            };
12297
12298            int ret = PackageManager.INSTALL_SUCCEEDED;
12299            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12300            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12301                Slog.e(TAG, "Failed to copy package");
12302                return ret;
12303            }
12304
12305            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12306            NativeLibraryHelper.Handle handle = null;
12307            try {
12308                handle = NativeLibraryHelper.Handle.create(codeFile);
12309                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12310                        abiOverride);
12311            } catch (IOException e) {
12312                Slog.e(TAG, "Copying native libraries failed", e);
12313                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12314            } finally {
12315                IoUtils.closeQuietly(handle);
12316            }
12317
12318            return ret;
12319        }
12320
12321        int doPreInstall(int status) {
12322            if (status != PackageManager.INSTALL_SUCCEEDED) {
12323                cleanUp();
12324            }
12325            return status;
12326        }
12327
12328        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12329            if (status != PackageManager.INSTALL_SUCCEEDED) {
12330                cleanUp();
12331                return false;
12332            }
12333
12334            final File targetDir = codeFile.getParentFile();
12335            final File beforeCodeFile = codeFile;
12336            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12337
12338            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12339            try {
12340                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12341            } catch (ErrnoException e) {
12342                Slog.w(TAG, "Failed to rename", e);
12343                return false;
12344            }
12345
12346            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12347                Slog.w(TAG, "Failed to restorecon");
12348                return false;
12349            }
12350
12351            // Reflect the rename internally
12352            codeFile = afterCodeFile;
12353            resourceFile = afterCodeFile;
12354
12355            // Reflect the rename in scanned details
12356            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12357            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12358                    afterCodeFile, pkg.baseCodePath));
12359            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12360                    afterCodeFile, pkg.splitCodePaths));
12361
12362            // Reflect the rename in app info
12363            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12364            pkg.setApplicationInfoCodePath(pkg.codePath);
12365            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12366            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12367            pkg.setApplicationInfoResourcePath(pkg.codePath);
12368            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12369            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12370
12371            return true;
12372        }
12373
12374        int doPostInstall(int status, int uid) {
12375            if (status != PackageManager.INSTALL_SUCCEEDED) {
12376                cleanUp();
12377            }
12378            return status;
12379        }
12380
12381        @Override
12382        String getCodePath() {
12383            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12384        }
12385
12386        @Override
12387        String getResourcePath() {
12388            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12389        }
12390
12391        private boolean cleanUp() {
12392            if (codeFile == null || !codeFile.exists()) {
12393                return false;
12394            }
12395
12396            removeCodePathLI(codeFile);
12397
12398            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12399                resourceFile.delete();
12400            }
12401
12402            return true;
12403        }
12404
12405        void cleanUpResourcesLI() {
12406            // Try enumerating all code paths before deleting
12407            List<String> allCodePaths = Collections.EMPTY_LIST;
12408            if (codeFile != null && codeFile.exists()) {
12409                try {
12410                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12411                    allCodePaths = pkg.getAllCodePaths();
12412                } catch (PackageParserException e) {
12413                    // Ignored; we tried our best
12414                }
12415            }
12416
12417            cleanUp();
12418            removeDexFiles(allCodePaths, instructionSets);
12419        }
12420
12421        boolean doPostDeleteLI(boolean delete) {
12422            // XXX err, shouldn't we respect the delete flag?
12423            cleanUpResourcesLI();
12424            return true;
12425        }
12426    }
12427
12428    private boolean isAsecExternal(String cid) {
12429        final String asecPath = PackageHelper.getSdFilesystem(cid);
12430        return !asecPath.startsWith(mAsecInternalPath);
12431    }
12432
12433    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12434            PackageManagerException {
12435        if (copyRet < 0) {
12436            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12437                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12438                throw new PackageManagerException(copyRet, message);
12439            }
12440        }
12441    }
12442
12443    /**
12444     * Extract the MountService "container ID" from the full code path of an
12445     * .apk.
12446     */
12447    static String cidFromCodePath(String fullCodePath) {
12448        int eidx = fullCodePath.lastIndexOf("/");
12449        String subStr1 = fullCodePath.substring(0, eidx);
12450        int sidx = subStr1.lastIndexOf("/");
12451        return subStr1.substring(sidx+1, eidx);
12452    }
12453
12454    /**
12455     * Logic to handle installation of ASEC applications, including copying and
12456     * renaming logic.
12457     */
12458    class AsecInstallArgs extends InstallArgs {
12459        static final String RES_FILE_NAME = "pkg.apk";
12460        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12461
12462        String cid;
12463        String packagePath;
12464        String resourcePath;
12465
12466        /** New install */
12467        AsecInstallArgs(InstallParams params) {
12468            super(params.origin, params.move, params.observer, params.installFlags,
12469                    params.installerPackageName, params.volumeUuid,
12470                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12471                    params.grantedRuntimePermissions,
12472                    params.traceMethod, params.traceCookie);
12473        }
12474
12475        /** Existing install */
12476        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12477                        boolean isExternal, boolean isForwardLocked) {
12478            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12479                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12480                    instructionSets, null, null, null, 0);
12481            // Hackily pretend we're still looking at a full code path
12482            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12483                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12484            }
12485
12486            // Extract cid from fullCodePath
12487            int eidx = fullCodePath.lastIndexOf("/");
12488            String subStr1 = fullCodePath.substring(0, eidx);
12489            int sidx = subStr1.lastIndexOf("/");
12490            cid = subStr1.substring(sidx+1, eidx);
12491            setMountPath(subStr1);
12492        }
12493
12494        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12495            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12496                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12497                    instructionSets, null, null, null, 0);
12498            this.cid = cid;
12499            setMountPath(PackageHelper.getSdDir(cid));
12500        }
12501
12502        void createCopyFile() {
12503            cid = mInstallerService.allocateExternalStageCidLegacy();
12504        }
12505
12506        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12507            if (origin.staged && origin.cid != null) {
12508                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12509                cid = origin.cid;
12510                setMountPath(PackageHelper.getSdDir(cid));
12511                return PackageManager.INSTALL_SUCCEEDED;
12512            }
12513
12514            if (temp) {
12515                createCopyFile();
12516            } else {
12517                /*
12518                 * Pre-emptively destroy the container since it's destroyed if
12519                 * copying fails due to it existing anyway.
12520                 */
12521                PackageHelper.destroySdDir(cid);
12522            }
12523
12524            final String newMountPath = imcs.copyPackageToContainer(
12525                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12526                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12527
12528            if (newMountPath != null) {
12529                setMountPath(newMountPath);
12530                return PackageManager.INSTALL_SUCCEEDED;
12531            } else {
12532                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12533            }
12534        }
12535
12536        @Override
12537        String getCodePath() {
12538            return packagePath;
12539        }
12540
12541        @Override
12542        String getResourcePath() {
12543            return resourcePath;
12544        }
12545
12546        int doPreInstall(int status) {
12547            if (status != PackageManager.INSTALL_SUCCEEDED) {
12548                // Destroy container
12549                PackageHelper.destroySdDir(cid);
12550            } else {
12551                boolean mounted = PackageHelper.isContainerMounted(cid);
12552                if (!mounted) {
12553                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12554                            Process.SYSTEM_UID);
12555                    if (newMountPath != null) {
12556                        setMountPath(newMountPath);
12557                    } else {
12558                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12559                    }
12560                }
12561            }
12562            return status;
12563        }
12564
12565        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12566            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12567            String newMountPath = null;
12568            if (PackageHelper.isContainerMounted(cid)) {
12569                // Unmount the container
12570                if (!PackageHelper.unMountSdDir(cid)) {
12571                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12572                    return false;
12573                }
12574            }
12575            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12576                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12577                        " which might be stale. Will try to clean up.");
12578                // Clean up the stale container and proceed to recreate.
12579                if (!PackageHelper.destroySdDir(newCacheId)) {
12580                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12581                    return false;
12582                }
12583                // Successfully cleaned up stale container. Try to rename again.
12584                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12585                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12586                            + " inspite of cleaning it up.");
12587                    return false;
12588                }
12589            }
12590            if (!PackageHelper.isContainerMounted(newCacheId)) {
12591                Slog.w(TAG, "Mounting container " + newCacheId);
12592                newMountPath = PackageHelper.mountSdDir(newCacheId,
12593                        getEncryptKey(), Process.SYSTEM_UID);
12594            } else {
12595                newMountPath = PackageHelper.getSdDir(newCacheId);
12596            }
12597            if (newMountPath == null) {
12598                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12599                return false;
12600            }
12601            Log.i(TAG, "Succesfully renamed " + cid +
12602                    " to " + newCacheId +
12603                    " at new path: " + newMountPath);
12604            cid = newCacheId;
12605
12606            final File beforeCodeFile = new File(packagePath);
12607            setMountPath(newMountPath);
12608            final File afterCodeFile = new File(packagePath);
12609
12610            // Reflect the rename in scanned details
12611            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12612            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12613                    afterCodeFile, pkg.baseCodePath));
12614            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12615                    afterCodeFile, pkg.splitCodePaths));
12616
12617            // Reflect the rename in app info
12618            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12619            pkg.setApplicationInfoCodePath(pkg.codePath);
12620            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12621            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12622            pkg.setApplicationInfoResourcePath(pkg.codePath);
12623            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12624            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12625
12626            return true;
12627        }
12628
12629        private void setMountPath(String mountPath) {
12630            final File mountFile = new File(mountPath);
12631
12632            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12633            if (monolithicFile.exists()) {
12634                packagePath = monolithicFile.getAbsolutePath();
12635                if (isFwdLocked()) {
12636                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12637                } else {
12638                    resourcePath = packagePath;
12639                }
12640            } else {
12641                packagePath = mountFile.getAbsolutePath();
12642                resourcePath = packagePath;
12643            }
12644        }
12645
12646        int doPostInstall(int status, int uid) {
12647            if (status != PackageManager.INSTALL_SUCCEEDED) {
12648                cleanUp();
12649            } else {
12650                final int groupOwner;
12651                final String protectedFile;
12652                if (isFwdLocked()) {
12653                    groupOwner = UserHandle.getSharedAppGid(uid);
12654                    protectedFile = RES_FILE_NAME;
12655                } else {
12656                    groupOwner = -1;
12657                    protectedFile = null;
12658                }
12659
12660                if (uid < Process.FIRST_APPLICATION_UID
12661                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12662                    Slog.e(TAG, "Failed to finalize " + cid);
12663                    PackageHelper.destroySdDir(cid);
12664                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12665                }
12666
12667                boolean mounted = PackageHelper.isContainerMounted(cid);
12668                if (!mounted) {
12669                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12670                }
12671            }
12672            return status;
12673        }
12674
12675        private void cleanUp() {
12676            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12677
12678            // Destroy secure container
12679            PackageHelper.destroySdDir(cid);
12680        }
12681
12682        private List<String> getAllCodePaths() {
12683            final File codeFile = new File(getCodePath());
12684            if (codeFile != null && codeFile.exists()) {
12685                try {
12686                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12687                    return pkg.getAllCodePaths();
12688                } catch (PackageParserException e) {
12689                    // Ignored; we tried our best
12690                }
12691            }
12692            return Collections.EMPTY_LIST;
12693        }
12694
12695        void cleanUpResourcesLI() {
12696            // Enumerate all code paths before deleting
12697            cleanUpResourcesLI(getAllCodePaths());
12698        }
12699
12700        private void cleanUpResourcesLI(List<String> allCodePaths) {
12701            cleanUp();
12702            removeDexFiles(allCodePaths, instructionSets);
12703        }
12704
12705        String getPackageName() {
12706            return getAsecPackageName(cid);
12707        }
12708
12709        boolean doPostDeleteLI(boolean delete) {
12710            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12711            final List<String> allCodePaths = getAllCodePaths();
12712            boolean mounted = PackageHelper.isContainerMounted(cid);
12713            if (mounted) {
12714                // Unmount first
12715                if (PackageHelper.unMountSdDir(cid)) {
12716                    mounted = false;
12717                }
12718            }
12719            if (!mounted && delete) {
12720                cleanUpResourcesLI(allCodePaths);
12721            }
12722            return !mounted;
12723        }
12724
12725        @Override
12726        int doPreCopy() {
12727            if (isFwdLocked()) {
12728                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12729                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12730                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12731                }
12732            }
12733
12734            return PackageManager.INSTALL_SUCCEEDED;
12735        }
12736
12737        @Override
12738        int doPostCopy(int uid) {
12739            if (isFwdLocked()) {
12740                if (uid < Process.FIRST_APPLICATION_UID
12741                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12742                                RES_FILE_NAME)) {
12743                    Slog.e(TAG, "Failed to finalize " + cid);
12744                    PackageHelper.destroySdDir(cid);
12745                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12746                }
12747            }
12748
12749            return PackageManager.INSTALL_SUCCEEDED;
12750        }
12751    }
12752
12753    /**
12754     * Logic to handle movement of existing installed applications.
12755     */
12756    class MoveInstallArgs extends InstallArgs {
12757        private File codeFile;
12758        private File resourceFile;
12759
12760        /** New install */
12761        MoveInstallArgs(InstallParams params) {
12762            super(params.origin, params.move, params.observer, params.installFlags,
12763                    params.installerPackageName, params.volumeUuid,
12764                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12765                    params.grantedRuntimePermissions,
12766                    params.traceMethod, params.traceCookie);
12767        }
12768
12769        int copyApk(IMediaContainerService imcs, boolean temp) {
12770            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12771                    + move.fromUuid + " to " + move.toUuid);
12772            synchronized (mInstaller) {
12773                try {
12774                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12775                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12776                } catch (InstallerException e) {
12777                    Slog.w(TAG, "Failed to move app", e);
12778                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12779                }
12780            }
12781
12782            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12783            resourceFile = codeFile;
12784            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12785
12786            return PackageManager.INSTALL_SUCCEEDED;
12787        }
12788
12789        int doPreInstall(int status) {
12790            if (status != PackageManager.INSTALL_SUCCEEDED) {
12791                cleanUp(move.toUuid);
12792            }
12793            return status;
12794        }
12795
12796        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12797            if (status != PackageManager.INSTALL_SUCCEEDED) {
12798                cleanUp(move.toUuid);
12799                return false;
12800            }
12801
12802            // Reflect the move in app info
12803            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12804            pkg.setApplicationInfoCodePath(pkg.codePath);
12805            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12806            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12807            pkg.setApplicationInfoResourcePath(pkg.codePath);
12808            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12809            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12810
12811            return true;
12812        }
12813
12814        int doPostInstall(int status, int uid) {
12815            if (status == PackageManager.INSTALL_SUCCEEDED) {
12816                cleanUp(move.fromUuid);
12817            } else {
12818                cleanUp(move.toUuid);
12819            }
12820            return status;
12821        }
12822
12823        @Override
12824        String getCodePath() {
12825            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12826        }
12827
12828        @Override
12829        String getResourcePath() {
12830            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12831        }
12832
12833        private boolean cleanUp(String volumeUuid) {
12834            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12835                    move.dataAppName);
12836            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12837            synchronized (mInstallLock) {
12838                // Clean up both app data and code
12839                removeDataDirsLI(volumeUuid, move.packageName);
12840                removeCodePathLI(codeFile);
12841            }
12842            return true;
12843        }
12844
12845        void cleanUpResourcesLI() {
12846            throw new UnsupportedOperationException();
12847        }
12848
12849        boolean doPostDeleteLI(boolean delete) {
12850            throw new UnsupportedOperationException();
12851        }
12852    }
12853
12854    static String getAsecPackageName(String packageCid) {
12855        int idx = packageCid.lastIndexOf("-");
12856        if (idx == -1) {
12857            return packageCid;
12858        }
12859        return packageCid.substring(0, idx);
12860    }
12861
12862    // Utility method used to create code paths based on package name and available index.
12863    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12864        String idxStr = "";
12865        int idx = 1;
12866        // Fall back to default value of idx=1 if prefix is not
12867        // part of oldCodePath
12868        if (oldCodePath != null) {
12869            String subStr = oldCodePath;
12870            // Drop the suffix right away
12871            if (suffix != null && subStr.endsWith(suffix)) {
12872                subStr = subStr.substring(0, subStr.length() - suffix.length());
12873            }
12874            // If oldCodePath already contains prefix find out the
12875            // ending index to either increment or decrement.
12876            int sidx = subStr.lastIndexOf(prefix);
12877            if (sidx != -1) {
12878                subStr = subStr.substring(sidx + prefix.length());
12879                if (subStr != null) {
12880                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12881                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12882                    }
12883                    try {
12884                        idx = Integer.parseInt(subStr);
12885                        if (idx <= 1) {
12886                            idx++;
12887                        } else {
12888                            idx--;
12889                        }
12890                    } catch(NumberFormatException e) {
12891                    }
12892                }
12893            }
12894        }
12895        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12896        return prefix + idxStr;
12897    }
12898
12899    private File getNextCodePath(File targetDir, String packageName) {
12900        int suffix = 1;
12901        File result;
12902        do {
12903            result = new File(targetDir, packageName + "-" + suffix);
12904            suffix++;
12905        } while (result.exists());
12906        return result;
12907    }
12908
12909    // Utility method that returns the relative package path with respect
12910    // to the installation directory. Like say for /data/data/com.test-1.apk
12911    // string com.test-1 is returned.
12912    static String deriveCodePathName(String codePath) {
12913        if (codePath == null) {
12914            return null;
12915        }
12916        final File codeFile = new File(codePath);
12917        final String name = codeFile.getName();
12918        if (codeFile.isDirectory()) {
12919            return name;
12920        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12921            final int lastDot = name.lastIndexOf('.');
12922            return name.substring(0, lastDot);
12923        } else {
12924            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12925            return null;
12926        }
12927    }
12928
12929    static class PackageInstalledInfo {
12930        String name;
12931        int uid;
12932        // The set of users that originally had this package installed.
12933        int[] origUsers;
12934        // The set of users that now have this package installed.
12935        int[] newUsers;
12936        PackageParser.Package pkg;
12937        int returnCode;
12938        String returnMsg;
12939        PackageRemovedInfo removedInfo;
12940        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12941
12942        public void setError(int code, String msg) {
12943            setReturnCode(code);
12944            setReturnMessage(msg);
12945            Slog.w(TAG, msg);
12946        }
12947
12948        public void setError(String msg, PackageParserException e) {
12949            setReturnCode(e.error);
12950            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12951            Slog.w(TAG, msg, e);
12952        }
12953
12954        public void setError(String msg, PackageManagerException e) {
12955            returnCode = e.error;
12956            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12957            Slog.w(TAG, msg, e);
12958        }
12959
12960        public void setReturnCode(int returnCode) {
12961            this.returnCode = returnCode;
12962            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12963            for (int i = 0; i < childCount; i++) {
12964                addedChildPackages.valueAt(i).returnCode = returnCode;
12965            }
12966        }
12967
12968        private void setReturnMessage(String returnMsg) {
12969            this.returnMsg = returnMsg;
12970            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12971            for (int i = 0; i < childCount; i++) {
12972                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12973            }
12974        }
12975
12976        // In some error cases we want to convey more info back to the observer
12977        String origPackage;
12978        String origPermission;
12979    }
12980
12981    /*
12982     * Install a non-existing package.
12983     */
12984    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12985            UserHandle user, String installerPackageName, String volumeUuid,
12986            PackageInstalledInfo res) {
12987        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12988
12989        // Remember this for later, in case we need to rollback this install
12990        String pkgName = pkg.packageName;
12991
12992        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12993
12994        synchronized(mPackages) {
12995            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12996                // A package with the same name is already installed, though
12997                // it has been renamed to an older name.  The package we
12998                // are trying to install should be installed as an update to
12999                // the existing one, but that has not been requested, so bail.
13000                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13001                        + " without first uninstalling package running as "
13002                        + mSettings.mRenamedPackages.get(pkgName));
13003                return;
13004            }
13005            if (mPackages.containsKey(pkgName)) {
13006                // Don't allow installation over an existing package with the same name.
13007                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13008                        + " without first uninstalling.");
13009                return;
13010            }
13011        }
13012
13013        try {
13014            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13015                    System.currentTimeMillis(), user);
13016
13017            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13018
13019            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13020                prepareAppDataAfterInstall(newPackage);
13021
13022            } else {
13023                // Remove package from internal structures, but keep around any
13024                // data that might have already existed
13025                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13026                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13027            }
13028        } catch (PackageManagerException e) {
13029            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13030        }
13031
13032        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13033    }
13034
13035    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13036        // Can't rotate keys during boot or if sharedUser.
13037        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13038                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13039            return false;
13040        }
13041        // app is using upgradeKeySets; make sure all are valid
13042        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13043        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13044        for (int i = 0; i < upgradeKeySets.length; i++) {
13045            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13046                Slog.wtf(TAG, "Package "
13047                         + (oldPs.name != null ? oldPs.name : "<null>")
13048                         + " contains upgrade-key-set reference to unknown key-set: "
13049                         + upgradeKeySets[i]
13050                         + " reverting to signatures check.");
13051                return false;
13052            }
13053        }
13054        return true;
13055    }
13056
13057    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13058        // Upgrade keysets are being used.  Determine if new package has a superset of the
13059        // required keys.
13060        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13061        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13062        for (int i = 0; i < upgradeKeySets.length; i++) {
13063            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13064            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13065                return true;
13066            }
13067        }
13068        return false;
13069    }
13070
13071    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13072            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13073        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13074
13075        final PackageParser.Package oldPackage;
13076        final String pkgName = pkg.packageName;
13077        final int[] allUsers;
13078
13079        // First find the old package info and check signatures
13080        synchronized(mPackages) {
13081            oldPackage = mPackages.get(pkgName);
13082            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13083            if (isEphemeral && !oldIsEphemeral) {
13084                // can't downgrade from full to ephemeral
13085                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13086                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13087                return;
13088            }
13089            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13090            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13091            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13092                if (!checkUpgradeKeySetLP(ps, pkg)) {
13093                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13094                            "New package not signed by keys specified by upgrade-keysets: "
13095                                    + pkgName);
13096                    return;
13097                }
13098            } else {
13099                // default to original signature matching
13100                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13101                        != PackageManager.SIGNATURE_MATCH) {
13102                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13103                            "New package has a different signature: " + pkgName);
13104                    return;
13105                }
13106            }
13107
13108            // In case of rollback, remember per-user/profile install state
13109            allUsers = sUserManager.getUserIds();
13110        }
13111
13112        // Update what is removed
13113        res.removedInfo = new PackageRemovedInfo();
13114        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13115        res.removedInfo.removedPackage = oldPackage.packageName;
13116        res.removedInfo.isUpdate = true;
13117        final int childCount = (oldPackage.childPackages != null)
13118                ? oldPackage.childPackages.size() : 0;
13119        for (int i = 0; i < childCount; i++) {
13120            boolean childPackageUpdated = false;
13121            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13122            if (res.addedChildPackages != null) {
13123                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13124                if (childRes != null) {
13125                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13126                    childRes.removedInfo.removedPackage = childPkg.packageName;
13127                    childRes.removedInfo.isUpdate = true;
13128                    childPackageUpdated = true;
13129                }
13130            }
13131            if (!childPackageUpdated) {
13132                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13133                childRemovedRes.removedPackage = childPkg.packageName;
13134                childRemovedRes.isUpdate = false;
13135                childRemovedRes.dataRemoved = true;
13136                synchronized (mPackages) {
13137                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13138                    if (childPs != null) {
13139                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13140                    }
13141                }
13142                if (res.removedInfo.removedChildPackages == null) {
13143                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13144                }
13145                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13146            }
13147        }
13148
13149        boolean sysPkg = (isSystemApp(oldPackage));
13150        if (sysPkg) {
13151            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13152                    user, allUsers, installerPackageName, res);
13153        } else {
13154            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13155                    user, allUsers, installerPackageName, res);
13156        }
13157    }
13158
13159    public List<String> getPreviousCodePaths(String packageName) {
13160        final PackageSetting ps = mSettings.mPackages.get(packageName);
13161        final List<String> result = new ArrayList<String>();
13162        if (ps != null && ps.oldCodePaths != null) {
13163            result.addAll(ps.oldCodePaths);
13164        }
13165        return result;
13166    }
13167
13168    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13169            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13170            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13171        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13172                + deletedPackage);
13173
13174        String pkgName = deletedPackage.packageName;
13175        boolean deletedPkg = true;
13176        boolean addedPkg = false;
13177        boolean updatedSettings = false;
13178        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13179        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13180                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13181
13182        final long origUpdateTime = (pkg.mExtras != null)
13183                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13184
13185        // First delete the existing package while retaining the data directory
13186        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13187                res.removedInfo, true, pkg)) {
13188            // If the existing package wasn't successfully deleted
13189            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13190            deletedPkg = false;
13191        } else {
13192            // Successfully deleted the old package; proceed with replace.
13193
13194            // If deleted package lived in a container, give users a chance to
13195            // relinquish resources before killing.
13196            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13197                if (DEBUG_INSTALL) {
13198                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13199                }
13200                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13201                final ArrayList<String> pkgList = new ArrayList<String>(1);
13202                pkgList.add(deletedPackage.applicationInfo.packageName);
13203                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13204            }
13205
13206            deleteCodeCacheDirsLI(pkg);
13207
13208            try {
13209                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13210                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13211                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13212
13213                // Update the in-memory copy of the previous code paths.
13214                PackageSetting ps = mSettings.mPackages.get(pkgName);
13215                if (!killApp) {
13216                    if (ps.oldCodePaths == null) {
13217                        ps.oldCodePaths = new ArraySet<>();
13218                    }
13219                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13220                    if (deletedPackage.splitCodePaths != null) {
13221                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13222                    }
13223                } else {
13224                    ps.oldCodePaths = null;
13225                }
13226                if (ps.childPackageNames != null) {
13227                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13228                        final String childPkgName = ps.childPackageNames.get(i);
13229                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13230                        childPs.oldCodePaths = ps.oldCodePaths;
13231                    }
13232                }
13233                prepareAppDataAfterInstall(newPackage);
13234                addedPkg = true;
13235            } catch (PackageManagerException e) {
13236                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13237            }
13238        }
13239
13240        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13241            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13242
13243            // Revert all internal state mutations and added folders for the failed install
13244            if (addedPkg) {
13245                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13246                        res.removedInfo, true, null);
13247            }
13248
13249            // Restore the old package
13250            if (deletedPkg) {
13251                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13252                File restoreFile = new File(deletedPackage.codePath);
13253                // Parse old package
13254                boolean oldExternal = isExternal(deletedPackage);
13255                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13256                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13257                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13258                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13259                try {
13260                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13261                            null);
13262                } catch (PackageManagerException e) {
13263                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13264                            + e.getMessage());
13265                    return;
13266                }
13267
13268                synchronized (mPackages) {
13269                    // Ensure the installer package name up to date
13270                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13271
13272                    // Update permissions for restored package
13273                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13274
13275                    mSettings.writeLPr();
13276                }
13277
13278                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13279            }
13280        } else {
13281            synchronized (mPackages) {
13282                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13283                if (ps != null) {
13284                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13285                    if (res.removedInfo.removedChildPackages != null) {
13286                        final int childCount = res.removedInfo.removedChildPackages.size();
13287                        // Iterate in reverse as we may modify the collection
13288                        for (int i = childCount - 1; i >= 0; i--) {
13289                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13290                            if (res.addedChildPackages.containsKey(childPackageName)) {
13291                                res.removedInfo.removedChildPackages.removeAt(i);
13292                            } else {
13293                                PackageRemovedInfo childInfo = res.removedInfo
13294                                        .removedChildPackages.valueAt(i);
13295                                childInfo.removedForAllUsers = mPackages.get(
13296                                        childInfo.removedPackage) == null;
13297                            }
13298                        }
13299                    }
13300                }
13301            }
13302        }
13303    }
13304
13305    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13306            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13307            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13308        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13309                + ", old=" + deletedPackage);
13310
13311        final boolean disabledSystem;
13312
13313        // Set the system/privileged flags as needed
13314        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13315        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13316                != 0) {
13317            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13318        }
13319
13320        // Kill package processes including services, providers, etc.
13321        killPackage(deletedPackage, "replace sys pkg");
13322
13323        // Remove existing system package
13324        removePackageLI(deletedPackage, true);
13325
13326        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13327        if (!disabledSystem) {
13328            // We didn't need to disable the .apk as a current system package,
13329            // which means we are replacing another update that is already
13330            // installed.  We need to make sure to delete the older one's .apk.
13331            res.removedInfo.args = createInstallArgsForExisting(0,
13332                    deletedPackage.applicationInfo.getCodePath(),
13333                    deletedPackage.applicationInfo.getResourcePath(),
13334                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13335        } else {
13336            res.removedInfo.args = null;
13337        }
13338
13339        // Successfully disabled the old package. Now proceed with re-installation
13340        deleteCodeCacheDirsLI(pkg);
13341
13342        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13343        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13344                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13345
13346        PackageParser.Package newPackage = null;
13347        try {
13348            // Add the package to the internal data structures
13349            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13350
13351            // Set the update and install times
13352            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13353            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13354                    System.currentTimeMillis());
13355
13356            // Check for shared user id changes
13357            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13358                    deletedPackage, newPackage);
13359            if (invalidPackageName != null) {
13360                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13361                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13362                                + " to " + invalidPackageName);
13363            }
13364
13365            // Update the package dynamic state if succeeded
13366            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13367                // Now that the install succeeded make sure we remove data
13368                // directories for any child package the update removed.
13369                final int deletedChildCount = (deletedPackage.childPackages != null)
13370                        ? deletedPackage.childPackages.size() : 0;
13371                final int newChildCount = (newPackage.childPackages != null)
13372                        ? newPackage.childPackages.size() : 0;
13373                for (int i = 0; i < deletedChildCount; i++) {
13374                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13375                    boolean childPackageDeleted = true;
13376                    for (int j = 0; j < newChildCount; j++) {
13377                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13378                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13379                            childPackageDeleted = false;
13380                            break;
13381                        }
13382                    }
13383                    if (childPackageDeleted) {
13384                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13385                                deletedChildPkg.packageName);
13386                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13387                            PackageRemovedInfo removedChildRes = res.removedInfo
13388                                    .removedChildPackages.get(deletedChildPkg.packageName);
13389                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13390                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13391                        }
13392                    }
13393                }
13394
13395                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13396                prepareAppDataAfterInstall(newPackage);
13397            }
13398        } catch (PackageManagerException e) {
13399            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13400            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13401        }
13402
13403        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13404            // Re installation failed. Restore old information
13405            // Remove new pkg information
13406            if (newPackage != null) {
13407                removeInstalledPackageLI(newPackage, true);
13408            }
13409            // Add back the old system package
13410            try {
13411                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13412            } catch (PackageManagerException e) {
13413                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13414            }
13415
13416            synchronized (mPackages) {
13417                if (disabledSystem) {
13418                    enableSystemPackageLPw(deletedPackage);
13419                }
13420
13421                // Ensure the installer package name up to date
13422                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13423
13424                // Update permissions for restored package
13425                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13426
13427                mSettings.writeLPr();
13428            }
13429
13430            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13431                    + " after failed upgrade");
13432        }
13433    }
13434
13435    /**
13436     * Checks whether the parent or any of the child packages have a change shared
13437     * user. For a package to be a valid update the shred users of the parent and
13438     * the children should match. We may later support changing child shared users.
13439     * @param oldPkg The updated package.
13440     * @param newPkg The update package.
13441     * @return The shared user that change between the versions.
13442     */
13443    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13444            PackageParser.Package newPkg) {
13445        // Check parent shared user
13446        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13447            return newPkg.packageName;
13448        }
13449        // Check child shared users
13450        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13451        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13452        for (int i = 0; i < newChildCount; i++) {
13453            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13454            // If this child was present, did it have the same shared user?
13455            for (int j = 0; j < oldChildCount; j++) {
13456                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13457                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13458                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13459                    return newChildPkg.packageName;
13460                }
13461            }
13462        }
13463        return null;
13464    }
13465
13466    private void removeNativeBinariesLI(PackageSetting ps) {
13467        // Remove the lib path for the parent package
13468        if (ps != null) {
13469            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13470            // Remove the lib path for the child packages
13471            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13472            for (int i = 0; i < childCount; i++) {
13473                PackageSetting childPs = null;
13474                synchronized (mPackages) {
13475                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13476                }
13477                if (childPs != null) {
13478                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13479                            .legacyNativeLibraryPathString);
13480                }
13481            }
13482        }
13483    }
13484
13485    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13486        // Enable the parent package
13487        mSettings.enableSystemPackageLPw(pkg.packageName);
13488        // Enable the child packages
13489        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13490        for (int i = 0; i < childCount; i++) {
13491            PackageParser.Package childPkg = pkg.childPackages.get(i);
13492            mSettings.enableSystemPackageLPw(childPkg.packageName);
13493        }
13494    }
13495
13496    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13497            PackageParser.Package newPkg) {
13498        // Disable the parent package (parent always replaced)
13499        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13500        // Disable the child packages
13501        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13502        for (int i = 0; i < childCount; i++) {
13503            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13504            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13505            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13506        }
13507        return disabled;
13508    }
13509
13510    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13511            String installerPackageName) {
13512        // Enable the parent package
13513        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13514        // Enable the child packages
13515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13516        for (int i = 0; i < childCount; i++) {
13517            PackageParser.Package childPkg = pkg.childPackages.get(i);
13518            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13519        }
13520    }
13521
13522    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13523        // Collect all used permissions in the UID
13524        ArraySet<String> usedPermissions = new ArraySet<>();
13525        final int packageCount = su.packages.size();
13526        for (int i = 0; i < packageCount; i++) {
13527            PackageSetting ps = su.packages.valueAt(i);
13528            if (ps.pkg == null) {
13529                continue;
13530            }
13531            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13532            for (int j = 0; j < requestedPermCount; j++) {
13533                String permission = ps.pkg.requestedPermissions.get(j);
13534                BasePermission bp = mSettings.mPermissions.get(permission);
13535                if (bp != null) {
13536                    usedPermissions.add(permission);
13537                }
13538            }
13539        }
13540
13541        PermissionsState permissionsState = su.getPermissionsState();
13542        // Prune install permissions
13543        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13544        final int installPermCount = installPermStates.size();
13545        for (int i = installPermCount - 1; i >= 0;  i--) {
13546            PermissionState permissionState = installPermStates.get(i);
13547            if (!usedPermissions.contains(permissionState.getName())) {
13548                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13549                if (bp != null) {
13550                    permissionsState.revokeInstallPermission(bp);
13551                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13552                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13553                }
13554            }
13555        }
13556
13557        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13558
13559        // Prune runtime permissions
13560        for (int userId : allUserIds) {
13561            List<PermissionState> runtimePermStates = permissionsState
13562                    .getRuntimePermissionStates(userId);
13563            final int runtimePermCount = runtimePermStates.size();
13564            for (int i = runtimePermCount - 1; i >= 0; i--) {
13565                PermissionState permissionState = runtimePermStates.get(i);
13566                if (!usedPermissions.contains(permissionState.getName())) {
13567                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13568                    if (bp != null) {
13569                        permissionsState.revokeRuntimePermission(bp, userId);
13570                        permissionsState.updatePermissionFlags(bp, userId,
13571                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13572                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13573                                runtimePermissionChangedUserIds, userId);
13574                    }
13575                }
13576            }
13577        }
13578
13579        return runtimePermissionChangedUserIds;
13580    }
13581
13582    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13583            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13584        // Update the parent package setting
13585        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13586                res, user);
13587        // Update the child packages setting
13588        final int childCount = (newPackage.childPackages != null)
13589                ? newPackage.childPackages.size() : 0;
13590        for (int i = 0; i < childCount; i++) {
13591            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13592            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13593            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13594                    childRes.origUsers, childRes, user);
13595        }
13596    }
13597
13598    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13599            String installerPackageName, int[] allUsers, int[] installedForUsers,
13600            PackageInstalledInfo res, UserHandle user) {
13601        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13602
13603        String pkgName = newPackage.packageName;
13604        synchronized (mPackages) {
13605            //write settings. the installStatus will be incomplete at this stage.
13606            //note that the new package setting would have already been
13607            //added to mPackages. It hasn't been persisted yet.
13608            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13609            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13610            mSettings.writeLPr();
13611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13612        }
13613
13614        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13615        synchronized (mPackages) {
13616            updatePermissionsLPw(newPackage.packageName, newPackage,
13617                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13618                            ? UPDATE_PERMISSIONS_ALL : 0));
13619            // For system-bundled packages, we assume that installing an upgraded version
13620            // of the package implies that the user actually wants to run that new code,
13621            // so we enable the package.
13622            PackageSetting ps = mSettings.mPackages.get(pkgName);
13623            final int userId = user.getIdentifier();
13624            if (ps != null) {
13625                if (isSystemApp(newPackage)) {
13626                    if (DEBUG_INSTALL) {
13627                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13628                    }
13629                    // Enable system package for requested users
13630                    if (res.origUsers != null) {
13631                        for (int origUserId : res.origUsers) {
13632                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13633                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13634                                        origUserId, installerPackageName);
13635                            }
13636                        }
13637                    }
13638                    // Also convey the prior install/uninstall state
13639                    if (allUsers != null && installedForUsers != null) {
13640                        for (int currentUserId : allUsers) {
13641                            final boolean installed = ArrayUtils.contains(
13642                                    installedForUsers, currentUserId);
13643                            if (DEBUG_INSTALL) {
13644                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13645                            }
13646                            ps.setInstalled(installed, currentUserId);
13647                        }
13648                        // these install state changes will be persisted in the
13649                        // upcoming call to mSettings.writeLPr().
13650                    }
13651                }
13652                // It's implied that when a user requests installation, they want the app to be
13653                // installed and enabled.
13654                if (userId != UserHandle.USER_ALL) {
13655                    ps.setInstalled(true, userId);
13656                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13657                }
13658            }
13659            res.name = pkgName;
13660            res.uid = newPackage.applicationInfo.uid;
13661            res.pkg = newPackage;
13662            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13663            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13664            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13665            //to update install status
13666            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13667            mSettings.writeLPr();
13668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13669        }
13670
13671        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13672    }
13673
13674    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13675        try {
13676            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13677            installPackageLI(args, res);
13678        } finally {
13679            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13680        }
13681    }
13682
13683    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13684        final int installFlags = args.installFlags;
13685        final String installerPackageName = args.installerPackageName;
13686        final String volumeUuid = args.volumeUuid;
13687        final File tmpPackageFile = new File(args.getCodePath());
13688        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13689        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13690                || (args.volumeUuid != null));
13691        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13692        boolean replace = false;
13693        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13694        if (args.move != null) {
13695            // moving a complete application; perform an initial scan on the new install location
13696            scanFlags |= SCAN_INITIAL;
13697        }
13698        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13699            scanFlags |= SCAN_DONT_KILL_APP;
13700        }
13701
13702        // Result object to be returned
13703        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13704
13705        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13706
13707        // Sanity check
13708        if (ephemeral && (forwardLocked || onExternal)) {
13709            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13710                    + " external=" + onExternal);
13711            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13712            return;
13713        }
13714
13715        // Retrieve PackageSettings and parse package
13716        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13717                | PackageParser.PARSE_ENFORCE_CODE
13718                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13719                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13720                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13721        PackageParser pp = new PackageParser();
13722        pp.setSeparateProcesses(mSeparateProcesses);
13723        pp.setDisplayMetrics(mMetrics);
13724
13725        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13726        final PackageParser.Package pkg;
13727        try {
13728            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13729        } catch (PackageParserException e) {
13730            res.setError("Failed parse during installPackageLI", e);
13731            return;
13732        } finally {
13733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13734        }
13735
13736        // If we are installing a clustered package add results for the children
13737        if (pkg.childPackages != null) {
13738            synchronized (mPackages) {
13739                final int childCount = pkg.childPackages.size();
13740                for (int i = 0; i < childCount; i++) {
13741                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13742                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13743                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13744                    childRes.pkg = childPkg;
13745                    childRes.name = childPkg.packageName;
13746                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13747                    if (childPs != null) {
13748                        childRes.origUsers = childPs.queryInstalledUsers(
13749                                sUserManager.getUserIds(), true);
13750                    }
13751                    if ((mPackages.containsKey(childPkg.packageName))) {
13752                        childRes.removedInfo = new PackageRemovedInfo();
13753                        childRes.removedInfo.removedPackage = childPkg.packageName;
13754                    }
13755                    if (res.addedChildPackages == null) {
13756                        res.addedChildPackages = new ArrayMap<>();
13757                    }
13758                    res.addedChildPackages.put(childPkg.packageName, childRes);
13759                }
13760            }
13761        }
13762
13763        // If package doesn't declare API override, mark that we have an install
13764        // time CPU ABI override.
13765        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13766            pkg.cpuAbiOverride = args.abiOverride;
13767        }
13768
13769        String pkgName = res.name = pkg.packageName;
13770        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13771            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13772                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13773                return;
13774            }
13775        }
13776
13777        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13778        try {
13779            PackageParser.collectCertificates(pkg, parseFlags);
13780        } catch (PackageParserException e) {
13781            res.setError("Failed collect during installPackageLI", e);
13782            return;
13783        } finally {
13784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13785        }
13786
13787        // Get rid of all references to package scan path via parser.
13788        pp = null;
13789        String oldCodePath = null;
13790        boolean systemApp = false;
13791        synchronized (mPackages) {
13792            // Check if installing already existing package
13793            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13794                String oldName = mSettings.mRenamedPackages.get(pkgName);
13795                if (pkg.mOriginalPackages != null
13796                        && pkg.mOriginalPackages.contains(oldName)
13797                        && mPackages.containsKey(oldName)) {
13798                    // This package is derived from an original package,
13799                    // and this device has been updating from that original
13800                    // name.  We must continue using the original name, so
13801                    // rename the new package here.
13802                    pkg.setPackageName(oldName);
13803                    pkgName = pkg.packageName;
13804                    replace = true;
13805                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13806                            + oldName + " pkgName=" + pkgName);
13807                } else if (mPackages.containsKey(pkgName)) {
13808                    // This package, under its official name, already exists
13809                    // on the device; we should replace it.
13810                    replace = true;
13811                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13812                }
13813
13814                // Child packages are installed through the parent package
13815                if (pkg.parentPackage != null) {
13816                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13817                            "Package " + pkg.packageName + " is child of package "
13818                                    + pkg.parentPackage.parentPackage + ". Child packages "
13819                                    + "can be updated only through the parent package.");
13820                    return;
13821                }
13822
13823                if (replace) {
13824                    // Prevent apps opting out from runtime permissions
13825                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13826                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13827                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13828                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13829                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13830                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13831                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13832                                        + " doesn't support runtime permissions but the old"
13833                                        + " target SDK " + oldTargetSdk + " does.");
13834                        return;
13835                    }
13836
13837                    // Prevent installing of child packages
13838                    if (oldPackage.parentPackage != null) {
13839                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13840                                "Package " + pkg.packageName + " is child of package "
13841                                        + oldPackage.parentPackage + ". Child packages "
13842                                        + "can be updated only through the parent package.");
13843                        return;
13844                    }
13845                }
13846            }
13847
13848            PackageSetting ps = mSettings.mPackages.get(pkgName);
13849            if (ps != null) {
13850                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13851
13852                // Quick sanity check that we're signed correctly if updating;
13853                // we'll check this again later when scanning, but we want to
13854                // bail early here before tripping over redefined permissions.
13855                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13856                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13857                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13858                                + pkg.packageName + " upgrade keys do not match the "
13859                                + "previously installed version");
13860                        return;
13861                    }
13862                } else {
13863                    try {
13864                        verifySignaturesLP(ps, pkg);
13865                    } catch (PackageManagerException e) {
13866                        res.setError(e.error, e.getMessage());
13867                        return;
13868                    }
13869                }
13870
13871                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13872                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13873                    systemApp = (ps.pkg.applicationInfo.flags &
13874                            ApplicationInfo.FLAG_SYSTEM) != 0;
13875                }
13876                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13877            }
13878
13879            // Check whether the newly-scanned package wants to define an already-defined perm
13880            int N = pkg.permissions.size();
13881            for (int i = N-1; i >= 0; i--) {
13882                PackageParser.Permission perm = pkg.permissions.get(i);
13883                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13884                if (bp != null) {
13885                    // If the defining package is signed with our cert, it's okay.  This
13886                    // also includes the "updating the same package" case, of course.
13887                    // "updating same package" could also involve key-rotation.
13888                    final boolean sigsOk;
13889                    if (bp.sourcePackage.equals(pkg.packageName)
13890                            && (bp.packageSetting instanceof PackageSetting)
13891                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13892                                    scanFlags))) {
13893                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13894                    } else {
13895                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13896                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13897                    }
13898                    if (!sigsOk) {
13899                        // If the owning package is the system itself, we log but allow
13900                        // install to proceed; we fail the install on all other permission
13901                        // redefinitions.
13902                        if (!bp.sourcePackage.equals("android")) {
13903                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13904                                    + pkg.packageName + " attempting to redeclare permission "
13905                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13906                            res.origPermission = perm.info.name;
13907                            res.origPackage = bp.sourcePackage;
13908                            return;
13909                        } else {
13910                            Slog.w(TAG, "Package " + pkg.packageName
13911                                    + " attempting to redeclare system permission "
13912                                    + perm.info.name + "; ignoring new declaration");
13913                            pkg.permissions.remove(i);
13914                        }
13915                    }
13916                }
13917            }
13918        }
13919
13920        if (systemApp) {
13921            if (onExternal) {
13922                // Abort update; system app can't be replaced with app on sdcard
13923                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13924                        "Cannot install updates to system apps on sdcard");
13925                return;
13926            } else if (ephemeral) {
13927                // Abort update; system app can't be replaced with an ephemeral app
13928                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13929                        "Cannot update a system app with an ephemeral app");
13930                return;
13931            }
13932        }
13933
13934        if (args.move != null) {
13935            // We did an in-place move, so dex is ready to roll
13936            scanFlags |= SCAN_NO_DEX;
13937            scanFlags |= SCAN_MOVE;
13938
13939            synchronized (mPackages) {
13940                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13941                if (ps == null) {
13942                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13943                            "Missing settings for moved package " + pkgName);
13944                }
13945
13946                // We moved the entire application as-is, so bring over the
13947                // previously derived ABI information.
13948                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13949                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13950            }
13951
13952        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13953            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13954            scanFlags |= SCAN_NO_DEX;
13955
13956            try {
13957                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13958                    args.abiOverride : pkg.cpuAbiOverride);
13959                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13960                        true /* extract libs */);
13961            } catch (PackageManagerException pme) {
13962                Slog.e(TAG, "Error deriving application ABI", pme);
13963                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13964                return;
13965            }
13966
13967
13968            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13969            // Do not run PackageDexOptimizer through the local performDexOpt
13970            // method because `pkg` is not in `mPackages` yet.
13971            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13972                    false /* useProfiles */, true /* extractOnly */);
13973            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13974            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13975                String msg = "Extracking package failed for " + pkgName;
13976                res.setError(INSTALL_FAILED_DEXOPT, msg);
13977                return;
13978            }
13979        }
13980
13981        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13982            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13983            return;
13984        }
13985
13986        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13987
13988        if (replace) {
13989            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13990                    installerPackageName, res);
13991        } else {
13992            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13993                    args.user, installerPackageName, volumeUuid, res);
13994        }
13995        synchronized (mPackages) {
13996            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13997            if (ps != null) {
13998                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13999            }
14000
14001            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14002            for (int i = 0; i < childCount; i++) {
14003                PackageParser.Package childPkg = pkg.childPackages.get(i);
14004                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14005                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14006                if (childPs != null) {
14007                    childRes.newUsers = childPs.queryInstalledUsers(
14008                            sUserManager.getUserIds(), true);
14009                }
14010            }
14011        }
14012    }
14013
14014    private void startIntentFilterVerifications(int userId, boolean replacing,
14015            PackageParser.Package pkg) {
14016        if (mIntentFilterVerifierComponent == null) {
14017            Slog.w(TAG, "No IntentFilter verification will not be done as "
14018                    + "there is no IntentFilterVerifier available!");
14019            return;
14020        }
14021
14022        final int verifierUid = getPackageUid(
14023                mIntentFilterVerifierComponent.getPackageName(),
14024                MATCH_DEBUG_TRIAGED_MISSING,
14025                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14026
14027        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14028        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14029        mHandler.sendMessage(msg);
14030
14031        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14032        for (int i = 0; i < childCount; i++) {
14033            PackageParser.Package childPkg = pkg.childPackages.get(i);
14034            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14035            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14036            mHandler.sendMessage(msg);
14037        }
14038    }
14039
14040    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14041            PackageParser.Package pkg) {
14042        int size = pkg.activities.size();
14043        if (size == 0) {
14044            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14045                    "No activity, so no need to verify any IntentFilter!");
14046            return;
14047        }
14048
14049        final boolean hasDomainURLs = hasDomainURLs(pkg);
14050        if (!hasDomainURLs) {
14051            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14052                    "No domain URLs, so no need to verify any IntentFilter!");
14053            return;
14054        }
14055
14056        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14057                + " if any IntentFilter from the " + size
14058                + " Activities needs verification ...");
14059
14060        int count = 0;
14061        final String packageName = pkg.packageName;
14062
14063        synchronized (mPackages) {
14064            // If this is a new install and we see that we've already run verification for this
14065            // package, we have nothing to do: it means the state was restored from backup.
14066            if (!replacing) {
14067                IntentFilterVerificationInfo ivi =
14068                        mSettings.getIntentFilterVerificationLPr(packageName);
14069                if (ivi != null) {
14070                    if (DEBUG_DOMAIN_VERIFICATION) {
14071                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14072                                + ivi.getStatusString());
14073                    }
14074                    return;
14075                }
14076            }
14077
14078            // If any filters need to be verified, then all need to be.
14079            boolean needToVerify = false;
14080            for (PackageParser.Activity a : pkg.activities) {
14081                for (ActivityIntentInfo filter : a.intents) {
14082                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14083                        if (DEBUG_DOMAIN_VERIFICATION) {
14084                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14085                        }
14086                        needToVerify = true;
14087                        break;
14088                    }
14089                }
14090            }
14091
14092            if (needToVerify) {
14093                final int verificationId = mIntentFilterVerificationToken++;
14094                for (PackageParser.Activity a : pkg.activities) {
14095                    for (ActivityIntentInfo filter : a.intents) {
14096                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14097                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14098                                    "Verification needed for IntentFilter:" + filter.toString());
14099                            mIntentFilterVerifier.addOneIntentFilterVerification(
14100                                    verifierUid, userId, verificationId, filter, packageName);
14101                            count++;
14102                        }
14103                    }
14104                }
14105            }
14106        }
14107
14108        if (count > 0) {
14109            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14110                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14111                    +  " for userId:" + userId);
14112            mIntentFilterVerifier.startVerifications(userId);
14113        } else {
14114            if (DEBUG_DOMAIN_VERIFICATION) {
14115                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14116            }
14117        }
14118    }
14119
14120    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14121        final ComponentName cn  = filter.activity.getComponentName();
14122        final String packageName = cn.getPackageName();
14123
14124        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14125                packageName);
14126        if (ivi == null) {
14127            return true;
14128        }
14129        int status = ivi.getStatus();
14130        switch (status) {
14131            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14132            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14133                return true;
14134
14135            default:
14136                // Nothing to do
14137                return false;
14138        }
14139    }
14140
14141    private static boolean isMultiArch(ApplicationInfo info) {
14142        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14143    }
14144
14145    private static boolean isExternal(PackageParser.Package pkg) {
14146        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14147    }
14148
14149    private static boolean isExternal(PackageSetting ps) {
14150        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14151    }
14152
14153    private static boolean isEphemeral(PackageParser.Package pkg) {
14154        return pkg.applicationInfo.isEphemeralApp();
14155    }
14156
14157    private static boolean isEphemeral(PackageSetting ps) {
14158        return ps.pkg != null && isEphemeral(ps.pkg);
14159    }
14160
14161    private static boolean isSystemApp(PackageParser.Package pkg) {
14162        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14163    }
14164
14165    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14166        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14167    }
14168
14169    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14170        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14171    }
14172
14173    private static boolean isSystemApp(PackageSetting ps) {
14174        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14175    }
14176
14177    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14178        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14179    }
14180
14181    private int packageFlagsToInstallFlags(PackageSetting ps) {
14182        int installFlags = 0;
14183        if (isEphemeral(ps)) {
14184            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14185        }
14186        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14187            // This existing package was an external ASEC install when we have
14188            // the external flag without a UUID
14189            installFlags |= PackageManager.INSTALL_EXTERNAL;
14190        }
14191        if (ps.isForwardLocked()) {
14192            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14193        }
14194        return installFlags;
14195    }
14196
14197    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14198        if (isExternal(pkg)) {
14199            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14200                return StorageManager.UUID_PRIMARY_PHYSICAL;
14201            } else {
14202                return pkg.volumeUuid;
14203            }
14204        } else {
14205            return StorageManager.UUID_PRIVATE_INTERNAL;
14206        }
14207    }
14208
14209    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14210        if (isExternal(pkg)) {
14211            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14212                return mSettings.getExternalVersion();
14213            } else {
14214                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14215            }
14216        } else {
14217            return mSettings.getInternalVersion();
14218        }
14219    }
14220
14221    private void deleteTempPackageFiles() {
14222        final FilenameFilter filter = new FilenameFilter() {
14223            public boolean accept(File dir, String name) {
14224                return name.startsWith("vmdl") && name.endsWith(".tmp");
14225            }
14226        };
14227        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14228            file.delete();
14229        }
14230    }
14231
14232    @Override
14233    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14234            int flags) {
14235        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14236                flags);
14237    }
14238
14239    @Override
14240    public void deletePackage(final String packageName,
14241            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14242        mContext.enforceCallingOrSelfPermission(
14243                android.Manifest.permission.DELETE_PACKAGES, null);
14244        Preconditions.checkNotNull(packageName);
14245        Preconditions.checkNotNull(observer);
14246        final int uid = Binder.getCallingUid();
14247        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14248        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14249        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14250            mContext.enforceCallingOrSelfPermission(
14251                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14252                    "deletePackage for user " + userId);
14253        }
14254
14255        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14256            try {
14257                observer.onPackageDeleted(packageName,
14258                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14259            } catch (RemoteException re) {
14260            }
14261            return;
14262        }
14263
14264        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14265            try {
14266                observer.onPackageDeleted(packageName,
14267                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14268            } catch (RemoteException re) {
14269            }
14270            return;
14271        }
14272
14273        if (DEBUG_REMOVE) {
14274            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14275                    + " deleteAllUsers: " + deleteAllUsers );
14276        }
14277        // Queue up an async operation since the package deletion may take a little while.
14278        mHandler.post(new Runnable() {
14279            public void run() {
14280                mHandler.removeCallbacks(this);
14281                int returnCode;
14282                if (!deleteAllUsers) {
14283                    returnCode = deletePackageX(packageName, userId, flags);
14284                } else {
14285                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14286                    // If nobody is blocking uninstall, proceed with delete for all users
14287                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14288                        returnCode = deletePackageX(packageName, userId, flags);
14289                    } else {
14290                        // Otherwise uninstall individually for users with blockUninstalls=false
14291                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14292                        for (int userId : users) {
14293                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14294                                returnCode = deletePackageX(packageName, userId, userFlags);
14295                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14296                                    Slog.w(TAG, "Package delete failed for user " + userId
14297                                            + ", returnCode " + returnCode);
14298                                }
14299                            }
14300                        }
14301                        // The app has only been marked uninstalled for certain users.
14302                        // We still need to report that delete was blocked
14303                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14304                    }
14305                }
14306                try {
14307                    observer.onPackageDeleted(packageName, returnCode, null);
14308                } catch (RemoteException e) {
14309                    Log.i(TAG, "Observer no longer exists.");
14310                } //end catch
14311            } //end run
14312        });
14313    }
14314
14315    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14316        int[] result = EMPTY_INT_ARRAY;
14317        for (int userId : userIds) {
14318            if (getBlockUninstallForUser(packageName, userId)) {
14319                result = ArrayUtils.appendInt(result, userId);
14320            }
14321        }
14322        return result;
14323    }
14324
14325    @Override
14326    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14327        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14328    }
14329
14330    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14331        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14332                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14333        try {
14334            if (dpm != null) {
14335                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14336                        /* callingUserOnly =*/ false);
14337                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14338                        : deviceOwnerComponentName.getPackageName();
14339                // Does the package contains the device owner?
14340                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14341                // this check is probably not needed, since DO should be registered as a device
14342                // admin on some user too. (Original bug for this: b/17657954)
14343                if (packageName.equals(deviceOwnerPackageName)) {
14344                    return true;
14345                }
14346                // Does it contain a device admin for any user?
14347                int[] users;
14348                if (userId == UserHandle.USER_ALL) {
14349                    users = sUserManager.getUserIds();
14350                } else {
14351                    users = new int[]{userId};
14352                }
14353                for (int i = 0; i < users.length; ++i) {
14354                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14355                        return true;
14356                    }
14357                }
14358            }
14359        } catch (RemoteException e) {
14360        }
14361        return false;
14362    }
14363
14364    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14365        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14366    }
14367
14368    /**
14369     *  This method is an internal method that could be get invoked either
14370     *  to delete an installed package or to clean up a failed installation.
14371     *  After deleting an installed package, a broadcast is sent to notify any
14372     *  listeners that the package has been installed. For cleaning up a failed
14373     *  installation, the broadcast is not necessary since the package's
14374     *  installation wouldn't have sent the initial broadcast either
14375     *  The key steps in deleting a package are
14376     *  deleting the package information in internal structures like mPackages,
14377     *  deleting the packages base directories through installd
14378     *  updating mSettings to reflect current status
14379     *  persisting settings for later use
14380     *  sending a broadcast if necessary
14381     */
14382    private int deletePackageX(String packageName, int userId, int flags) {
14383        final PackageRemovedInfo info = new PackageRemovedInfo();
14384        final boolean res;
14385
14386        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14387                ? UserHandle.ALL : new UserHandle(userId);
14388
14389        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14390            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14391            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14392        }
14393
14394        PackageSetting uninstalledPs = null;
14395
14396        // for the uninstall-updates case and restricted profiles, remember the per-
14397        // user handle installed state
14398        int[] allUsers;
14399        synchronized (mPackages) {
14400            uninstalledPs = mSettings.mPackages.get(packageName);
14401            if (uninstalledPs == null) {
14402                Slog.w(TAG, "Not removing non-existent package " + packageName);
14403                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14404            }
14405            allUsers = sUserManager.getUserIds();
14406            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14407        }
14408
14409        synchronized (mInstallLock) {
14410            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14411            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14412                    flags | REMOVE_CHATTY, info, true, null);
14413            synchronized (mPackages) {
14414                if (res) {
14415                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14416                }
14417            }
14418        }
14419
14420        if (res) {
14421            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14422            info.sendPackageRemovedBroadcasts(killApp);
14423            info.sendSystemPackageUpdatedBroadcasts();
14424            info.sendSystemPackageAppearedBroadcasts();
14425        }
14426        // Force a gc here.
14427        Runtime.getRuntime().gc();
14428        // Delete the resources here after sending the broadcast to let
14429        // other processes clean up before deleting resources.
14430        if (info.args != null) {
14431            synchronized (mInstallLock) {
14432                info.args.doPostDeleteLI(true);
14433            }
14434        }
14435
14436        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14437    }
14438
14439    class PackageRemovedInfo {
14440        String removedPackage;
14441        int uid = -1;
14442        int removedAppId = -1;
14443        int[] origUsers;
14444        int[] removedUsers = null;
14445        boolean isRemovedPackageSystemUpdate = false;
14446        boolean isUpdate;
14447        boolean dataRemoved;
14448        boolean removedForAllUsers;
14449        // Clean up resources deleted packages.
14450        InstallArgs args = null;
14451        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14452        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14453
14454        void sendPackageRemovedBroadcasts(boolean killApp) {
14455            sendPackageRemovedBroadcastInternal(killApp);
14456            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14457            for (int i = 0; i < childCount; i++) {
14458                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14459                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14460            }
14461        }
14462
14463        void sendSystemPackageUpdatedBroadcasts() {
14464            if (isRemovedPackageSystemUpdate) {
14465                sendSystemPackageUpdatedBroadcastsInternal();
14466                final int childCount = (removedChildPackages != null)
14467                        ? removedChildPackages.size() : 0;
14468                for (int i = 0; i < childCount; i++) {
14469                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14470                    if (childInfo.isRemovedPackageSystemUpdate) {
14471                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14472                    }
14473                }
14474            }
14475        }
14476
14477        void sendSystemPackageAppearedBroadcasts() {
14478            final int packageCount = (appearedChildPackages != null)
14479                    ? appearedChildPackages.size() : 0;
14480            for (int i = 0; i < packageCount; i++) {
14481                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14482                for (int userId : installedInfo.newUsers) {
14483                    sendPackageAddedForUser(installedInfo.name, true,
14484                            UserHandle.getAppId(installedInfo.uid), userId);
14485                }
14486            }
14487        }
14488
14489        private void sendSystemPackageUpdatedBroadcastsInternal() {
14490            Bundle extras = new Bundle(2);
14491            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14492            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14493            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14494                    extras, 0, null, null, null);
14495            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14496                    extras, 0, null, null, null);
14497            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14498                    null, 0, removedPackage, null, null);
14499        }
14500
14501        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14502            Bundle extras = new Bundle(2);
14503            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14504            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14505            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14506            if (isUpdate || isRemovedPackageSystemUpdate) {
14507                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14508            }
14509            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14510            if (removedPackage != null) {
14511                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14512                        extras, 0, null, null, removedUsers);
14513                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14514                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14515                            removedPackage, extras, 0, null, null, removedUsers);
14516                }
14517            }
14518            if (removedAppId >= 0) {
14519                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14520                        removedUsers);
14521            }
14522        }
14523    }
14524
14525    /*
14526     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14527     * flag is not set, the data directory is removed as well.
14528     * make sure this flag is set for partially installed apps. If not its meaningless to
14529     * delete a partially installed application.
14530     */
14531    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14532            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14533        String packageName = ps.name;
14534        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14535        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14536        // Retrieve object to delete permissions for shared user later on
14537        final PackageSetting deletedPs;
14538        // reader
14539        synchronized (mPackages) {
14540            deletedPs = mSettings.mPackages.get(packageName);
14541            if (outInfo != null) {
14542                outInfo.removedPackage = packageName;
14543                outInfo.removedUsers = deletedPs != null
14544                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14545                        : null;
14546            }
14547        }
14548        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14549            removeDataDirsLI(ps.volumeUuid, packageName);
14550            if (outInfo != null) {
14551                outInfo.dataRemoved = true;
14552            }
14553            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14554        }
14555        // writer
14556        synchronized (mPackages) {
14557            if (deletedPs != null) {
14558                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14559                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14560                    clearDefaultBrowserIfNeeded(packageName);
14561                    if (outInfo != null) {
14562                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14563                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14564                    }
14565                    updatePermissionsLPw(deletedPs.name, null, 0);
14566                    if (deletedPs.sharedUser != null) {
14567                        // Remove permissions associated with package. Since runtime
14568                        // permissions are per user we have to kill the removed package
14569                        // or packages running under the shared user of the removed
14570                        // package if revoking the permissions requested only by the removed
14571                        // package is successful and this causes a change in gids.
14572                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14573                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14574                                    userId);
14575                            if (userIdToKill == UserHandle.USER_ALL
14576                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14577                                // If gids changed for this user, kill all affected packages.
14578                                mHandler.post(new Runnable() {
14579                                    @Override
14580                                    public void run() {
14581                                        // This has to happen with no lock held.
14582                                        killApplication(deletedPs.name, deletedPs.appId,
14583                                                KILL_APP_REASON_GIDS_CHANGED);
14584                                    }
14585                                });
14586                                break;
14587                            }
14588                        }
14589                    }
14590                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14591                }
14592                // make sure to preserve per-user disabled state if this removal was just
14593                // a downgrade of a system app to the factory package
14594                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14595                    if (DEBUG_REMOVE) {
14596                        Slog.d(TAG, "Propagating install state across downgrade");
14597                    }
14598                    for (int userId : allUserHandles) {
14599                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14600                        if (DEBUG_REMOVE) {
14601                            Slog.d(TAG, "    user " + userId + " => " + installed);
14602                        }
14603                        ps.setInstalled(installed, userId);
14604                    }
14605                }
14606            }
14607            // can downgrade to reader
14608            if (writeSettings) {
14609                // Save settings now
14610                mSettings.writeLPr();
14611            }
14612        }
14613        if (outInfo != null) {
14614            // A user ID was deleted here. Go through all users and remove it
14615            // from KeyStore.
14616            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14617        }
14618    }
14619
14620    static boolean locationIsPrivileged(File path) {
14621        try {
14622            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14623                    .getCanonicalPath();
14624            return path.getCanonicalPath().startsWith(privilegedAppDir);
14625        } catch (IOException e) {
14626            Slog.e(TAG, "Unable to access code path " + path);
14627        }
14628        return false;
14629    }
14630
14631    /*
14632     * Tries to delete system package.
14633     */
14634    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14635            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14636            boolean writeSettings) {
14637        if (deletedPs.parentPackageName != null) {
14638            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14639            return false;
14640        }
14641
14642        final boolean applyUserRestrictions
14643                = (allUserHandles != null) && (outInfo.origUsers != null);
14644        final PackageSetting disabledPs;
14645        // Confirm if the system package has been updated
14646        // An updated system app can be deleted. This will also have to restore
14647        // the system pkg from system partition
14648        // reader
14649        synchronized (mPackages) {
14650            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14651        }
14652
14653        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14654                + " disabledPs=" + disabledPs);
14655
14656        if (disabledPs == null) {
14657            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14658            return false;
14659        } else if (DEBUG_REMOVE) {
14660            Slog.d(TAG, "Deleting system pkg from data partition");
14661        }
14662
14663        if (DEBUG_REMOVE) {
14664            if (applyUserRestrictions) {
14665                Slog.d(TAG, "Remembering install states:");
14666                for (int userId : allUserHandles) {
14667                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14668                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14669                }
14670            }
14671        }
14672
14673        // Delete the updated package
14674        outInfo.isRemovedPackageSystemUpdate = true;
14675        if (outInfo.removedChildPackages != null) {
14676            final int childCount = (deletedPs.childPackageNames != null)
14677                    ? deletedPs.childPackageNames.size() : 0;
14678            for (int i = 0; i < childCount; i++) {
14679                String childPackageName = deletedPs.childPackageNames.get(i);
14680                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14681                        .contains(childPackageName)) {
14682                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14683                            childPackageName);
14684                    if (childInfo != null) {
14685                        childInfo.isRemovedPackageSystemUpdate = true;
14686                    }
14687                }
14688            }
14689        }
14690
14691        if (disabledPs.versionCode < deletedPs.versionCode) {
14692            // Delete data for downgrades
14693            flags &= ~PackageManager.DELETE_KEEP_DATA;
14694        } else {
14695            // Preserve data by setting flag
14696            flags |= PackageManager.DELETE_KEEP_DATA;
14697        }
14698
14699        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14700                outInfo, writeSettings, disabledPs.pkg);
14701        if (!ret) {
14702            return false;
14703        }
14704
14705        // writer
14706        synchronized (mPackages) {
14707            // Reinstate the old system package
14708            enableSystemPackageLPw(disabledPs.pkg);
14709            // Remove any native libraries from the upgraded package.
14710            removeNativeBinariesLI(deletedPs);
14711        }
14712
14713        // Install the system package
14714        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14715        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14716        if (locationIsPrivileged(disabledPs.codePath)) {
14717            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14718        }
14719
14720        final PackageParser.Package newPkg;
14721        try {
14722            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14723        } catch (PackageManagerException e) {
14724            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14725                    + e.getMessage());
14726            return false;
14727        }
14728
14729        prepareAppDataAfterInstall(newPkg);
14730
14731        // writer
14732        synchronized (mPackages) {
14733            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14734
14735            // Propagate the permissions state as we do not want to drop on the floor
14736            // runtime permissions. The update permissions method below will take
14737            // care of removing obsolete permissions and grant install permissions.
14738            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14739            updatePermissionsLPw(newPkg.packageName, newPkg,
14740                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14741
14742            if (applyUserRestrictions) {
14743                if (DEBUG_REMOVE) {
14744                    Slog.d(TAG, "Propagating install state across reinstall");
14745                }
14746                for (int userId : allUserHandles) {
14747                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14748                    if (DEBUG_REMOVE) {
14749                        Slog.d(TAG, "    user " + userId + " => " + installed);
14750                    }
14751                    ps.setInstalled(installed, userId);
14752
14753                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14754                }
14755                // Regardless of writeSettings we need to ensure that this restriction
14756                // state propagation is persisted
14757                mSettings.writeAllUsersPackageRestrictionsLPr();
14758            }
14759            // can downgrade to reader here
14760            if (writeSettings) {
14761                mSettings.writeLPr();
14762            }
14763        }
14764        return true;
14765    }
14766
14767    private boolean deleteInstalledPackageLI(PackageSetting ps,
14768            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14769            PackageRemovedInfo outInfo, boolean writeSettings,
14770            PackageParser.Package replacingPackage) {
14771        synchronized (mPackages) {
14772            if (outInfo != null) {
14773                outInfo.uid = ps.appId;
14774            }
14775
14776            if (outInfo != null && outInfo.removedChildPackages != null) {
14777                final int childCount = (ps.childPackageNames != null)
14778                        ? ps.childPackageNames.size() : 0;
14779                for (int i = 0; i < childCount; i++) {
14780                    String childPackageName = ps.childPackageNames.get(i);
14781                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14782                    if (childPs == null) {
14783                        return false;
14784                    }
14785                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14786                            childPackageName);
14787                    if (childInfo != null) {
14788                        childInfo.uid = childPs.appId;
14789                    }
14790                }
14791            }
14792        }
14793
14794        // Delete package data from internal structures and also remove data if flag is set
14795        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14796
14797        // Delete the child packages data
14798        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14799        for (int i = 0; i < childCount; i++) {
14800            PackageSetting childPs;
14801            synchronized (mPackages) {
14802                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14803            }
14804            if (childPs != null) {
14805                PackageRemovedInfo childOutInfo = (outInfo != null
14806                        && outInfo.removedChildPackages != null)
14807                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14808                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14809                        && (replacingPackage != null
14810                        && !replacingPackage.hasChildPackage(childPs.name))
14811                        ? flags & ~DELETE_KEEP_DATA : flags;
14812                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14813                        deleteFlags, writeSettings);
14814            }
14815        }
14816
14817        // Delete application code and resources only for parent packages
14818        if (ps.parentPackageName == null) {
14819            if (deleteCodeAndResources && (outInfo != null)) {
14820                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14821                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14822                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14823            }
14824        }
14825
14826        return true;
14827    }
14828
14829    @Override
14830    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14831            int userId) {
14832        mContext.enforceCallingOrSelfPermission(
14833                android.Manifest.permission.DELETE_PACKAGES, null);
14834        synchronized (mPackages) {
14835            PackageSetting ps = mSettings.mPackages.get(packageName);
14836            if (ps == null) {
14837                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14838                return false;
14839            }
14840            if (!ps.getInstalled(userId)) {
14841                // Can't block uninstall for an app that is not installed or enabled.
14842                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14843                return false;
14844            }
14845            ps.setBlockUninstall(blockUninstall, userId);
14846            mSettings.writePackageRestrictionsLPr(userId);
14847        }
14848        return true;
14849    }
14850
14851    @Override
14852    public boolean getBlockUninstallForUser(String packageName, int userId) {
14853        synchronized (mPackages) {
14854            PackageSetting ps = mSettings.mPackages.get(packageName);
14855            if (ps == null) {
14856                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14857                return false;
14858            }
14859            return ps.getBlockUninstall(userId);
14860        }
14861    }
14862
14863    @Override
14864    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14865        int callingUid = Binder.getCallingUid();
14866        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14867            throw new SecurityException(
14868                    "setRequiredForSystemUser can only be run by the system or root");
14869        }
14870        synchronized (mPackages) {
14871            PackageSetting ps = mSettings.mPackages.get(packageName);
14872            if (ps == null) {
14873                Log.w(TAG, "Package doesn't exist: " + packageName);
14874                return false;
14875            }
14876            if (systemUserApp) {
14877                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14878            } else {
14879                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14880            }
14881            mSettings.writeLPr();
14882        }
14883        return true;
14884    }
14885
14886    /*
14887     * This method handles package deletion in general
14888     */
14889    private boolean deletePackageLI(String packageName, UserHandle user,
14890            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14891            PackageRemovedInfo outInfo, boolean writeSettings,
14892            PackageParser.Package replacingPackage) {
14893        if (packageName == null) {
14894            Slog.w(TAG, "Attempt to delete null packageName.");
14895            return false;
14896        }
14897
14898        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14899
14900        PackageSetting ps;
14901
14902        synchronized (mPackages) {
14903            ps = mSettings.mPackages.get(packageName);
14904            if (ps == null) {
14905                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14906                return false;
14907            }
14908
14909            if (ps.parentPackageName != null && (!isSystemApp(ps)
14910                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14911                if (DEBUG_REMOVE) {
14912                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14913                            + ((user == null) ? UserHandle.USER_ALL : user));
14914                }
14915                final int removedUserId = (user != null) ? user.getIdentifier()
14916                        : UserHandle.USER_ALL;
14917                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14918                    return false;
14919                }
14920                markPackageUninstalledForUserLPw(ps, user);
14921                scheduleWritePackageRestrictionsLocked(user);
14922                return true;
14923            }
14924        }
14925
14926        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14927                && user.getIdentifier() != UserHandle.USER_ALL)) {
14928            // The caller is asking that the package only be deleted for a single
14929            // user.  To do this, we just mark its uninstalled state and delete
14930            // its data. If this is a system app, we only allow this to happen if
14931            // they have set the special DELETE_SYSTEM_APP which requests different
14932            // semantics than normal for uninstalling system apps.
14933            markPackageUninstalledForUserLPw(ps, user);
14934
14935            if (!isSystemApp(ps)) {
14936                // Do not uninstall the APK if an app should be cached
14937                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14938                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14939                    // Other user still have this package installed, so all
14940                    // we need to do is clear this user's data and save that
14941                    // it is uninstalled.
14942                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14943                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14944                        return false;
14945                    }
14946                    scheduleWritePackageRestrictionsLocked(user);
14947                    return true;
14948                } else {
14949                    // We need to set it back to 'installed' so the uninstall
14950                    // broadcasts will be sent correctly.
14951                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14952                    ps.setInstalled(true, user.getIdentifier());
14953                }
14954            } else {
14955                // This is a system app, so we assume that the
14956                // other users still have this package installed, so all
14957                // we need to do is clear this user's data and save that
14958                // it is uninstalled.
14959                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14960                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14961                    return false;
14962                }
14963                scheduleWritePackageRestrictionsLocked(user);
14964                return true;
14965            }
14966        }
14967
14968        // If we are deleting a composite package for all users, keep track
14969        // of result for each child.
14970        if (ps.childPackageNames != null && outInfo != null) {
14971            synchronized (mPackages) {
14972                final int childCount = ps.childPackageNames.size();
14973                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14974                for (int i = 0; i < childCount; i++) {
14975                    String childPackageName = ps.childPackageNames.get(i);
14976                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14977                    childInfo.removedPackage = childPackageName;
14978                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14979                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14980                    if (childPs != null) {
14981                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14982                    }
14983                }
14984            }
14985        }
14986
14987        boolean ret = false;
14988        if (isSystemApp(ps)) {
14989            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14990            // When an updated system application is deleted we delete the existing resources
14991            // as well and fall back to existing code in system partition
14992            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14993        } else {
14994            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14995            // Kill application pre-emptively especially for apps on sd.
14996            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
14997            if (killApp) {
14998                killApplication(packageName, ps.appId, "uninstall pkg");
14999            }
15000            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15001                    outInfo, writeSettings, replacingPackage);
15002        }
15003
15004        // Take a note whether we deleted the package for all users
15005        if (outInfo != null) {
15006            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15007            if (outInfo.removedChildPackages != null) {
15008                synchronized (mPackages) {
15009                    final int childCount = outInfo.removedChildPackages.size();
15010                    for (int i = 0; i < childCount; i++) {
15011                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15012                        if (childInfo != null) {
15013                            childInfo.removedForAllUsers = mPackages.get(
15014                                    childInfo.removedPackage) == null;
15015                        }
15016                    }
15017                }
15018            }
15019            // If we uninstalled an update to a system app there may be some
15020            // child packages that appeared as they are declared in the system
15021            // app but were not declared in the update.
15022            if (isSystemApp(ps)) {
15023                synchronized (mPackages) {
15024                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15025                    final int childCount = (updatedPs.childPackageNames != null)
15026                            ? updatedPs.childPackageNames.size() : 0;
15027                    for (int i = 0; i < childCount; i++) {
15028                        String childPackageName = updatedPs.childPackageNames.get(i);
15029                        if (outInfo.removedChildPackages == null
15030                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15031                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15032                            if (childPs == null) {
15033                                continue;
15034                            }
15035                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15036                            installRes.name = childPackageName;
15037                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15038                            installRes.pkg = mPackages.get(childPackageName);
15039                            installRes.uid = childPs.pkg.applicationInfo.uid;
15040                            if (outInfo.appearedChildPackages == null) {
15041                                outInfo.appearedChildPackages = new ArrayMap<>();
15042                            }
15043                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15044                        }
15045                    }
15046                }
15047            }
15048        }
15049
15050        return ret;
15051    }
15052
15053    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15054        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15055                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15056        for (int nextUserId : userIds) {
15057            if (DEBUG_REMOVE) {
15058                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15059            }
15060            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15061                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15062                    false /*hidden*/, false /*suspended*/, null, null, null,
15063                    false /*blockUninstall*/,
15064                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15065        }
15066    }
15067
15068    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15069            PackageRemovedInfo outInfo) {
15070        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15071                : new int[] {userId};
15072        for (int nextUserId : userIds) {
15073            if (DEBUG_REMOVE) {
15074                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15075                        + nextUserId);
15076            }
15077            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15078            try {
15079                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15080            } catch (InstallerException e) {
15081                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15082                return false;
15083            }
15084            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15085            schedulePackageCleaning(ps.name, nextUserId, false);
15086            synchronized (mPackages) {
15087                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15088                    scheduleWritePackageRestrictionsLocked(nextUserId);
15089                }
15090                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15091            }
15092        }
15093
15094        if (outInfo != null) {
15095            outInfo.removedPackage = ps.name;
15096            outInfo.removedAppId = ps.appId;
15097            outInfo.removedUsers = userIds;
15098        }
15099
15100        return true;
15101    }
15102
15103    private final class ClearStorageConnection implements ServiceConnection {
15104        IMediaContainerService mContainerService;
15105
15106        @Override
15107        public void onServiceConnected(ComponentName name, IBinder service) {
15108            synchronized (this) {
15109                mContainerService = IMediaContainerService.Stub.asInterface(service);
15110                notifyAll();
15111            }
15112        }
15113
15114        @Override
15115        public void onServiceDisconnected(ComponentName name) {
15116        }
15117    }
15118
15119    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15120        final boolean mounted;
15121        if (Environment.isExternalStorageEmulated()) {
15122            mounted = true;
15123        } else {
15124            final String status = Environment.getExternalStorageState();
15125
15126            mounted = status.equals(Environment.MEDIA_MOUNTED)
15127                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15128        }
15129
15130        if (!mounted) {
15131            return;
15132        }
15133
15134        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15135        int[] users;
15136        if (userId == UserHandle.USER_ALL) {
15137            users = sUserManager.getUserIds();
15138        } else {
15139            users = new int[] { userId };
15140        }
15141        final ClearStorageConnection conn = new ClearStorageConnection();
15142        if (mContext.bindServiceAsUser(
15143                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15144            try {
15145                for (int curUser : users) {
15146                    long timeout = SystemClock.uptimeMillis() + 5000;
15147                    synchronized (conn) {
15148                        long now = SystemClock.uptimeMillis();
15149                        while (conn.mContainerService == null && now < timeout) {
15150                            try {
15151                                conn.wait(timeout - now);
15152                            } catch (InterruptedException e) {
15153                            }
15154                        }
15155                    }
15156                    if (conn.mContainerService == null) {
15157                        return;
15158                    }
15159
15160                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15161                    clearDirectory(conn.mContainerService,
15162                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15163                    if (allData) {
15164                        clearDirectory(conn.mContainerService,
15165                                userEnv.buildExternalStorageAppDataDirs(packageName));
15166                        clearDirectory(conn.mContainerService,
15167                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15168                    }
15169                }
15170            } finally {
15171                mContext.unbindService(conn);
15172            }
15173        }
15174    }
15175
15176    @Override
15177    public void clearApplicationProfileData(String packageName) {
15178        enforceSystemOrRoot("Only the system can clear all profile data");
15179        try {
15180            mInstaller.rmProfiles(packageName);
15181        } catch (InstallerException ex) {
15182            Log.e(TAG, "Could not clear profile data of package " + packageName);
15183        }
15184    }
15185
15186    @Override
15187    public void clearApplicationUserData(final String packageName,
15188            final IPackageDataObserver observer, final int userId) {
15189        mContext.enforceCallingOrSelfPermission(
15190                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15191
15192        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15193                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15194
15195        final DevicePolicyManagerInternal dpmi = LocalServices
15196                .getService(DevicePolicyManagerInternal.class);
15197        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15198            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15199        }
15200        // Queue up an async operation since the package deletion may take a little while.
15201        mHandler.post(new Runnable() {
15202            public void run() {
15203                mHandler.removeCallbacks(this);
15204                final boolean succeeded;
15205                synchronized (mInstallLock) {
15206                    succeeded = clearApplicationUserDataLI(packageName, userId);
15207                }
15208                clearExternalStorageDataSync(packageName, userId, true);
15209                if (succeeded) {
15210                    // invoke DeviceStorageMonitor's update method to clear any notifications
15211                    DeviceStorageMonitorInternal dsm = LocalServices
15212                            .getService(DeviceStorageMonitorInternal.class);
15213                    if (dsm != null) {
15214                        dsm.checkMemory();
15215                    }
15216                }
15217                if(observer != null) {
15218                    try {
15219                        observer.onRemoveCompleted(packageName, succeeded);
15220                    } catch (RemoteException e) {
15221                        Log.i(TAG, "Observer no longer exists.");
15222                    }
15223                } //end if observer
15224            } //end run
15225        });
15226    }
15227
15228    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15229        if (packageName == null) {
15230            Slog.w(TAG, "Attempt to delete null packageName.");
15231            return false;
15232        }
15233
15234        // Try finding details about the requested package
15235        PackageParser.Package pkg;
15236        synchronized (mPackages) {
15237            pkg = mPackages.get(packageName);
15238            if (pkg == null) {
15239                final PackageSetting ps = mSettings.mPackages.get(packageName);
15240                if (ps != null) {
15241                    pkg = ps.pkg;
15242                }
15243            }
15244
15245            if (pkg == null) {
15246                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15247                return false;
15248            }
15249
15250            PackageSetting ps = (PackageSetting) pkg.mExtras;
15251            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15252        }
15253
15254        // Always delete data directories for package, even if we found no other
15255        // record of app. This helps users recover from UID mismatches without
15256        // resorting to a full data wipe.
15257        // TODO: triage flags as part of 26466827
15258        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15259        try {
15260            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15261        } catch (InstallerException e) {
15262            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15263            return false;
15264        }
15265
15266        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15267        removeKeystoreDataIfNeeded(userId, appId);
15268
15269        // Create a native library symlink only if we have native libraries
15270        // and if the native libraries are 32 bit libraries. We do not provide
15271        // this symlink for 64 bit libraries.
15272        if (pkg.applicationInfo.primaryCpuAbi != null &&
15273                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15274            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15275            try {
15276                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15277                        nativeLibPath, userId);
15278            } catch (InstallerException e) {
15279                Slog.w(TAG, "Failed linking native library dir", e);
15280                return false;
15281            }
15282        }
15283
15284        return true;
15285    }
15286
15287    /**
15288     * Reverts user permission state changes (permissions and flags) in
15289     * all packages for a given user.
15290     *
15291     * @param userId The device user for which to do a reset.
15292     */
15293    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15294        final int packageCount = mPackages.size();
15295        for (int i = 0; i < packageCount; i++) {
15296            PackageParser.Package pkg = mPackages.valueAt(i);
15297            PackageSetting ps = (PackageSetting) pkg.mExtras;
15298            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15299        }
15300    }
15301
15302    /**
15303     * Reverts user permission state changes (permissions and flags).
15304     *
15305     * @param ps The package for which to reset.
15306     * @param userId The device user for which to do a reset.
15307     */
15308    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15309            final PackageSetting ps, final int userId) {
15310        if (ps.pkg == null) {
15311            return;
15312        }
15313
15314        // These are flags that can change base on user actions.
15315        final int userSettableMask = FLAG_PERMISSION_USER_SET
15316                | FLAG_PERMISSION_USER_FIXED
15317                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15318                | FLAG_PERMISSION_REVIEW_REQUIRED;
15319
15320        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15321                | FLAG_PERMISSION_POLICY_FIXED;
15322
15323        boolean writeInstallPermissions = false;
15324        boolean writeRuntimePermissions = false;
15325
15326        final int permissionCount = ps.pkg.requestedPermissions.size();
15327        for (int i = 0; i < permissionCount; i++) {
15328            String permission = ps.pkg.requestedPermissions.get(i);
15329
15330            BasePermission bp = mSettings.mPermissions.get(permission);
15331            if (bp == null) {
15332                continue;
15333            }
15334
15335            // If shared user we just reset the state to which only this app contributed.
15336            if (ps.sharedUser != null) {
15337                boolean used = false;
15338                final int packageCount = ps.sharedUser.packages.size();
15339                for (int j = 0; j < packageCount; j++) {
15340                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15341                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15342                            && pkg.pkg.requestedPermissions.contains(permission)) {
15343                        used = true;
15344                        break;
15345                    }
15346                }
15347                if (used) {
15348                    continue;
15349                }
15350            }
15351
15352            PermissionsState permissionsState = ps.getPermissionsState();
15353
15354            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15355
15356            // Always clear the user settable flags.
15357            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15358                    bp.name) != null;
15359            // If permission review is enabled and this is a legacy app, mark the
15360            // permission as requiring a review as this is the initial state.
15361            int flags = 0;
15362            if (Build.PERMISSIONS_REVIEW_REQUIRED
15363                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15364                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15365            }
15366            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15367                if (hasInstallState) {
15368                    writeInstallPermissions = true;
15369                } else {
15370                    writeRuntimePermissions = true;
15371                }
15372            }
15373
15374            // Below is only runtime permission handling.
15375            if (!bp.isRuntime()) {
15376                continue;
15377            }
15378
15379            // Never clobber system or policy.
15380            if ((oldFlags & policyOrSystemFlags) != 0) {
15381                continue;
15382            }
15383
15384            // If this permission was granted by default, make sure it is.
15385            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15386                if (permissionsState.grantRuntimePermission(bp, userId)
15387                        != PERMISSION_OPERATION_FAILURE) {
15388                    writeRuntimePermissions = true;
15389                }
15390            // If permission review is enabled the permissions for a legacy apps
15391            // are represented as constantly granted runtime ones, so don't revoke.
15392            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15393                // Otherwise, reset the permission.
15394                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15395                switch (revokeResult) {
15396                    case PERMISSION_OPERATION_SUCCESS: {
15397                        writeRuntimePermissions = true;
15398                    } break;
15399
15400                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15401                        writeRuntimePermissions = true;
15402                        final int appId = ps.appId;
15403                        mHandler.post(new Runnable() {
15404                            @Override
15405                            public void run() {
15406                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15407                            }
15408                        });
15409                    } break;
15410                }
15411            }
15412        }
15413
15414        // Synchronously write as we are taking permissions away.
15415        if (writeRuntimePermissions) {
15416            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15417        }
15418
15419        // Synchronously write as we are taking permissions away.
15420        if (writeInstallPermissions) {
15421            mSettings.writeLPr();
15422        }
15423    }
15424
15425    /**
15426     * Remove entries from the keystore daemon. Will only remove it if the
15427     * {@code appId} is valid.
15428     */
15429    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15430        if (appId < 0) {
15431            return;
15432        }
15433
15434        final KeyStore keyStore = KeyStore.getInstance();
15435        if (keyStore != null) {
15436            if (userId == UserHandle.USER_ALL) {
15437                for (final int individual : sUserManager.getUserIds()) {
15438                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15439                }
15440            } else {
15441                keyStore.clearUid(UserHandle.getUid(userId, appId));
15442            }
15443        } else {
15444            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15445        }
15446    }
15447
15448    @Override
15449    public void deleteApplicationCacheFiles(final String packageName,
15450            final IPackageDataObserver observer) {
15451        mContext.enforceCallingOrSelfPermission(
15452                android.Manifest.permission.DELETE_CACHE_FILES, null);
15453        // Queue up an async operation since the package deletion may take a little while.
15454        final int userId = UserHandle.getCallingUserId();
15455        mHandler.post(new Runnable() {
15456            public void run() {
15457                mHandler.removeCallbacks(this);
15458                final boolean succeded;
15459                synchronized (mInstallLock) {
15460                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15461                }
15462                clearExternalStorageDataSync(packageName, userId, false);
15463                if (observer != null) {
15464                    try {
15465                        observer.onRemoveCompleted(packageName, succeded);
15466                    } catch (RemoteException e) {
15467                        Log.i(TAG, "Observer no longer exists.");
15468                    }
15469                } //end if observer
15470            } //end run
15471        });
15472    }
15473
15474    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15475        if (packageName == null) {
15476            Slog.w(TAG, "Attempt to delete null packageName.");
15477            return false;
15478        }
15479        PackageParser.Package p;
15480        synchronized (mPackages) {
15481            p = mPackages.get(packageName);
15482        }
15483        if (p == null) {
15484            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15485            return false;
15486        }
15487        final ApplicationInfo applicationInfo = p.applicationInfo;
15488        if (applicationInfo == null) {
15489            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15490            return false;
15491        }
15492        // TODO: triage flags as part of 26466827
15493        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15494        try {
15495            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15496                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15497        } catch (InstallerException e) {
15498            Slog.w(TAG, "Couldn't remove cache files for package "
15499                    + packageName + " u" + userId, e);
15500            return false;
15501        }
15502        return true;
15503    }
15504
15505    @Override
15506    public void getPackageSizeInfo(final String packageName, int userHandle,
15507            final IPackageStatsObserver observer) {
15508        mContext.enforceCallingOrSelfPermission(
15509                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15510        if (packageName == null) {
15511            throw new IllegalArgumentException("Attempt to get size of null packageName");
15512        }
15513
15514        PackageStats stats = new PackageStats(packageName, userHandle);
15515
15516        /*
15517         * Queue up an async operation since the package measurement may take a
15518         * little while.
15519         */
15520        Message msg = mHandler.obtainMessage(INIT_COPY);
15521        msg.obj = new MeasureParams(stats, observer);
15522        mHandler.sendMessage(msg);
15523    }
15524
15525    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15526            PackageStats pStats) {
15527        if (packageName == null) {
15528            Slog.w(TAG, "Attempt to get size of null packageName.");
15529            return false;
15530        }
15531        PackageParser.Package p;
15532        boolean dataOnly = false;
15533        String libDirRoot = null;
15534        String asecPath = null;
15535        PackageSetting ps = null;
15536        synchronized (mPackages) {
15537            p = mPackages.get(packageName);
15538            ps = mSettings.mPackages.get(packageName);
15539            if(p == null) {
15540                dataOnly = true;
15541                if((ps == null) || (ps.pkg == null)) {
15542                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15543                    return false;
15544                }
15545                p = ps.pkg;
15546            }
15547            if (ps != null) {
15548                libDirRoot = ps.legacyNativeLibraryPathString;
15549            }
15550            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15551                final long token = Binder.clearCallingIdentity();
15552                try {
15553                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15554                    if (secureContainerId != null) {
15555                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15556                    }
15557                } finally {
15558                    Binder.restoreCallingIdentity(token);
15559                }
15560            }
15561        }
15562        String publicSrcDir = null;
15563        if(!dataOnly) {
15564            final ApplicationInfo applicationInfo = p.applicationInfo;
15565            if (applicationInfo == null) {
15566                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15567                return false;
15568            }
15569            if (p.isForwardLocked()) {
15570                publicSrcDir = applicationInfo.getBaseResourcePath();
15571            }
15572        }
15573        // TODO: extend to measure size of split APKs
15574        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15575        // not just the first level.
15576        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15577        // just the primary.
15578        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15579
15580        String apkPath;
15581        File packageDir = new File(p.codePath);
15582
15583        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15584            apkPath = packageDir.getAbsolutePath();
15585            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15586            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15587                libDirRoot = null;
15588            }
15589        } else {
15590            apkPath = p.baseCodePath;
15591        }
15592
15593        // TODO: triage flags as part of 26466827
15594        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15595        try {
15596            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15597                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15598        } catch (InstallerException e) {
15599            return false;
15600        }
15601
15602        // Fix-up for forward-locked applications in ASEC containers.
15603        if (!isExternal(p)) {
15604            pStats.codeSize += pStats.externalCodeSize;
15605            pStats.externalCodeSize = 0L;
15606        }
15607
15608        return true;
15609    }
15610
15611    private int getUidTargetSdkVersionLockedLPr(int uid) {
15612        Object obj = mSettings.getUserIdLPr(uid);
15613        if (obj instanceof SharedUserSetting) {
15614            final SharedUserSetting sus = (SharedUserSetting) obj;
15615            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15616            final Iterator<PackageSetting> it = sus.packages.iterator();
15617            while (it.hasNext()) {
15618                final PackageSetting ps = it.next();
15619                if (ps.pkg != null) {
15620                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15621                    if (v < vers) vers = v;
15622                }
15623            }
15624            return vers;
15625        } else if (obj instanceof PackageSetting) {
15626            final PackageSetting ps = (PackageSetting) obj;
15627            if (ps.pkg != null) {
15628                return ps.pkg.applicationInfo.targetSdkVersion;
15629            }
15630        }
15631        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15632    }
15633
15634    @Override
15635    public void addPreferredActivity(IntentFilter filter, int match,
15636            ComponentName[] set, ComponentName activity, int userId) {
15637        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15638                "Adding preferred");
15639    }
15640
15641    private void addPreferredActivityInternal(IntentFilter filter, int match,
15642            ComponentName[] set, ComponentName activity, boolean always, int userId,
15643            String opname) {
15644        // writer
15645        int callingUid = Binder.getCallingUid();
15646        enforceCrossUserPermission(callingUid, userId,
15647                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15648        if (filter.countActions() == 0) {
15649            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15650            return;
15651        }
15652        synchronized (mPackages) {
15653            if (mContext.checkCallingOrSelfPermission(
15654                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15655                    != PackageManager.PERMISSION_GRANTED) {
15656                if (getUidTargetSdkVersionLockedLPr(callingUid)
15657                        < Build.VERSION_CODES.FROYO) {
15658                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15659                            + callingUid);
15660                    return;
15661                }
15662                mContext.enforceCallingOrSelfPermission(
15663                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15664            }
15665
15666            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15667            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15668                    + userId + ":");
15669            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15670            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15671            scheduleWritePackageRestrictionsLocked(userId);
15672        }
15673    }
15674
15675    @Override
15676    public void replacePreferredActivity(IntentFilter filter, int match,
15677            ComponentName[] set, ComponentName activity, int userId) {
15678        if (filter.countActions() != 1) {
15679            throw new IllegalArgumentException(
15680                    "replacePreferredActivity expects filter to have only 1 action.");
15681        }
15682        if (filter.countDataAuthorities() != 0
15683                || filter.countDataPaths() != 0
15684                || filter.countDataSchemes() > 1
15685                || filter.countDataTypes() != 0) {
15686            throw new IllegalArgumentException(
15687                    "replacePreferredActivity expects filter to have no data authorities, " +
15688                    "paths, or types; and at most one scheme.");
15689        }
15690
15691        final int callingUid = Binder.getCallingUid();
15692        enforceCrossUserPermission(callingUid, userId,
15693                true /* requireFullPermission */, false /* checkShell */,
15694                "replace preferred activity");
15695        synchronized (mPackages) {
15696            if (mContext.checkCallingOrSelfPermission(
15697                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15698                    != PackageManager.PERMISSION_GRANTED) {
15699                if (getUidTargetSdkVersionLockedLPr(callingUid)
15700                        < Build.VERSION_CODES.FROYO) {
15701                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15702                            + Binder.getCallingUid());
15703                    return;
15704                }
15705                mContext.enforceCallingOrSelfPermission(
15706                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15707            }
15708
15709            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15710            if (pir != null) {
15711                // Get all of the existing entries that exactly match this filter.
15712                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15713                if (existing != null && existing.size() == 1) {
15714                    PreferredActivity cur = existing.get(0);
15715                    if (DEBUG_PREFERRED) {
15716                        Slog.i(TAG, "Checking replace of preferred:");
15717                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15718                        if (!cur.mPref.mAlways) {
15719                            Slog.i(TAG, "  -- CUR; not mAlways!");
15720                        } else {
15721                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15722                            Slog.i(TAG, "  -- CUR: mSet="
15723                                    + Arrays.toString(cur.mPref.mSetComponents));
15724                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15725                            Slog.i(TAG, "  -- NEW: mMatch="
15726                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15727                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15728                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15729                        }
15730                    }
15731                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15732                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15733                            && cur.mPref.sameSet(set)) {
15734                        // Setting the preferred activity to what it happens to be already
15735                        if (DEBUG_PREFERRED) {
15736                            Slog.i(TAG, "Replacing with same preferred activity "
15737                                    + cur.mPref.mShortComponent + " for user "
15738                                    + userId + ":");
15739                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15740                        }
15741                        return;
15742                    }
15743                }
15744
15745                if (existing != null) {
15746                    if (DEBUG_PREFERRED) {
15747                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15748                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15749                    }
15750                    for (int i = 0; i < existing.size(); i++) {
15751                        PreferredActivity pa = existing.get(i);
15752                        if (DEBUG_PREFERRED) {
15753                            Slog.i(TAG, "Removing existing preferred activity "
15754                                    + pa.mPref.mComponent + ":");
15755                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15756                        }
15757                        pir.removeFilter(pa);
15758                    }
15759                }
15760            }
15761            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15762                    "Replacing preferred");
15763        }
15764    }
15765
15766    @Override
15767    public void clearPackagePreferredActivities(String packageName) {
15768        final int uid = Binder.getCallingUid();
15769        // writer
15770        synchronized (mPackages) {
15771            PackageParser.Package pkg = mPackages.get(packageName);
15772            if (pkg == null || pkg.applicationInfo.uid != uid) {
15773                if (mContext.checkCallingOrSelfPermission(
15774                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15775                        != PackageManager.PERMISSION_GRANTED) {
15776                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15777                            < Build.VERSION_CODES.FROYO) {
15778                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15779                                + Binder.getCallingUid());
15780                        return;
15781                    }
15782                    mContext.enforceCallingOrSelfPermission(
15783                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15784                }
15785            }
15786
15787            int user = UserHandle.getCallingUserId();
15788            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15789                scheduleWritePackageRestrictionsLocked(user);
15790            }
15791        }
15792    }
15793
15794    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15795    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15796        ArrayList<PreferredActivity> removed = null;
15797        boolean changed = false;
15798        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15799            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15800            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15801            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15802                continue;
15803            }
15804            Iterator<PreferredActivity> it = pir.filterIterator();
15805            while (it.hasNext()) {
15806                PreferredActivity pa = it.next();
15807                // Mark entry for removal only if it matches the package name
15808                // and the entry is of type "always".
15809                if (packageName == null ||
15810                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15811                                && pa.mPref.mAlways)) {
15812                    if (removed == null) {
15813                        removed = new ArrayList<PreferredActivity>();
15814                    }
15815                    removed.add(pa);
15816                }
15817            }
15818            if (removed != null) {
15819                for (int j=0; j<removed.size(); j++) {
15820                    PreferredActivity pa = removed.get(j);
15821                    pir.removeFilter(pa);
15822                }
15823                changed = true;
15824            }
15825        }
15826        return changed;
15827    }
15828
15829    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15830    private void clearIntentFilterVerificationsLPw(int userId) {
15831        final int packageCount = mPackages.size();
15832        for (int i = 0; i < packageCount; i++) {
15833            PackageParser.Package pkg = mPackages.valueAt(i);
15834            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15835        }
15836    }
15837
15838    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15839    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15840        if (userId == UserHandle.USER_ALL) {
15841            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15842                    sUserManager.getUserIds())) {
15843                for (int oneUserId : sUserManager.getUserIds()) {
15844                    scheduleWritePackageRestrictionsLocked(oneUserId);
15845                }
15846            }
15847        } else {
15848            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15849                scheduleWritePackageRestrictionsLocked(userId);
15850            }
15851        }
15852    }
15853
15854    void clearDefaultBrowserIfNeeded(String packageName) {
15855        for (int oneUserId : sUserManager.getUserIds()) {
15856            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15857            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15858            if (packageName.equals(defaultBrowserPackageName)) {
15859                setDefaultBrowserPackageName(null, oneUserId);
15860            }
15861        }
15862    }
15863
15864    @Override
15865    public void resetApplicationPreferences(int userId) {
15866        mContext.enforceCallingOrSelfPermission(
15867                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15868        // writer
15869        synchronized (mPackages) {
15870            final long identity = Binder.clearCallingIdentity();
15871            try {
15872                clearPackagePreferredActivitiesLPw(null, userId);
15873                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15874                // TODO: We have to reset the default SMS and Phone. This requires
15875                // significant refactoring to keep all default apps in the package
15876                // manager (cleaner but more work) or have the services provide
15877                // callbacks to the package manager to request a default app reset.
15878                applyFactoryDefaultBrowserLPw(userId);
15879                clearIntentFilterVerificationsLPw(userId);
15880                primeDomainVerificationsLPw(userId);
15881                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15882                scheduleWritePackageRestrictionsLocked(userId);
15883            } finally {
15884                Binder.restoreCallingIdentity(identity);
15885            }
15886        }
15887    }
15888
15889    @Override
15890    public int getPreferredActivities(List<IntentFilter> outFilters,
15891            List<ComponentName> outActivities, String packageName) {
15892
15893        int num = 0;
15894        final int userId = UserHandle.getCallingUserId();
15895        // reader
15896        synchronized (mPackages) {
15897            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15898            if (pir != null) {
15899                final Iterator<PreferredActivity> it = pir.filterIterator();
15900                while (it.hasNext()) {
15901                    final PreferredActivity pa = it.next();
15902                    if (packageName == null
15903                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15904                                    && pa.mPref.mAlways)) {
15905                        if (outFilters != null) {
15906                            outFilters.add(new IntentFilter(pa));
15907                        }
15908                        if (outActivities != null) {
15909                            outActivities.add(pa.mPref.mComponent);
15910                        }
15911                    }
15912                }
15913            }
15914        }
15915
15916        return num;
15917    }
15918
15919    @Override
15920    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15921            int userId) {
15922        int callingUid = Binder.getCallingUid();
15923        if (callingUid != Process.SYSTEM_UID) {
15924            throw new SecurityException(
15925                    "addPersistentPreferredActivity can only be run by the system");
15926        }
15927        if (filter.countActions() == 0) {
15928            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15929            return;
15930        }
15931        synchronized (mPackages) {
15932            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15933                    ":");
15934            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15935            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15936                    new PersistentPreferredActivity(filter, activity));
15937            scheduleWritePackageRestrictionsLocked(userId);
15938        }
15939    }
15940
15941    @Override
15942    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15943        int callingUid = Binder.getCallingUid();
15944        if (callingUid != Process.SYSTEM_UID) {
15945            throw new SecurityException(
15946                    "clearPackagePersistentPreferredActivities can only be run by the system");
15947        }
15948        ArrayList<PersistentPreferredActivity> removed = null;
15949        boolean changed = false;
15950        synchronized (mPackages) {
15951            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15952                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15953                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15954                        .valueAt(i);
15955                if (userId != thisUserId) {
15956                    continue;
15957                }
15958                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15959                while (it.hasNext()) {
15960                    PersistentPreferredActivity ppa = it.next();
15961                    // Mark entry for removal only if it matches the package name.
15962                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15963                        if (removed == null) {
15964                            removed = new ArrayList<PersistentPreferredActivity>();
15965                        }
15966                        removed.add(ppa);
15967                    }
15968                }
15969                if (removed != null) {
15970                    for (int j=0; j<removed.size(); j++) {
15971                        PersistentPreferredActivity ppa = removed.get(j);
15972                        ppir.removeFilter(ppa);
15973                    }
15974                    changed = true;
15975                }
15976            }
15977
15978            if (changed) {
15979                scheduleWritePackageRestrictionsLocked(userId);
15980            }
15981        }
15982    }
15983
15984    /**
15985     * Common machinery for picking apart a restored XML blob and passing
15986     * it to a caller-supplied functor to be applied to the running system.
15987     */
15988    private void restoreFromXml(XmlPullParser parser, int userId,
15989            String expectedStartTag, BlobXmlRestorer functor)
15990            throws IOException, XmlPullParserException {
15991        int type;
15992        while ((type = parser.next()) != XmlPullParser.START_TAG
15993                && type != XmlPullParser.END_DOCUMENT) {
15994        }
15995        if (type != XmlPullParser.START_TAG) {
15996            // oops didn't find a start tag?!
15997            if (DEBUG_BACKUP) {
15998                Slog.e(TAG, "Didn't find start tag during restore");
15999            }
16000            return;
16001        }
16002Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16003        // this is supposed to be TAG_PREFERRED_BACKUP
16004        if (!expectedStartTag.equals(parser.getName())) {
16005            if (DEBUG_BACKUP) {
16006                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16007            }
16008            return;
16009        }
16010
16011        // skip interfering stuff, then we're aligned with the backing implementation
16012        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16013Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16014        functor.apply(parser, userId);
16015    }
16016
16017    private interface BlobXmlRestorer {
16018        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16019    }
16020
16021    /**
16022     * Non-Binder method, support for the backup/restore mechanism: write the
16023     * full set of preferred activities in its canonical XML format.  Returns the
16024     * XML output as a byte array, or null if there is none.
16025     */
16026    @Override
16027    public byte[] getPreferredActivityBackup(int userId) {
16028        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16029            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16030        }
16031
16032        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16033        try {
16034            final XmlSerializer serializer = new FastXmlSerializer();
16035            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16036            serializer.startDocument(null, true);
16037            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16038
16039            synchronized (mPackages) {
16040                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16041            }
16042
16043            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16044            serializer.endDocument();
16045            serializer.flush();
16046        } catch (Exception e) {
16047            if (DEBUG_BACKUP) {
16048                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16049            }
16050            return null;
16051        }
16052
16053        return dataStream.toByteArray();
16054    }
16055
16056    @Override
16057    public void restorePreferredActivities(byte[] backup, int userId) {
16058        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16059            throw new SecurityException("Only the system may call restorePreferredActivities()");
16060        }
16061
16062        try {
16063            final XmlPullParser parser = Xml.newPullParser();
16064            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16065            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16066                    new BlobXmlRestorer() {
16067                        @Override
16068                        public void apply(XmlPullParser parser, int userId)
16069                                throws XmlPullParserException, IOException {
16070                            synchronized (mPackages) {
16071                                mSettings.readPreferredActivitiesLPw(parser, userId);
16072                            }
16073                        }
16074                    } );
16075        } catch (Exception e) {
16076            if (DEBUG_BACKUP) {
16077                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16078            }
16079        }
16080    }
16081
16082    /**
16083     * Non-Binder method, support for the backup/restore mechanism: write the
16084     * default browser (etc) settings in its canonical XML format.  Returns the default
16085     * browser XML representation as a byte array, or null if there is none.
16086     */
16087    @Override
16088    public byte[] getDefaultAppsBackup(int userId) {
16089        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16090            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16091        }
16092
16093        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16094        try {
16095            final XmlSerializer serializer = new FastXmlSerializer();
16096            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16097            serializer.startDocument(null, true);
16098            serializer.startTag(null, TAG_DEFAULT_APPS);
16099
16100            synchronized (mPackages) {
16101                mSettings.writeDefaultAppsLPr(serializer, userId);
16102            }
16103
16104            serializer.endTag(null, TAG_DEFAULT_APPS);
16105            serializer.endDocument();
16106            serializer.flush();
16107        } catch (Exception e) {
16108            if (DEBUG_BACKUP) {
16109                Slog.e(TAG, "Unable to write default apps for backup", e);
16110            }
16111            return null;
16112        }
16113
16114        return dataStream.toByteArray();
16115    }
16116
16117    @Override
16118    public void restoreDefaultApps(byte[] backup, int userId) {
16119        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16120            throw new SecurityException("Only the system may call restoreDefaultApps()");
16121        }
16122
16123        try {
16124            final XmlPullParser parser = Xml.newPullParser();
16125            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16126            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16127                    new BlobXmlRestorer() {
16128                        @Override
16129                        public void apply(XmlPullParser parser, int userId)
16130                                throws XmlPullParserException, IOException {
16131                            synchronized (mPackages) {
16132                                mSettings.readDefaultAppsLPw(parser, userId);
16133                            }
16134                        }
16135                    } );
16136        } catch (Exception e) {
16137            if (DEBUG_BACKUP) {
16138                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16139            }
16140        }
16141    }
16142
16143    @Override
16144    public byte[] getIntentFilterVerificationBackup(int userId) {
16145        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16146            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16147        }
16148
16149        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16150        try {
16151            final XmlSerializer serializer = new FastXmlSerializer();
16152            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16153            serializer.startDocument(null, true);
16154            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16155
16156            synchronized (mPackages) {
16157                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16158            }
16159
16160            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16161            serializer.endDocument();
16162            serializer.flush();
16163        } catch (Exception e) {
16164            if (DEBUG_BACKUP) {
16165                Slog.e(TAG, "Unable to write default apps for backup", e);
16166            }
16167            return null;
16168        }
16169
16170        return dataStream.toByteArray();
16171    }
16172
16173    @Override
16174    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16175        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16176            throw new SecurityException("Only the system may call restorePreferredActivities()");
16177        }
16178
16179        try {
16180            final XmlPullParser parser = Xml.newPullParser();
16181            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16182            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16183                    new BlobXmlRestorer() {
16184                        @Override
16185                        public void apply(XmlPullParser parser, int userId)
16186                                throws XmlPullParserException, IOException {
16187                            synchronized (mPackages) {
16188                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16189                                mSettings.writeLPr();
16190                            }
16191                        }
16192                    } );
16193        } catch (Exception e) {
16194            if (DEBUG_BACKUP) {
16195                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16196            }
16197        }
16198    }
16199
16200    @Override
16201    public byte[] getPermissionGrantBackup(int userId) {
16202        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16203            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16204        }
16205
16206        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16207        try {
16208            final XmlSerializer serializer = new FastXmlSerializer();
16209            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16210            serializer.startDocument(null, true);
16211            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16212
16213            synchronized (mPackages) {
16214                serializeRuntimePermissionGrantsLPr(serializer, userId);
16215            }
16216
16217            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16218            serializer.endDocument();
16219            serializer.flush();
16220        } catch (Exception e) {
16221            if (DEBUG_BACKUP) {
16222                Slog.e(TAG, "Unable to write default apps for backup", e);
16223            }
16224            return null;
16225        }
16226
16227        return dataStream.toByteArray();
16228    }
16229
16230    @Override
16231    public void restorePermissionGrants(byte[] backup, int userId) {
16232        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16233            throw new SecurityException("Only the system may call restorePermissionGrants()");
16234        }
16235
16236        try {
16237            final XmlPullParser parser = Xml.newPullParser();
16238            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16239            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16240                    new BlobXmlRestorer() {
16241                        @Override
16242                        public void apply(XmlPullParser parser, int userId)
16243                                throws XmlPullParserException, IOException {
16244                            synchronized (mPackages) {
16245                                processRestoredPermissionGrantsLPr(parser, userId);
16246                            }
16247                        }
16248                    } );
16249        } catch (Exception e) {
16250            if (DEBUG_BACKUP) {
16251                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16252            }
16253        }
16254    }
16255
16256    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16257            throws IOException {
16258        serializer.startTag(null, TAG_ALL_GRANTS);
16259
16260        final int N = mSettings.mPackages.size();
16261        for (int i = 0; i < N; i++) {
16262            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16263            boolean pkgGrantsKnown = false;
16264
16265            PermissionsState packagePerms = ps.getPermissionsState();
16266
16267            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16268                final int grantFlags = state.getFlags();
16269                // only look at grants that are not system/policy fixed
16270                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16271                    final boolean isGranted = state.isGranted();
16272                    // And only back up the user-twiddled state bits
16273                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16274                        final String packageName = mSettings.mPackages.keyAt(i);
16275                        if (!pkgGrantsKnown) {
16276                            serializer.startTag(null, TAG_GRANT);
16277                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16278                            pkgGrantsKnown = true;
16279                        }
16280
16281                        final boolean userSet =
16282                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16283                        final boolean userFixed =
16284                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16285                        final boolean revoke =
16286                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16287
16288                        serializer.startTag(null, TAG_PERMISSION);
16289                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16290                        if (isGranted) {
16291                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16292                        }
16293                        if (userSet) {
16294                            serializer.attribute(null, ATTR_USER_SET, "true");
16295                        }
16296                        if (userFixed) {
16297                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16298                        }
16299                        if (revoke) {
16300                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16301                        }
16302                        serializer.endTag(null, TAG_PERMISSION);
16303                    }
16304                }
16305            }
16306
16307            if (pkgGrantsKnown) {
16308                serializer.endTag(null, TAG_GRANT);
16309            }
16310        }
16311
16312        serializer.endTag(null, TAG_ALL_GRANTS);
16313    }
16314
16315    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16316            throws XmlPullParserException, IOException {
16317        String pkgName = null;
16318        int outerDepth = parser.getDepth();
16319        int type;
16320        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16321                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16322            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16323                continue;
16324            }
16325
16326            final String tagName = parser.getName();
16327            if (tagName.equals(TAG_GRANT)) {
16328                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16329                if (DEBUG_BACKUP) {
16330                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16331                }
16332            } else if (tagName.equals(TAG_PERMISSION)) {
16333
16334                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16335                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16336
16337                int newFlagSet = 0;
16338                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16339                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16340                }
16341                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16342                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16343                }
16344                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16345                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16346                }
16347                if (DEBUG_BACKUP) {
16348                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16349                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16350                }
16351                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16352                if (ps != null) {
16353                    // Already installed so we apply the grant immediately
16354                    if (DEBUG_BACKUP) {
16355                        Slog.v(TAG, "        + already installed; applying");
16356                    }
16357                    PermissionsState perms = ps.getPermissionsState();
16358                    BasePermission bp = mSettings.mPermissions.get(permName);
16359                    if (bp != null) {
16360                        if (isGranted) {
16361                            perms.grantRuntimePermission(bp, userId);
16362                        }
16363                        if (newFlagSet != 0) {
16364                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16365                        }
16366                    }
16367                } else {
16368                    // Need to wait for post-restore install to apply the grant
16369                    if (DEBUG_BACKUP) {
16370                        Slog.v(TAG, "        - not yet installed; saving for later");
16371                    }
16372                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16373                            isGranted, newFlagSet, userId);
16374                }
16375            } else {
16376                PackageManagerService.reportSettingsProblem(Log.WARN,
16377                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16378                XmlUtils.skipCurrentTag(parser);
16379            }
16380        }
16381
16382        scheduleWriteSettingsLocked();
16383        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16384    }
16385
16386    @Override
16387    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16388            int sourceUserId, int targetUserId, int flags) {
16389        mContext.enforceCallingOrSelfPermission(
16390                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16391        int callingUid = Binder.getCallingUid();
16392        enforceOwnerRights(ownerPackage, callingUid);
16393        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16394        if (intentFilter.countActions() == 0) {
16395            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16396            return;
16397        }
16398        synchronized (mPackages) {
16399            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16400                    ownerPackage, targetUserId, flags);
16401            CrossProfileIntentResolver resolver =
16402                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16403            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16404            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16405            if (existing != null) {
16406                int size = existing.size();
16407                for (int i = 0; i < size; i++) {
16408                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16409                        return;
16410                    }
16411                }
16412            }
16413            resolver.addFilter(newFilter);
16414            scheduleWritePackageRestrictionsLocked(sourceUserId);
16415        }
16416    }
16417
16418    @Override
16419    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16420        mContext.enforceCallingOrSelfPermission(
16421                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16422        int callingUid = Binder.getCallingUid();
16423        enforceOwnerRights(ownerPackage, callingUid);
16424        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16425        synchronized (mPackages) {
16426            CrossProfileIntentResolver resolver =
16427                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16428            ArraySet<CrossProfileIntentFilter> set =
16429                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16430            for (CrossProfileIntentFilter filter : set) {
16431                if (filter.getOwnerPackage().equals(ownerPackage)) {
16432                    resolver.removeFilter(filter);
16433                }
16434            }
16435            scheduleWritePackageRestrictionsLocked(sourceUserId);
16436        }
16437    }
16438
16439    // Enforcing that callingUid is owning pkg on userId
16440    private void enforceOwnerRights(String pkg, int callingUid) {
16441        // The system owns everything.
16442        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16443            return;
16444        }
16445        int callingUserId = UserHandle.getUserId(callingUid);
16446        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16447        if (pi == null) {
16448            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16449                    + callingUserId);
16450        }
16451        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16452            throw new SecurityException("Calling uid " + callingUid
16453                    + " does not own package " + pkg);
16454        }
16455    }
16456
16457    @Override
16458    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16459        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16460    }
16461
16462    private Intent getHomeIntent() {
16463        Intent intent = new Intent(Intent.ACTION_MAIN);
16464        intent.addCategory(Intent.CATEGORY_HOME);
16465        return intent;
16466    }
16467
16468    private IntentFilter getHomeFilter() {
16469        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16470        filter.addCategory(Intent.CATEGORY_HOME);
16471        filter.addCategory(Intent.CATEGORY_DEFAULT);
16472        return filter;
16473    }
16474
16475    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16476            int userId) {
16477        Intent intent  = getHomeIntent();
16478        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16479                PackageManager.GET_META_DATA, userId);
16480        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16481                true, false, false, userId);
16482
16483        allHomeCandidates.clear();
16484        if (list != null) {
16485            for (ResolveInfo ri : list) {
16486                allHomeCandidates.add(ri);
16487            }
16488        }
16489        return (preferred == null || preferred.activityInfo == null)
16490                ? null
16491                : new ComponentName(preferred.activityInfo.packageName,
16492                        preferred.activityInfo.name);
16493    }
16494
16495    @Override
16496    public void setHomeActivity(ComponentName comp, int userId) {
16497        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16498        getHomeActivitiesAsUser(homeActivities, userId);
16499
16500        boolean found = false;
16501
16502        final int size = homeActivities.size();
16503        final ComponentName[] set = new ComponentName[size];
16504        for (int i = 0; i < size; i++) {
16505            final ResolveInfo candidate = homeActivities.get(i);
16506            final ActivityInfo info = candidate.activityInfo;
16507            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16508            set[i] = activityName;
16509            if (!found && activityName.equals(comp)) {
16510                found = true;
16511            }
16512        }
16513        if (!found) {
16514            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16515                    + userId);
16516        }
16517        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16518                set, comp, userId);
16519    }
16520
16521    @Override
16522    public void setApplicationEnabledSetting(String appPackageName,
16523            int newState, int flags, int userId, String callingPackage) {
16524        if (!sUserManager.exists(userId)) return;
16525        if (callingPackage == null) {
16526            callingPackage = Integer.toString(Binder.getCallingUid());
16527        }
16528        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16529    }
16530
16531    @Override
16532    public void setComponentEnabledSetting(ComponentName componentName,
16533            int newState, int flags, int userId) {
16534        if (!sUserManager.exists(userId)) return;
16535        setEnabledSetting(componentName.getPackageName(),
16536                componentName.getClassName(), newState, flags, userId, null);
16537    }
16538
16539    private void setEnabledSetting(final String packageName, String className, int newState,
16540            final int flags, int userId, String callingPackage) {
16541        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16542              || newState == COMPONENT_ENABLED_STATE_ENABLED
16543              || newState == COMPONENT_ENABLED_STATE_DISABLED
16544              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16545              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16546            throw new IllegalArgumentException("Invalid new component state: "
16547                    + newState);
16548        }
16549        PackageSetting pkgSetting;
16550        final int uid = Binder.getCallingUid();
16551        final int permission = mContext.checkCallingOrSelfPermission(
16552                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16553        enforceCrossUserPermission(uid, userId,
16554                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16555        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16556        boolean sendNow = false;
16557        boolean isApp = (className == null);
16558        String componentName = isApp ? packageName : className;
16559        int packageUid = -1;
16560        ArrayList<String> components;
16561
16562        // writer
16563        synchronized (mPackages) {
16564            pkgSetting = mSettings.mPackages.get(packageName);
16565            if (pkgSetting == null) {
16566                if (className == null) {
16567                    throw new IllegalArgumentException("Unknown package: " + packageName);
16568                }
16569                throw new IllegalArgumentException(
16570                        "Unknown component: " + packageName + "/" + className);
16571            }
16572            // Allow root and verify that userId is not being specified by a different user
16573            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16574                throw new SecurityException(
16575                        "Permission Denial: attempt to change component state from pid="
16576                        + Binder.getCallingPid()
16577                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16578            }
16579            if (className == null) {
16580                // We're dealing with an application/package level state change
16581                if (pkgSetting.getEnabled(userId) == newState) {
16582                    // Nothing to do
16583                    return;
16584                }
16585                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16586                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16587                    // Don't care about who enables an app.
16588                    callingPackage = null;
16589                }
16590                pkgSetting.setEnabled(newState, userId, callingPackage);
16591                // pkgSetting.pkg.mSetEnabled = newState;
16592            } else {
16593                // We're dealing with a component level state change
16594                // First, verify that this is a valid class name.
16595                PackageParser.Package pkg = pkgSetting.pkg;
16596                if (pkg == null || !pkg.hasComponentClassName(className)) {
16597                    if (pkg != null &&
16598                            pkg.applicationInfo.targetSdkVersion >=
16599                                    Build.VERSION_CODES.JELLY_BEAN) {
16600                        throw new IllegalArgumentException("Component class " + className
16601                                + " does not exist in " + packageName);
16602                    } else {
16603                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16604                                + className + " does not exist in " + packageName);
16605                    }
16606                }
16607                switch (newState) {
16608                case COMPONENT_ENABLED_STATE_ENABLED:
16609                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16610                        return;
16611                    }
16612                    break;
16613                case COMPONENT_ENABLED_STATE_DISABLED:
16614                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16615                        return;
16616                    }
16617                    break;
16618                case COMPONENT_ENABLED_STATE_DEFAULT:
16619                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16620                        return;
16621                    }
16622                    break;
16623                default:
16624                    Slog.e(TAG, "Invalid new component state: " + newState);
16625                    return;
16626                }
16627            }
16628            scheduleWritePackageRestrictionsLocked(userId);
16629            components = mPendingBroadcasts.get(userId, packageName);
16630            final boolean newPackage = components == null;
16631            if (newPackage) {
16632                components = new ArrayList<String>();
16633            }
16634            if (!components.contains(componentName)) {
16635                components.add(componentName);
16636            }
16637            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16638                sendNow = true;
16639                // Purge entry from pending broadcast list if another one exists already
16640                // since we are sending one right away.
16641                mPendingBroadcasts.remove(userId, packageName);
16642            } else {
16643                if (newPackage) {
16644                    mPendingBroadcasts.put(userId, packageName, components);
16645                }
16646                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16647                    // Schedule a message
16648                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16649                }
16650            }
16651        }
16652
16653        long callingId = Binder.clearCallingIdentity();
16654        try {
16655            if (sendNow) {
16656                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16657                sendPackageChangedBroadcast(packageName,
16658                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16659            }
16660        } finally {
16661            Binder.restoreCallingIdentity(callingId);
16662        }
16663    }
16664
16665    @Override
16666    public void flushPackageRestrictionsAsUser(int userId) {
16667        if (!sUserManager.exists(userId)) {
16668            return;
16669        }
16670        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
16671                false /* checkShell */, "flushPackageRestrictions");
16672        synchronized (mPackages) {
16673            mSettings.writePackageRestrictionsLPr(userId);
16674            mDirtyUsers.remove(userId);
16675            if (mDirtyUsers.isEmpty()) {
16676                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
16677            }
16678        }
16679    }
16680
16681    private void sendPackageChangedBroadcast(String packageName,
16682            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16683        if (DEBUG_INSTALL)
16684            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16685                    + componentNames);
16686        Bundle extras = new Bundle(4);
16687        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16688        String nameList[] = new String[componentNames.size()];
16689        componentNames.toArray(nameList);
16690        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16691        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16692        extras.putInt(Intent.EXTRA_UID, packageUid);
16693        // If this is not reporting a change of the overall package, then only send it
16694        // to registered receivers.  We don't want to launch a swath of apps for every
16695        // little component state change.
16696        final int flags = !componentNames.contains(packageName)
16697                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16698        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16699                new int[] {UserHandle.getUserId(packageUid)});
16700    }
16701
16702    @Override
16703    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16704        if (!sUserManager.exists(userId)) return;
16705        final int uid = Binder.getCallingUid();
16706        final int permission = mContext.checkCallingOrSelfPermission(
16707                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16708        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16709        enforceCrossUserPermission(uid, userId,
16710                true /* requireFullPermission */, true /* checkShell */, "stop package");
16711        // writer
16712        synchronized (mPackages) {
16713            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16714                    allowedByPermission, uid, userId)) {
16715                scheduleWritePackageRestrictionsLocked(userId);
16716            }
16717        }
16718    }
16719
16720    @Override
16721    public String getInstallerPackageName(String packageName) {
16722        // reader
16723        synchronized (mPackages) {
16724            return mSettings.getInstallerPackageNameLPr(packageName);
16725        }
16726    }
16727
16728    @Override
16729    public int getApplicationEnabledSetting(String packageName, int userId) {
16730        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16731        int uid = Binder.getCallingUid();
16732        enforceCrossUserPermission(uid, userId,
16733                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16734        // reader
16735        synchronized (mPackages) {
16736            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16737        }
16738    }
16739
16740    @Override
16741    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16742        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16743        int uid = Binder.getCallingUid();
16744        enforceCrossUserPermission(uid, userId,
16745                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16746        // reader
16747        synchronized (mPackages) {
16748            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16749        }
16750    }
16751
16752    @Override
16753    public void enterSafeMode() {
16754        enforceSystemOrRoot("Only the system can request entering safe mode");
16755
16756        if (!mSystemReady) {
16757            mSafeMode = true;
16758        }
16759    }
16760
16761    @Override
16762    public void systemReady() {
16763        mSystemReady = true;
16764
16765        // Read the compatibilty setting when the system is ready.
16766        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16767                mContext.getContentResolver(),
16768                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16769        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16770        if (DEBUG_SETTINGS) {
16771            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16772        }
16773
16774        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16775
16776        synchronized (mPackages) {
16777            // Verify that all of the preferred activity components actually
16778            // exist.  It is possible for applications to be updated and at
16779            // that point remove a previously declared activity component that
16780            // had been set as a preferred activity.  We try to clean this up
16781            // the next time we encounter that preferred activity, but it is
16782            // possible for the user flow to never be able to return to that
16783            // situation so here we do a sanity check to make sure we haven't
16784            // left any junk around.
16785            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16786            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16787                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16788                removed.clear();
16789                for (PreferredActivity pa : pir.filterSet()) {
16790                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16791                        removed.add(pa);
16792                    }
16793                }
16794                if (removed.size() > 0) {
16795                    for (int r=0; r<removed.size(); r++) {
16796                        PreferredActivity pa = removed.get(r);
16797                        Slog.w(TAG, "Removing dangling preferred activity: "
16798                                + pa.mPref.mComponent);
16799                        pir.removeFilter(pa);
16800                    }
16801                    mSettings.writePackageRestrictionsLPr(
16802                            mSettings.mPreferredActivities.keyAt(i));
16803                }
16804            }
16805
16806            for (int userId : UserManagerService.getInstance().getUserIds()) {
16807                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16808                    grantPermissionsUserIds = ArrayUtils.appendInt(
16809                            grantPermissionsUserIds, userId);
16810                }
16811            }
16812        }
16813        sUserManager.systemReady();
16814
16815        // If we upgraded grant all default permissions before kicking off.
16816        for (int userId : grantPermissionsUserIds) {
16817            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16818        }
16819
16820        // Kick off any messages waiting for system ready
16821        if (mPostSystemReadyMessages != null) {
16822            for (Message msg : mPostSystemReadyMessages) {
16823                msg.sendToTarget();
16824            }
16825            mPostSystemReadyMessages = null;
16826        }
16827
16828        // Watch for external volumes that come and go over time
16829        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16830        storage.registerListener(mStorageListener);
16831
16832        mInstallerService.systemReady();
16833        mPackageDexOptimizer.systemReady();
16834
16835        MountServiceInternal mountServiceInternal = LocalServices.getService(
16836                MountServiceInternal.class);
16837        mountServiceInternal.addExternalStoragePolicy(
16838                new MountServiceInternal.ExternalStorageMountPolicy() {
16839            @Override
16840            public int getMountMode(int uid, String packageName) {
16841                if (Process.isIsolated(uid)) {
16842                    return Zygote.MOUNT_EXTERNAL_NONE;
16843                }
16844                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16845                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16846                }
16847                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16848                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16849                }
16850                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16851                    return Zygote.MOUNT_EXTERNAL_READ;
16852                }
16853                return Zygote.MOUNT_EXTERNAL_WRITE;
16854            }
16855
16856            @Override
16857            public boolean hasExternalStorage(int uid, String packageName) {
16858                return true;
16859            }
16860        });
16861    }
16862
16863    @Override
16864    public boolean isSafeMode() {
16865        return mSafeMode;
16866    }
16867
16868    @Override
16869    public boolean hasSystemUidErrors() {
16870        return mHasSystemUidErrors;
16871    }
16872
16873    static String arrayToString(int[] array) {
16874        StringBuffer buf = new StringBuffer(128);
16875        buf.append('[');
16876        if (array != null) {
16877            for (int i=0; i<array.length; i++) {
16878                if (i > 0) buf.append(", ");
16879                buf.append(array[i]);
16880            }
16881        }
16882        buf.append(']');
16883        return buf.toString();
16884    }
16885
16886    static class DumpState {
16887        public static final int DUMP_LIBS = 1 << 0;
16888        public static final int DUMP_FEATURES = 1 << 1;
16889        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16890        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16891        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16892        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16893        public static final int DUMP_PERMISSIONS = 1 << 6;
16894        public static final int DUMP_PACKAGES = 1 << 7;
16895        public static final int DUMP_SHARED_USERS = 1 << 8;
16896        public static final int DUMP_MESSAGES = 1 << 9;
16897        public static final int DUMP_PROVIDERS = 1 << 10;
16898        public static final int DUMP_VERIFIERS = 1 << 11;
16899        public static final int DUMP_PREFERRED = 1 << 12;
16900        public static final int DUMP_PREFERRED_XML = 1 << 13;
16901        public static final int DUMP_KEYSETS = 1 << 14;
16902        public static final int DUMP_VERSION = 1 << 15;
16903        public static final int DUMP_INSTALLS = 1 << 16;
16904        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16905        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16906
16907        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16908
16909        private int mTypes;
16910
16911        private int mOptions;
16912
16913        private boolean mTitlePrinted;
16914
16915        private SharedUserSetting mSharedUser;
16916
16917        public boolean isDumping(int type) {
16918            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16919                return true;
16920            }
16921
16922            return (mTypes & type) != 0;
16923        }
16924
16925        public void setDump(int type) {
16926            mTypes |= type;
16927        }
16928
16929        public boolean isOptionEnabled(int option) {
16930            return (mOptions & option) != 0;
16931        }
16932
16933        public void setOptionEnabled(int option) {
16934            mOptions |= option;
16935        }
16936
16937        public boolean onTitlePrinted() {
16938            final boolean printed = mTitlePrinted;
16939            mTitlePrinted = true;
16940            return printed;
16941        }
16942
16943        public boolean getTitlePrinted() {
16944            return mTitlePrinted;
16945        }
16946
16947        public void setTitlePrinted(boolean enabled) {
16948            mTitlePrinted = enabled;
16949        }
16950
16951        public SharedUserSetting getSharedUser() {
16952            return mSharedUser;
16953        }
16954
16955        public void setSharedUser(SharedUserSetting user) {
16956            mSharedUser = user;
16957        }
16958    }
16959
16960    @Override
16961    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16962            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16963        (new PackageManagerShellCommand(this)).exec(
16964                this, in, out, err, args, resultReceiver);
16965    }
16966
16967    @Override
16968    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16969        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16970                != PackageManager.PERMISSION_GRANTED) {
16971            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16972                    + Binder.getCallingPid()
16973                    + ", uid=" + Binder.getCallingUid()
16974                    + " without permission "
16975                    + android.Manifest.permission.DUMP);
16976            return;
16977        }
16978
16979        DumpState dumpState = new DumpState();
16980        boolean fullPreferred = false;
16981        boolean checkin = false;
16982
16983        String packageName = null;
16984        ArraySet<String> permissionNames = null;
16985
16986        int opti = 0;
16987        while (opti < args.length) {
16988            String opt = args[opti];
16989            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16990                break;
16991            }
16992            opti++;
16993
16994            if ("-a".equals(opt)) {
16995                // Right now we only know how to print all.
16996            } else if ("-h".equals(opt)) {
16997                pw.println("Package manager dump options:");
16998                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16999                pw.println("    --checkin: dump for a checkin");
17000                pw.println("    -f: print details of intent filters");
17001                pw.println("    -h: print this help");
17002                pw.println("  cmd may be one of:");
17003                pw.println("    l[ibraries]: list known shared libraries");
17004                pw.println("    f[eatures]: list device features");
17005                pw.println("    k[eysets]: print known keysets");
17006                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17007                pw.println("    perm[issions]: dump permissions");
17008                pw.println("    permission [name ...]: dump declaration and use of given permission");
17009                pw.println("    pref[erred]: print preferred package settings");
17010                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17011                pw.println("    prov[iders]: dump content providers");
17012                pw.println("    p[ackages]: dump installed packages");
17013                pw.println("    s[hared-users]: dump shared user IDs");
17014                pw.println("    m[essages]: print collected runtime messages");
17015                pw.println("    v[erifiers]: print package verifier info");
17016                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17017                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17018                pw.println("    version: print database version info");
17019                pw.println("    write: write current settings now");
17020                pw.println("    installs: details about install sessions");
17021                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17022                pw.println("    <package.name>: info about given package");
17023                return;
17024            } else if ("--checkin".equals(opt)) {
17025                checkin = true;
17026            } else if ("-f".equals(opt)) {
17027                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17028            } else {
17029                pw.println("Unknown argument: " + opt + "; use -h for help");
17030            }
17031        }
17032
17033        // Is the caller requesting to dump a particular piece of data?
17034        if (opti < args.length) {
17035            String cmd = args[opti];
17036            opti++;
17037            // Is this a package name?
17038            if ("android".equals(cmd) || cmd.contains(".")) {
17039                packageName = cmd;
17040                // When dumping a single package, we always dump all of its
17041                // filter information since the amount of data will be reasonable.
17042                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17043            } else if ("check-permission".equals(cmd)) {
17044                if (opti >= args.length) {
17045                    pw.println("Error: check-permission missing permission argument");
17046                    return;
17047                }
17048                String perm = args[opti];
17049                opti++;
17050                if (opti >= args.length) {
17051                    pw.println("Error: check-permission missing package argument");
17052                    return;
17053                }
17054                String pkg = args[opti];
17055                opti++;
17056                int user = UserHandle.getUserId(Binder.getCallingUid());
17057                if (opti < args.length) {
17058                    try {
17059                        user = Integer.parseInt(args[opti]);
17060                    } catch (NumberFormatException e) {
17061                        pw.println("Error: check-permission user argument is not a number: "
17062                                + args[opti]);
17063                        return;
17064                    }
17065                }
17066                pw.println(checkPermission(perm, pkg, user));
17067                return;
17068            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17069                dumpState.setDump(DumpState.DUMP_LIBS);
17070            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17071                dumpState.setDump(DumpState.DUMP_FEATURES);
17072            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17073                if (opti >= args.length) {
17074                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17075                            | DumpState.DUMP_SERVICE_RESOLVERS
17076                            | DumpState.DUMP_RECEIVER_RESOLVERS
17077                            | DumpState.DUMP_CONTENT_RESOLVERS);
17078                } else {
17079                    while (opti < args.length) {
17080                        String name = args[opti];
17081                        if ("a".equals(name) || "activity".equals(name)) {
17082                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17083                        } else if ("s".equals(name) || "service".equals(name)) {
17084                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17085                        } else if ("r".equals(name) || "receiver".equals(name)) {
17086                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17087                        } else if ("c".equals(name) || "content".equals(name)) {
17088                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17089                        } else {
17090                            pw.println("Error: unknown resolver table type: " + name);
17091                            return;
17092                        }
17093                        opti++;
17094                    }
17095                }
17096            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17097                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17098            } else if ("permission".equals(cmd)) {
17099                if (opti >= args.length) {
17100                    pw.println("Error: permission requires permission name");
17101                    return;
17102                }
17103                permissionNames = new ArraySet<>();
17104                while (opti < args.length) {
17105                    permissionNames.add(args[opti]);
17106                    opti++;
17107                }
17108                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17109                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17110            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17111                dumpState.setDump(DumpState.DUMP_PREFERRED);
17112            } else if ("preferred-xml".equals(cmd)) {
17113                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17114                if (opti < args.length && "--full".equals(args[opti])) {
17115                    fullPreferred = true;
17116                    opti++;
17117                }
17118            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17119                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17120            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17121                dumpState.setDump(DumpState.DUMP_PACKAGES);
17122            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17123                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17124            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17125                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17126            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17127                dumpState.setDump(DumpState.DUMP_MESSAGES);
17128            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17129                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17130            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17131                    || "intent-filter-verifiers".equals(cmd)) {
17132                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17133            } else if ("version".equals(cmd)) {
17134                dumpState.setDump(DumpState.DUMP_VERSION);
17135            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17136                dumpState.setDump(DumpState.DUMP_KEYSETS);
17137            } else if ("installs".equals(cmd)) {
17138                dumpState.setDump(DumpState.DUMP_INSTALLS);
17139            } else if ("write".equals(cmd)) {
17140                synchronized (mPackages) {
17141                    mSettings.writeLPr();
17142                    pw.println("Settings written.");
17143                    return;
17144                }
17145            }
17146        }
17147
17148        if (checkin) {
17149            pw.println("vers,1");
17150        }
17151
17152        // reader
17153        synchronized (mPackages) {
17154            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17155                if (!checkin) {
17156                    if (dumpState.onTitlePrinted())
17157                        pw.println();
17158                    pw.println("Database versions:");
17159                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17160                }
17161            }
17162
17163            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17164                if (!checkin) {
17165                    if (dumpState.onTitlePrinted())
17166                        pw.println();
17167                    pw.println("Verifiers:");
17168                    pw.print("  Required: ");
17169                    pw.print(mRequiredVerifierPackage);
17170                    pw.print(" (uid=");
17171                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17172                            UserHandle.USER_SYSTEM));
17173                    pw.println(")");
17174                } else if (mRequiredVerifierPackage != null) {
17175                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17176                    pw.print(",");
17177                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17178                            UserHandle.USER_SYSTEM));
17179                }
17180            }
17181
17182            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17183                    packageName == null) {
17184                if (mIntentFilterVerifierComponent != null) {
17185                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17186                    if (!checkin) {
17187                        if (dumpState.onTitlePrinted())
17188                            pw.println();
17189                        pw.println("Intent Filter Verifier:");
17190                        pw.print("  Using: ");
17191                        pw.print(verifierPackageName);
17192                        pw.print(" (uid=");
17193                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17194                                UserHandle.USER_SYSTEM));
17195                        pw.println(")");
17196                    } else if (verifierPackageName != null) {
17197                        pw.print("ifv,"); pw.print(verifierPackageName);
17198                        pw.print(",");
17199                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17200                                UserHandle.USER_SYSTEM));
17201                    }
17202                } else {
17203                    pw.println();
17204                    pw.println("No Intent Filter Verifier available!");
17205                }
17206            }
17207
17208            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17209                boolean printedHeader = false;
17210                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17211                while (it.hasNext()) {
17212                    String name = it.next();
17213                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17214                    if (!checkin) {
17215                        if (!printedHeader) {
17216                            if (dumpState.onTitlePrinted())
17217                                pw.println();
17218                            pw.println("Libraries:");
17219                            printedHeader = true;
17220                        }
17221                        pw.print("  ");
17222                    } else {
17223                        pw.print("lib,");
17224                    }
17225                    pw.print(name);
17226                    if (!checkin) {
17227                        pw.print(" -> ");
17228                    }
17229                    if (ent.path != null) {
17230                        if (!checkin) {
17231                            pw.print("(jar) ");
17232                            pw.print(ent.path);
17233                        } else {
17234                            pw.print(",jar,");
17235                            pw.print(ent.path);
17236                        }
17237                    } else {
17238                        if (!checkin) {
17239                            pw.print("(apk) ");
17240                            pw.print(ent.apk);
17241                        } else {
17242                            pw.print(",apk,");
17243                            pw.print(ent.apk);
17244                        }
17245                    }
17246                    pw.println();
17247                }
17248            }
17249
17250            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17251                if (dumpState.onTitlePrinted())
17252                    pw.println();
17253                if (!checkin) {
17254                    pw.println("Features:");
17255                }
17256
17257                for (FeatureInfo feat : mAvailableFeatures.values()) {
17258                    if (checkin) {
17259                        pw.print("feat,");
17260                        pw.print(feat.name);
17261                        pw.print(",");
17262                        pw.println(feat.version);
17263                    } else {
17264                        pw.print("  ");
17265                        pw.print(feat.name);
17266                        if (feat.version > 0) {
17267                            pw.print(" version=");
17268                            pw.print(feat.version);
17269                        }
17270                        pw.println();
17271                    }
17272                }
17273            }
17274
17275            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17276                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17277                        : "Activity Resolver Table:", "  ", packageName,
17278                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17279                    dumpState.setTitlePrinted(true);
17280                }
17281            }
17282            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17283                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17284                        : "Receiver Resolver Table:", "  ", packageName,
17285                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17286                    dumpState.setTitlePrinted(true);
17287                }
17288            }
17289            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17290                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17291                        : "Service Resolver Table:", "  ", packageName,
17292                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17293                    dumpState.setTitlePrinted(true);
17294                }
17295            }
17296            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17297                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17298                        : "Provider Resolver Table:", "  ", packageName,
17299                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17300                    dumpState.setTitlePrinted(true);
17301                }
17302            }
17303
17304            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17305                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17306                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17307                    int user = mSettings.mPreferredActivities.keyAt(i);
17308                    if (pir.dump(pw,
17309                            dumpState.getTitlePrinted()
17310                                ? "\nPreferred Activities User " + user + ":"
17311                                : "Preferred Activities User " + user + ":", "  ",
17312                            packageName, true, false)) {
17313                        dumpState.setTitlePrinted(true);
17314                    }
17315                }
17316            }
17317
17318            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17319                pw.flush();
17320                FileOutputStream fout = new FileOutputStream(fd);
17321                BufferedOutputStream str = new BufferedOutputStream(fout);
17322                XmlSerializer serializer = new FastXmlSerializer();
17323                try {
17324                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17325                    serializer.startDocument(null, true);
17326                    serializer.setFeature(
17327                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17328                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17329                    serializer.endDocument();
17330                    serializer.flush();
17331                } catch (IllegalArgumentException e) {
17332                    pw.println("Failed writing: " + e);
17333                } catch (IllegalStateException e) {
17334                    pw.println("Failed writing: " + e);
17335                } catch (IOException e) {
17336                    pw.println("Failed writing: " + e);
17337                }
17338            }
17339
17340            if (!checkin
17341                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17342                    && packageName == null) {
17343                pw.println();
17344                int count = mSettings.mPackages.size();
17345                if (count == 0) {
17346                    pw.println("No applications!");
17347                    pw.println();
17348                } else {
17349                    final String prefix = "  ";
17350                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17351                    if (allPackageSettings.size() == 0) {
17352                        pw.println("No domain preferred apps!");
17353                        pw.println();
17354                    } else {
17355                        pw.println("App verification status:");
17356                        pw.println();
17357                        count = 0;
17358                        for (PackageSetting ps : allPackageSettings) {
17359                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17360                            if (ivi == null || ivi.getPackageName() == null) continue;
17361                            pw.println(prefix + "Package: " + ivi.getPackageName());
17362                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17363                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17364                            pw.println();
17365                            count++;
17366                        }
17367                        if (count == 0) {
17368                            pw.println(prefix + "No app verification established.");
17369                            pw.println();
17370                        }
17371                        for (int userId : sUserManager.getUserIds()) {
17372                            pw.println("App linkages for user " + userId + ":");
17373                            pw.println();
17374                            count = 0;
17375                            for (PackageSetting ps : allPackageSettings) {
17376                                final long status = ps.getDomainVerificationStatusForUser(userId);
17377                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17378                                    continue;
17379                                }
17380                                pw.println(prefix + "Package: " + ps.name);
17381                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17382                                String statusStr = IntentFilterVerificationInfo.
17383                                        getStatusStringFromValue(status);
17384                                pw.println(prefix + "Status:  " + statusStr);
17385                                pw.println();
17386                                count++;
17387                            }
17388                            if (count == 0) {
17389                                pw.println(prefix + "No configured app linkages.");
17390                                pw.println();
17391                            }
17392                        }
17393                    }
17394                }
17395            }
17396
17397            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17398                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17399                if (packageName == null && permissionNames == null) {
17400                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17401                        if (iperm == 0) {
17402                            if (dumpState.onTitlePrinted())
17403                                pw.println();
17404                            pw.println("AppOp Permissions:");
17405                        }
17406                        pw.print("  AppOp Permission ");
17407                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17408                        pw.println(":");
17409                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17410                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17411                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17412                        }
17413                    }
17414                }
17415            }
17416
17417            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17418                boolean printedSomething = false;
17419                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17420                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17421                        continue;
17422                    }
17423                    if (!printedSomething) {
17424                        if (dumpState.onTitlePrinted())
17425                            pw.println();
17426                        pw.println("Registered ContentProviders:");
17427                        printedSomething = true;
17428                    }
17429                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17430                    pw.print("    "); pw.println(p.toString());
17431                }
17432                printedSomething = false;
17433                for (Map.Entry<String, PackageParser.Provider> entry :
17434                        mProvidersByAuthority.entrySet()) {
17435                    PackageParser.Provider p = entry.getValue();
17436                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17437                        continue;
17438                    }
17439                    if (!printedSomething) {
17440                        if (dumpState.onTitlePrinted())
17441                            pw.println();
17442                        pw.println("ContentProvider Authorities:");
17443                        printedSomething = true;
17444                    }
17445                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17446                    pw.print("    "); pw.println(p.toString());
17447                    if (p.info != null && p.info.applicationInfo != null) {
17448                        final String appInfo = p.info.applicationInfo.toString();
17449                        pw.print("      applicationInfo="); pw.println(appInfo);
17450                    }
17451                }
17452            }
17453
17454            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17455                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17456            }
17457
17458            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17459                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17460            }
17461
17462            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17463                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17464            }
17465
17466            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17467                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17468            }
17469
17470            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17471                // XXX should handle packageName != null by dumping only install data that
17472                // the given package is involved with.
17473                if (dumpState.onTitlePrinted()) pw.println();
17474                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17475            }
17476
17477            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17478                if (dumpState.onTitlePrinted()) pw.println();
17479                mSettings.dumpReadMessagesLPr(pw, dumpState);
17480
17481                pw.println();
17482                pw.println("Package warning messages:");
17483                BufferedReader in = null;
17484                String line = null;
17485                try {
17486                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17487                    while ((line = in.readLine()) != null) {
17488                        if (line.contains("ignored: updated version")) continue;
17489                        pw.println(line);
17490                    }
17491                } catch (IOException ignored) {
17492                } finally {
17493                    IoUtils.closeQuietly(in);
17494                }
17495            }
17496
17497            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17498                BufferedReader in = null;
17499                String line = null;
17500                try {
17501                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17502                    while ((line = in.readLine()) != null) {
17503                        if (line.contains("ignored: updated version")) continue;
17504                        pw.print("msg,");
17505                        pw.println(line);
17506                    }
17507                } catch (IOException ignored) {
17508                } finally {
17509                    IoUtils.closeQuietly(in);
17510                }
17511            }
17512        }
17513    }
17514
17515    private String dumpDomainString(String packageName) {
17516        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
17517                .getList();
17518        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
17519
17520        ArraySet<String> result = new ArraySet<>();
17521        if (iviList.size() > 0) {
17522            for (IntentFilterVerificationInfo ivi : iviList) {
17523                for (String host : ivi.getDomains()) {
17524                    result.add(host);
17525                }
17526            }
17527        }
17528        if (filters != null && filters.size() > 0) {
17529            for (IntentFilter filter : filters) {
17530                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17531                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17532                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17533                    result.addAll(filter.getHostsList());
17534                }
17535            }
17536        }
17537
17538        StringBuilder sb = new StringBuilder(result.size() * 16);
17539        for (String domain : result) {
17540            if (sb.length() > 0) sb.append(" ");
17541            sb.append(domain);
17542        }
17543        return sb.toString();
17544    }
17545
17546    // ------- apps on sdcard specific code -------
17547    static final boolean DEBUG_SD_INSTALL = false;
17548
17549    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17550
17551    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17552
17553    private boolean mMediaMounted = false;
17554
17555    static String getEncryptKey() {
17556        try {
17557            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17558                    SD_ENCRYPTION_KEYSTORE_NAME);
17559            if (sdEncKey == null) {
17560                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17561                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17562                if (sdEncKey == null) {
17563                    Slog.e(TAG, "Failed to create encryption keys");
17564                    return null;
17565                }
17566            }
17567            return sdEncKey;
17568        } catch (NoSuchAlgorithmException nsae) {
17569            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17570            return null;
17571        } catch (IOException ioe) {
17572            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17573            return null;
17574        }
17575    }
17576
17577    /*
17578     * Update media status on PackageManager.
17579     */
17580    @Override
17581    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17582        int callingUid = Binder.getCallingUid();
17583        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17584            throw new SecurityException("Media status can only be updated by the system");
17585        }
17586        // reader; this apparently protects mMediaMounted, but should probably
17587        // be a different lock in that case.
17588        synchronized (mPackages) {
17589            Log.i(TAG, "Updating external media status from "
17590                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17591                    + (mediaStatus ? "mounted" : "unmounted"));
17592            if (DEBUG_SD_INSTALL)
17593                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17594                        + ", mMediaMounted=" + mMediaMounted);
17595            if (mediaStatus == mMediaMounted) {
17596                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17597                        : 0, -1);
17598                mHandler.sendMessage(msg);
17599                return;
17600            }
17601            mMediaMounted = mediaStatus;
17602        }
17603        // Queue up an async operation since the package installation may take a
17604        // little while.
17605        mHandler.post(new Runnable() {
17606            public void run() {
17607                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17608            }
17609        });
17610    }
17611
17612    /**
17613     * Called by MountService when the initial ASECs to scan are available.
17614     * Should block until all the ASEC containers are finished being scanned.
17615     */
17616    public void scanAvailableAsecs() {
17617        updateExternalMediaStatusInner(true, false, false);
17618    }
17619
17620    /*
17621     * Collect information of applications on external media, map them against
17622     * existing containers and update information based on current mount status.
17623     * Please note that we always have to report status if reportStatus has been
17624     * set to true especially when unloading packages.
17625     */
17626    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17627            boolean externalStorage) {
17628        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17629        int[] uidArr = EmptyArray.INT;
17630
17631        final String[] list = PackageHelper.getSecureContainerList();
17632        if (ArrayUtils.isEmpty(list)) {
17633            Log.i(TAG, "No secure containers found");
17634        } else {
17635            // Process list of secure containers and categorize them
17636            // as active or stale based on their package internal state.
17637
17638            // reader
17639            synchronized (mPackages) {
17640                for (String cid : list) {
17641                    // Leave stages untouched for now; installer service owns them
17642                    if (PackageInstallerService.isStageName(cid)) continue;
17643
17644                    if (DEBUG_SD_INSTALL)
17645                        Log.i(TAG, "Processing container " + cid);
17646                    String pkgName = getAsecPackageName(cid);
17647                    if (pkgName == null) {
17648                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17649                        continue;
17650                    }
17651                    if (DEBUG_SD_INSTALL)
17652                        Log.i(TAG, "Looking for pkg : " + pkgName);
17653
17654                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17655                    if (ps == null) {
17656                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17657                        continue;
17658                    }
17659
17660                    /*
17661                     * Skip packages that are not external if we're unmounting
17662                     * external storage.
17663                     */
17664                    if (externalStorage && !isMounted && !isExternal(ps)) {
17665                        continue;
17666                    }
17667
17668                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17669                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17670                    // The package status is changed only if the code path
17671                    // matches between settings and the container id.
17672                    if (ps.codePathString != null
17673                            && ps.codePathString.startsWith(args.getCodePath())) {
17674                        if (DEBUG_SD_INSTALL) {
17675                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17676                                    + " at code path: " + ps.codePathString);
17677                        }
17678
17679                        // We do have a valid package installed on sdcard
17680                        processCids.put(args, ps.codePathString);
17681                        final int uid = ps.appId;
17682                        if (uid != -1) {
17683                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17684                        }
17685                    } else {
17686                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17687                                + ps.codePathString);
17688                    }
17689                }
17690            }
17691
17692            Arrays.sort(uidArr);
17693        }
17694
17695        // Process packages with valid entries.
17696        if (isMounted) {
17697            if (DEBUG_SD_INSTALL)
17698                Log.i(TAG, "Loading packages");
17699            loadMediaPackages(processCids, uidArr, externalStorage);
17700            startCleaningPackages();
17701            mInstallerService.onSecureContainersAvailable();
17702        } else {
17703            if (DEBUG_SD_INSTALL)
17704                Log.i(TAG, "Unloading packages");
17705            unloadMediaPackages(processCids, uidArr, reportStatus);
17706        }
17707    }
17708
17709    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17710            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17711        final int size = infos.size();
17712        final String[] packageNames = new String[size];
17713        final int[] packageUids = new int[size];
17714        for (int i = 0; i < size; i++) {
17715            final ApplicationInfo info = infos.get(i);
17716            packageNames[i] = info.packageName;
17717            packageUids[i] = info.uid;
17718        }
17719        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17720                finishedReceiver);
17721    }
17722
17723    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17724            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17725        sendResourcesChangedBroadcast(mediaStatus, replacing,
17726                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17727    }
17728
17729    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17730            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17731        int size = pkgList.length;
17732        if (size > 0) {
17733            // Send broadcasts here
17734            Bundle extras = new Bundle();
17735            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17736            if (uidArr != null) {
17737                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17738            }
17739            if (replacing) {
17740                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17741            }
17742            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17743                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17744            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17745        }
17746    }
17747
17748   /*
17749     * Look at potentially valid container ids from processCids If package
17750     * information doesn't match the one on record or package scanning fails,
17751     * the cid is added to list of removeCids. We currently don't delete stale
17752     * containers.
17753     */
17754    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17755            boolean externalStorage) {
17756        ArrayList<String> pkgList = new ArrayList<String>();
17757        Set<AsecInstallArgs> keys = processCids.keySet();
17758
17759        for (AsecInstallArgs args : keys) {
17760            String codePath = processCids.get(args);
17761            if (DEBUG_SD_INSTALL)
17762                Log.i(TAG, "Loading container : " + args.cid);
17763            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17764            try {
17765                // Make sure there are no container errors first.
17766                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17767                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17768                            + " when installing from sdcard");
17769                    continue;
17770                }
17771                // Check code path here.
17772                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17773                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17774                            + " does not match one in settings " + codePath);
17775                    continue;
17776                }
17777                // Parse package
17778                int parseFlags = mDefParseFlags;
17779                if (args.isExternalAsec()) {
17780                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17781                }
17782                if (args.isFwdLocked()) {
17783                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17784                }
17785
17786                synchronized (mInstallLock) {
17787                    PackageParser.Package pkg = null;
17788                    try {
17789                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17790                    } catch (PackageManagerException e) {
17791                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17792                    }
17793                    // Scan the package
17794                    if (pkg != null) {
17795                        /*
17796                         * TODO why is the lock being held? doPostInstall is
17797                         * called in other places without the lock. This needs
17798                         * to be straightened out.
17799                         */
17800                        // writer
17801                        synchronized (mPackages) {
17802                            retCode = PackageManager.INSTALL_SUCCEEDED;
17803                            pkgList.add(pkg.packageName);
17804                            // Post process args
17805                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17806                                    pkg.applicationInfo.uid);
17807                        }
17808                    } else {
17809                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17810                    }
17811                }
17812
17813            } finally {
17814                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17815                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17816                }
17817            }
17818        }
17819        // writer
17820        synchronized (mPackages) {
17821            // If the platform SDK has changed since the last time we booted,
17822            // we need to re-grant app permission to catch any new ones that
17823            // appear. This is really a hack, and means that apps can in some
17824            // cases get permissions that the user didn't initially explicitly
17825            // allow... it would be nice to have some better way to handle
17826            // this situation.
17827            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17828                    : mSettings.getInternalVersion();
17829            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17830                    : StorageManager.UUID_PRIVATE_INTERNAL;
17831
17832            int updateFlags = UPDATE_PERMISSIONS_ALL;
17833            if (ver.sdkVersion != mSdkVersion) {
17834                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17835                        + mSdkVersion + "; regranting permissions for external");
17836                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17837            }
17838            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17839
17840            // Yay, everything is now upgraded
17841            ver.forceCurrent();
17842
17843            // can downgrade to reader
17844            // Persist settings
17845            mSettings.writeLPr();
17846        }
17847        // Send a broadcast to let everyone know we are done processing
17848        if (pkgList.size() > 0) {
17849            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17850        }
17851    }
17852
17853   /*
17854     * Utility method to unload a list of specified containers
17855     */
17856    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17857        // Just unmount all valid containers.
17858        for (AsecInstallArgs arg : cidArgs) {
17859            synchronized (mInstallLock) {
17860                arg.doPostDeleteLI(false);
17861           }
17862       }
17863   }
17864
17865    /*
17866     * Unload packages mounted on external media. This involves deleting package
17867     * data from internal structures, sending broadcasts about disabled packages,
17868     * gc'ing to free up references, unmounting all secure containers
17869     * corresponding to packages on external media, and posting a
17870     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17871     * that we always have to post this message if status has been requested no
17872     * matter what.
17873     */
17874    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17875            final boolean reportStatus) {
17876        if (DEBUG_SD_INSTALL)
17877            Log.i(TAG, "unloading media packages");
17878        ArrayList<String> pkgList = new ArrayList<String>();
17879        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17880        final Set<AsecInstallArgs> keys = processCids.keySet();
17881        for (AsecInstallArgs args : keys) {
17882            String pkgName = args.getPackageName();
17883            if (DEBUG_SD_INSTALL)
17884                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17885            // Delete package internally
17886            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17887            synchronized (mInstallLock) {
17888                boolean res = deletePackageLI(pkgName, null, false, null,
17889                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17890                if (res) {
17891                    pkgList.add(pkgName);
17892                } else {
17893                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17894                    failedList.add(args);
17895                }
17896            }
17897        }
17898
17899        // reader
17900        synchronized (mPackages) {
17901            // We didn't update the settings after removing each package;
17902            // write them now for all packages.
17903            mSettings.writeLPr();
17904        }
17905
17906        // We have to absolutely send UPDATED_MEDIA_STATUS only
17907        // after confirming that all the receivers processed the ordered
17908        // broadcast when packages get disabled, force a gc to clean things up.
17909        // and unload all the containers.
17910        if (pkgList.size() > 0) {
17911            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17912                    new IIntentReceiver.Stub() {
17913                public void performReceive(Intent intent, int resultCode, String data,
17914                        Bundle extras, boolean ordered, boolean sticky,
17915                        int sendingUser) throws RemoteException {
17916                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17917                            reportStatus ? 1 : 0, 1, keys);
17918                    mHandler.sendMessage(msg);
17919                }
17920            });
17921        } else {
17922            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17923                    keys);
17924            mHandler.sendMessage(msg);
17925        }
17926    }
17927
17928    private void loadPrivatePackages(final VolumeInfo vol) {
17929        mHandler.post(new Runnable() {
17930            @Override
17931            public void run() {
17932                loadPrivatePackagesInner(vol);
17933            }
17934        });
17935    }
17936
17937    private void loadPrivatePackagesInner(VolumeInfo vol) {
17938        final String volumeUuid = vol.fsUuid;
17939        if (TextUtils.isEmpty(volumeUuid)) {
17940            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17941            return;
17942        }
17943
17944        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17945        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17946
17947        final VersionInfo ver;
17948        final List<PackageSetting> packages;
17949        synchronized (mPackages) {
17950            ver = mSettings.findOrCreateVersion(volumeUuid);
17951            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17952        }
17953
17954        // TODO: introduce a new concept similar to "frozen" to prevent these
17955        // apps from being launched until after data has been fully reconciled
17956        for (PackageSetting ps : packages) {
17957            synchronized (mInstallLock) {
17958                final PackageParser.Package pkg;
17959                try {
17960                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17961                    loaded.add(pkg.applicationInfo);
17962
17963                } catch (PackageManagerException e) {
17964                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17965                }
17966
17967                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17968                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17969                }
17970            }
17971        }
17972
17973        // Reconcile app data for all started/unlocked users
17974        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17975        final UserManager um = mContext.getSystemService(UserManager.class);
17976        for (UserInfo user : um.getUsers()) {
17977            final int flags;
17978            if (um.isUserUnlocked(user.id)) {
17979                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17980            } else if (um.isUserRunning(user.id)) {
17981                flags = StorageManager.FLAG_STORAGE_DE;
17982            } else {
17983                continue;
17984            }
17985
17986            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17987            reconcileAppsData(volumeUuid, user.id, flags);
17988        }
17989
17990        synchronized (mPackages) {
17991            int updateFlags = UPDATE_PERMISSIONS_ALL;
17992            if (ver.sdkVersion != mSdkVersion) {
17993                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17994                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17995                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17996            }
17997            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17998
17999            // Yay, everything is now upgraded
18000            ver.forceCurrent();
18001
18002            mSettings.writeLPr();
18003        }
18004
18005        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18006        sendResourcesChangedBroadcast(true, false, loaded, null);
18007    }
18008
18009    private void unloadPrivatePackages(final VolumeInfo vol) {
18010        mHandler.post(new Runnable() {
18011            @Override
18012            public void run() {
18013                unloadPrivatePackagesInner(vol);
18014            }
18015        });
18016    }
18017
18018    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18019        final String volumeUuid = vol.fsUuid;
18020        if (TextUtils.isEmpty(volumeUuid)) {
18021            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18022            return;
18023        }
18024
18025        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18026        synchronized (mInstallLock) {
18027        synchronized (mPackages) {
18028            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18029            for (PackageSetting ps : packages) {
18030                if (ps.pkg == null) continue;
18031
18032                final ApplicationInfo info = ps.pkg.applicationInfo;
18033                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18034                if (deletePackageLI(ps.name, null, false, null,
18035                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18036                    unloaded.add(info);
18037                } else {
18038                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18039                }
18040            }
18041
18042            mSettings.writeLPr();
18043        }
18044        }
18045
18046        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18047        sendResourcesChangedBroadcast(false, false, unloaded, null);
18048    }
18049
18050    /**
18051     * Examine all users present on given mounted volume, and destroy data
18052     * belonging to users that are no longer valid, or whose user ID has been
18053     * recycled.
18054     */
18055    private void reconcileUsers(String volumeUuid) {
18056        // TODO: also reconcile DE directories
18057        final File[] files = FileUtils
18058                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18059        for (File file : files) {
18060            if (!file.isDirectory()) continue;
18061
18062            final int userId;
18063            final UserInfo info;
18064            try {
18065                userId = Integer.parseInt(file.getName());
18066                info = sUserManager.getUserInfo(userId);
18067            } catch (NumberFormatException e) {
18068                Slog.w(TAG, "Invalid user directory " + file);
18069                continue;
18070            }
18071
18072            boolean destroyUser = false;
18073            if (info == null) {
18074                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18075                        + " because no matching user was found");
18076                destroyUser = true;
18077            } else {
18078                try {
18079                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18080                } catch (IOException e) {
18081                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18082                            + " because we failed to enforce serial number: " + e);
18083                    destroyUser = true;
18084                }
18085            }
18086
18087            if (destroyUser) {
18088                synchronized (mInstallLock) {
18089                    try {
18090                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18091                    } catch (InstallerException e) {
18092                        Slog.w(TAG, "Failed to clean up user dirs", e);
18093                    }
18094                }
18095            }
18096        }
18097    }
18098
18099    private void assertPackageKnown(String volumeUuid, String packageName)
18100            throws PackageManagerException {
18101        synchronized (mPackages) {
18102            final PackageSetting ps = mSettings.mPackages.get(packageName);
18103            if (ps == null) {
18104                throw new PackageManagerException("Package " + packageName + " is unknown");
18105            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18106                throw new PackageManagerException(
18107                        "Package " + packageName + " found on unknown volume " + volumeUuid
18108                                + "; expected volume " + ps.volumeUuid);
18109            }
18110        }
18111    }
18112
18113    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18114            throws PackageManagerException {
18115        synchronized (mPackages) {
18116            final PackageSetting ps = mSettings.mPackages.get(packageName);
18117            if (ps == null) {
18118                throw new PackageManagerException("Package " + packageName + " is unknown");
18119            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18120                throw new PackageManagerException(
18121                        "Package " + packageName + " found on unknown volume " + volumeUuid
18122                                + "; expected volume " + ps.volumeUuid);
18123            } else if (!ps.getInstalled(userId)) {
18124                throw new PackageManagerException(
18125                        "Package " + packageName + " not installed for user " + userId);
18126            }
18127        }
18128    }
18129
18130    /**
18131     * Examine all apps present on given mounted volume, and destroy apps that
18132     * aren't expected, either due to uninstallation or reinstallation on
18133     * another volume.
18134     */
18135    private void reconcileApps(String volumeUuid) {
18136        final File[] files = FileUtils
18137                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18138        for (File file : files) {
18139            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18140                    && !PackageInstallerService.isStageName(file.getName());
18141            if (!isPackage) {
18142                // Ignore entries which are not packages
18143                continue;
18144            }
18145
18146            try {
18147                final PackageLite pkg = PackageParser.parsePackageLite(file,
18148                        PackageParser.PARSE_MUST_BE_APK);
18149                assertPackageKnown(volumeUuid, pkg.packageName);
18150
18151            } catch (PackageParserException | PackageManagerException e) {
18152                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18153                synchronized (mInstallLock) {
18154                    removeCodePathLI(file);
18155                }
18156            }
18157        }
18158    }
18159
18160    /**
18161     * Reconcile all app data for the given user.
18162     * <p>
18163     * Verifies that directories exist and that ownership and labeling is
18164     * correct for all installed apps on all mounted volumes.
18165     */
18166    void reconcileAppsData(int userId, int flags) {
18167        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18168        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18169            final String volumeUuid = vol.getFsUuid();
18170            reconcileAppsData(volumeUuid, userId, flags);
18171        }
18172    }
18173
18174    /**
18175     * Reconcile all app data on given mounted volume.
18176     * <p>
18177     * Destroys app data that isn't expected, either due to uninstallation or
18178     * reinstallation on another volume.
18179     * <p>
18180     * Verifies that directories exist and that ownership and labeling is
18181     * correct for all installed apps.
18182     */
18183    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18184        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18185                + Integer.toHexString(flags));
18186
18187        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18188        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18189
18190        boolean restoreconNeeded = false;
18191
18192        // First look for stale data that doesn't belong, and check if things
18193        // have changed since we did our last restorecon
18194        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18195            if (!isUserKeyUnlocked(userId)) {
18196                throw new RuntimeException(
18197                        "Yikes, someone asked us to reconcile CE storage while " + userId
18198                                + " was still locked; this would have caused massive data loss!");
18199            }
18200
18201            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18202
18203            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18204            for (File file : files) {
18205                final String packageName = file.getName();
18206                try {
18207                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18208                } catch (PackageManagerException e) {
18209                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18210                    synchronized (mInstallLock) {
18211                        destroyAppDataLI(volumeUuid, packageName, userId,
18212                                StorageManager.FLAG_STORAGE_CE);
18213                    }
18214                }
18215            }
18216        }
18217        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18218            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18219
18220            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18221            for (File file : files) {
18222                final String packageName = file.getName();
18223                try {
18224                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18225                } catch (PackageManagerException e) {
18226                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18227                    synchronized (mInstallLock) {
18228                        destroyAppDataLI(volumeUuid, packageName, userId,
18229                                StorageManager.FLAG_STORAGE_DE);
18230                    }
18231                }
18232            }
18233        }
18234
18235        // Ensure that data directories are ready to roll for all packages
18236        // installed for this volume and user
18237        final List<PackageSetting> packages;
18238        synchronized (mPackages) {
18239            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18240        }
18241        int preparedCount = 0;
18242        for (PackageSetting ps : packages) {
18243            final String packageName = ps.name;
18244            if (ps.pkg == null) {
18245                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18246                // TODO: might be due to legacy ASEC apps; we should circle back
18247                // and reconcile again once they're scanned
18248                continue;
18249            }
18250
18251            if (ps.getInstalled(userId)) {
18252                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18253
18254                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18255                    // We may have just shuffled around app data directories, so
18256                    // prepare them one more time
18257                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18258                }
18259
18260                preparedCount++;
18261            }
18262        }
18263
18264        if (restoreconNeeded) {
18265            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18266                SELinuxMMAC.setRestoreconDone(ceDir);
18267            }
18268            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18269                SELinuxMMAC.setRestoreconDone(deDir);
18270            }
18271        }
18272
18273        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18274                + " packages; restoreconNeeded was " + restoreconNeeded);
18275    }
18276
18277    /**
18278     * Prepare app data for the given app just after it was installed or
18279     * upgraded. This method carefully only touches users that it's installed
18280     * for, and it forces a restorecon to handle any seinfo changes.
18281     * <p>
18282     * Verifies that directories exist and that ownership and labeling is
18283     * correct for all installed apps. If there is an ownership mismatch, it
18284     * will try recovering system apps by wiping data; third-party app data is
18285     * left intact.
18286     * <p>
18287     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18288     */
18289    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18290        prepareAppDataAfterInstallInternal(pkg);
18291        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18292        for (int i = 0; i < childCount; i++) {
18293            PackageParser.Package childPackage = pkg.childPackages.get(i);
18294            prepareAppDataAfterInstallInternal(childPackage);
18295        }
18296    }
18297
18298    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18299        final PackageSetting ps;
18300        synchronized (mPackages) {
18301            ps = mSettings.mPackages.get(pkg.packageName);
18302            mSettings.writeKernelMappingLPr(ps);
18303        }
18304
18305        final UserManager um = mContext.getSystemService(UserManager.class);
18306        for (UserInfo user : um.getUsers()) {
18307            final int flags;
18308            if (um.isUserUnlocked(user.id)) {
18309                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18310            } else if (um.isUserRunning(user.id)) {
18311                flags = StorageManager.FLAG_STORAGE_DE;
18312            } else {
18313                continue;
18314            }
18315
18316            if (ps.getInstalled(user.id)) {
18317                // Whenever an app changes, force a restorecon of its data
18318                // TODO: when user data is locked, mark that we're still dirty
18319                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18320            }
18321        }
18322    }
18323
18324    /**
18325     * Prepare app data for the given app.
18326     * <p>
18327     * Verifies that directories exist and that ownership and labeling is
18328     * correct for all installed apps. If there is an ownership mismatch, this
18329     * will try recovering system apps by wiping data; third-party app data is
18330     * left intact.
18331     */
18332    private void prepareAppData(String volumeUuid, int userId, int flags,
18333            PackageParser.Package pkg, boolean restoreconNeeded) {
18334        if (DEBUG_APP_DATA) {
18335            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18336                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18337        }
18338
18339        final String packageName = pkg.packageName;
18340        final ApplicationInfo app = pkg.applicationInfo;
18341        final int appId = UserHandle.getAppId(app.uid);
18342
18343        Preconditions.checkNotNull(app.seinfo);
18344
18345        synchronized (mInstallLock) {
18346            try {
18347                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18348                        appId, app.seinfo, app.targetSdkVersion);
18349            } catch (InstallerException e) {
18350                if (app.isSystemApp()) {
18351                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18352                            + ", but trying to recover: " + e);
18353                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18354                    try {
18355                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18356                                appId, app.seinfo, app.targetSdkVersion);
18357                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18358                    } catch (InstallerException e2) {
18359                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18360                    }
18361                } else {
18362                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18363                }
18364            }
18365
18366            if (restoreconNeeded) {
18367                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18368            }
18369
18370            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18371                // Create a native library symlink only if we have native libraries
18372                // and if the native libraries are 32 bit libraries. We do not provide
18373                // this symlink for 64 bit libraries.
18374                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18375                    final String nativeLibPath = app.nativeLibraryDir;
18376                    try {
18377                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18378                                nativeLibPath, userId);
18379                    } catch (InstallerException e) {
18380                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18381                    }
18382                }
18383            }
18384        }
18385    }
18386
18387    /**
18388     * For system apps on non-FBE devices, this method migrates any existing
18389     * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by
18390     * the app.
18391     */
18392    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18393        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18394                && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
18395            final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted()
18396                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18397            synchronized (mInstallLock) {
18398                try {
18399                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18400                } catch (InstallerException e) {
18401                    logCriticalInfo(Log.WARN,
18402                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18403                }
18404            }
18405            return true;
18406        } else {
18407            return false;
18408        }
18409    }
18410
18411    private void unfreezePackage(String packageName) {
18412        synchronized (mPackages) {
18413            final PackageSetting ps = mSettings.mPackages.get(packageName);
18414            if (ps != null) {
18415                ps.frozen = false;
18416            }
18417        }
18418    }
18419
18420    @Override
18421    public int movePackage(final String packageName, final String volumeUuid) {
18422        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18423
18424        final int moveId = mNextMoveId.getAndIncrement();
18425        mHandler.post(new Runnable() {
18426            @Override
18427            public void run() {
18428                try {
18429                    movePackageInternal(packageName, volumeUuid, moveId);
18430                } catch (PackageManagerException e) {
18431                    Slog.w(TAG, "Failed to move " + packageName, e);
18432                    mMoveCallbacks.notifyStatusChanged(moveId,
18433                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18434                }
18435            }
18436        });
18437        return moveId;
18438    }
18439
18440    private void movePackageInternal(final String packageName, final String volumeUuid,
18441            final int moveId) throws PackageManagerException {
18442        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18443        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18444        final PackageManager pm = mContext.getPackageManager();
18445
18446        final boolean currentAsec;
18447        final String currentVolumeUuid;
18448        final File codeFile;
18449        final String installerPackageName;
18450        final String packageAbiOverride;
18451        final int appId;
18452        final String seinfo;
18453        final String label;
18454        final int targetSdkVersion;
18455
18456        // reader
18457        synchronized (mPackages) {
18458            final PackageParser.Package pkg = mPackages.get(packageName);
18459            final PackageSetting ps = mSettings.mPackages.get(packageName);
18460            if (pkg == null || ps == null) {
18461                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18462            }
18463
18464            if (pkg.applicationInfo.isSystemApp()) {
18465                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18466                        "Cannot move system application");
18467            }
18468
18469            if (pkg.applicationInfo.isExternalAsec()) {
18470                currentAsec = true;
18471                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18472            } else if (pkg.applicationInfo.isForwardLocked()) {
18473                currentAsec = true;
18474                currentVolumeUuid = "forward_locked";
18475            } else {
18476                currentAsec = false;
18477                currentVolumeUuid = ps.volumeUuid;
18478
18479                final File probe = new File(pkg.codePath);
18480                final File probeOat = new File(probe, "oat");
18481                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18482                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18483                            "Move only supported for modern cluster style installs");
18484                }
18485            }
18486
18487            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18488                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18489                        "Package already moved to " + volumeUuid);
18490            }
18491            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18492                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18493                        "Device admin cannot be moved");
18494            }
18495
18496            if (ps.frozen) {
18497                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18498                        "Failed to move already frozen package");
18499            }
18500            ps.frozen = true;
18501
18502            codeFile = new File(pkg.codePath);
18503            installerPackageName = ps.installerPackageName;
18504            packageAbiOverride = ps.cpuAbiOverrideString;
18505            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18506            seinfo = pkg.applicationInfo.seinfo;
18507            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18508            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18509        }
18510
18511        // Now that we're guarded by frozen state, kill app during move
18512        final long token = Binder.clearCallingIdentity();
18513        try {
18514            killApplication(packageName, appId, "move pkg");
18515        } finally {
18516            Binder.restoreCallingIdentity(token);
18517        }
18518
18519        final Bundle extras = new Bundle();
18520        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18521        extras.putString(Intent.EXTRA_TITLE, label);
18522        mMoveCallbacks.notifyCreated(moveId, extras);
18523
18524        int installFlags;
18525        final boolean moveCompleteApp;
18526        final File measurePath;
18527
18528        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18529            installFlags = INSTALL_INTERNAL;
18530            moveCompleteApp = !currentAsec;
18531            measurePath = Environment.getDataAppDirectory(volumeUuid);
18532        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18533            installFlags = INSTALL_EXTERNAL;
18534            moveCompleteApp = false;
18535            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18536        } else {
18537            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18538            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18539                    || !volume.isMountedWritable()) {
18540                unfreezePackage(packageName);
18541                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18542                        "Move location not mounted private volume");
18543            }
18544
18545            Preconditions.checkState(!currentAsec);
18546
18547            installFlags = INSTALL_INTERNAL;
18548            moveCompleteApp = true;
18549            measurePath = Environment.getDataAppDirectory(volumeUuid);
18550        }
18551
18552        final PackageStats stats = new PackageStats(null, -1);
18553        synchronized (mInstaller) {
18554            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18555                unfreezePackage(packageName);
18556                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18557                        "Failed to measure package size");
18558            }
18559        }
18560
18561        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18562                + stats.dataSize);
18563
18564        final long startFreeBytes = measurePath.getFreeSpace();
18565        final long sizeBytes;
18566        if (moveCompleteApp) {
18567            sizeBytes = stats.codeSize + stats.dataSize;
18568        } else {
18569            sizeBytes = stats.codeSize;
18570        }
18571
18572        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18573            unfreezePackage(packageName);
18574            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18575                    "Not enough free space to move");
18576        }
18577
18578        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18579
18580        final CountDownLatch installedLatch = new CountDownLatch(1);
18581        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18582            @Override
18583            public void onUserActionRequired(Intent intent) throws RemoteException {
18584                throw new IllegalStateException();
18585            }
18586
18587            @Override
18588            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18589                    Bundle extras) throws RemoteException {
18590                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18591                        + PackageManager.installStatusToString(returnCode, msg));
18592
18593                installedLatch.countDown();
18594
18595                // Regardless of success or failure of the move operation,
18596                // always unfreeze the package
18597                unfreezePackage(packageName);
18598
18599                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18600                switch (status) {
18601                    case PackageInstaller.STATUS_SUCCESS:
18602                        mMoveCallbacks.notifyStatusChanged(moveId,
18603                                PackageManager.MOVE_SUCCEEDED);
18604                        break;
18605                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18606                        mMoveCallbacks.notifyStatusChanged(moveId,
18607                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18608                        break;
18609                    default:
18610                        mMoveCallbacks.notifyStatusChanged(moveId,
18611                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18612                        break;
18613                }
18614            }
18615        };
18616
18617        final MoveInfo move;
18618        if (moveCompleteApp) {
18619            // Kick off a thread to report progress estimates
18620            new Thread() {
18621                @Override
18622                public void run() {
18623                    while (true) {
18624                        try {
18625                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18626                                break;
18627                            }
18628                        } catch (InterruptedException ignored) {
18629                        }
18630
18631                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18632                        final int progress = 10 + (int) MathUtils.constrain(
18633                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18634                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18635                    }
18636                }
18637            }.start();
18638
18639            final String dataAppName = codeFile.getName();
18640            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18641                    dataAppName, appId, seinfo, targetSdkVersion);
18642        } else {
18643            move = null;
18644        }
18645
18646        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18647
18648        final Message msg = mHandler.obtainMessage(INIT_COPY);
18649        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18650        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18651                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18652                packageAbiOverride, null);
18653        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18654        msg.obj = params;
18655
18656        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18657                System.identityHashCode(msg.obj));
18658        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18659                System.identityHashCode(msg.obj));
18660
18661        mHandler.sendMessage(msg);
18662    }
18663
18664    @Override
18665    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18666        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18667
18668        final int realMoveId = mNextMoveId.getAndIncrement();
18669        final Bundle extras = new Bundle();
18670        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18671        mMoveCallbacks.notifyCreated(realMoveId, extras);
18672
18673        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18674            @Override
18675            public void onCreated(int moveId, Bundle extras) {
18676                // Ignored
18677            }
18678
18679            @Override
18680            public void onStatusChanged(int moveId, int status, long estMillis) {
18681                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18682            }
18683        };
18684
18685        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18686        storage.setPrimaryStorageUuid(volumeUuid, callback);
18687        return realMoveId;
18688    }
18689
18690    @Override
18691    public int getMoveStatus(int moveId) {
18692        mContext.enforceCallingOrSelfPermission(
18693                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18694        return mMoveCallbacks.mLastStatus.get(moveId);
18695    }
18696
18697    @Override
18698    public void registerMoveCallback(IPackageMoveObserver callback) {
18699        mContext.enforceCallingOrSelfPermission(
18700                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18701        mMoveCallbacks.register(callback);
18702    }
18703
18704    @Override
18705    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18706        mContext.enforceCallingOrSelfPermission(
18707                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18708        mMoveCallbacks.unregister(callback);
18709    }
18710
18711    @Override
18712    public boolean setInstallLocation(int loc) {
18713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18714                null);
18715        if (getInstallLocation() == loc) {
18716            return true;
18717        }
18718        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18719                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18720            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18721                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18722            return true;
18723        }
18724        return false;
18725   }
18726
18727    @Override
18728    public int getInstallLocation() {
18729        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18730                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18731                PackageHelper.APP_INSTALL_AUTO);
18732    }
18733
18734    /** Called by UserManagerService */
18735    void cleanUpUser(UserManagerService userManager, int userHandle) {
18736        synchronized (mPackages) {
18737            mDirtyUsers.remove(userHandle);
18738            mUserNeedsBadging.delete(userHandle);
18739            mSettings.removeUserLPw(userHandle);
18740            mPendingBroadcasts.remove(userHandle);
18741            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18742        }
18743        synchronized (mInstallLock) {
18744            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18745            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18746                final String volumeUuid = vol.getFsUuid();
18747                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18748                try {
18749                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18750                } catch (InstallerException e) {
18751                    Slog.w(TAG, "Failed to remove user data", e);
18752                }
18753            }
18754            synchronized (mPackages) {
18755                removeUnusedPackagesLILPw(userManager, userHandle);
18756            }
18757        }
18758    }
18759
18760    /**
18761     * We're removing userHandle and would like to remove any downloaded packages
18762     * that are no longer in use by any other user.
18763     * @param userHandle the user being removed
18764     */
18765    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18766        final boolean DEBUG_CLEAN_APKS = false;
18767        int [] users = userManager.getUserIds();
18768        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18769        while (psit.hasNext()) {
18770            PackageSetting ps = psit.next();
18771            if (ps.pkg == null) {
18772                continue;
18773            }
18774            final String packageName = ps.pkg.packageName;
18775            // Skip over if system app
18776            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18777                continue;
18778            }
18779            if (DEBUG_CLEAN_APKS) {
18780                Slog.i(TAG, "Checking package " + packageName);
18781            }
18782            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18783            if (keep) {
18784                if (DEBUG_CLEAN_APKS) {
18785                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18786                }
18787            } else {
18788                for (int i = 0; i < users.length; i++) {
18789                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18790                        keep = true;
18791                        if (DEBUG_CLEAN_APKS) {
18792                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18793                                    + users[i]);
18794                        }
18795                        break;
18796                    }
18797                }
18798            }
18799            if (!keep) {
18800                if (DEBUG_CLEAN_APKS) {
18801                    Slog.i(TAG, "  Removing package " + packageName);
18802                }
18803                mHandler.post(new Runnable() {
18804                    public void run() {
18805                        deletePackageX(packageName, userHandle, 0);
18806                    } //end run
18807                });
18808            }
18809        }
18810    }
18811
18812    /** Called by UserManagerService */
18813    void createNewUser(int userHandle) {
18814        synchronized (mInstallLock) {
18815            try {
18816                mInstaller.createUserConfig(userHandle);
18817            } catch (InstallerException e) {
18818                Slog.w(TAG, "Failed to create user config", e);
18819            }
18820            mSettings.createNewUserLI(this, mInstaller, userHandle);
18821        }
18822        synchronized (mPackages) {
18823            applyFactoryDefaultBrowserLPw(userHandle);
18824            primeDomainVerificationsLPw(userHandle);
18825        }
18826    }
18827
18828    void newUserCreated(final int userHandle) {
18829        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18830        // If permission review for legacy apps is required, we represent
18831        // dagerous permissions for such apps as always granted runtime
18832        // permissions to keep per user flag state whether review is needed.
18833        // Hence, if a new user is added we have to propagate dangerous
18834        // permission grants for these legacy apps.
18835        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18836            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18837                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18838        }
18839    }
18840
18841    @Override
18842    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18843        mContext.enforceCallingOrSelfPermission(
18844                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18845                "Only package verification agents can read the verifier device identity");
18846
18847        synchronized (mPackages) {
18848            return mSettings.getVerifierDeviceIdentityLPw();
18849        }
18850    }
18851
18852    @Override
18853    public void setPermissionEnforced(String permission, boolean enforced) {
18854        // TODO: Now that we no longer change GID for storage, this should to away.
18855        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18856                "setPermissionEnforced");
18857        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18858            synchronized (mPackages) {
18859                if (mSettings.mReadExternalStorageEnforced == null
18860                        || mSettings.mReadExternalStorageEnforced != enforced) {
18861                    mSettings.mReadExternalStorageEnforced = enforced;
18862                    mSettings.writeLPr();
18863                }
18864            }
18865            // kill any non-foreground processes so we restart them and
18866            // grant/revoke the GID.
18867            final IActivityManager am = ActivityManagerNative.getDefault();
18868            if (am != null) {
18869                final long token = Binder.clearCallingIdentity();
18870                try {
18871                    am.killProcessesBelowForeground("setPermissionEnforcement");
18872                } catch (RemoteException e) {
18873                } finally {
18874                    Binder.restoreCallingIdentity(token);
18875                }
18876            }
18877        } else {
18878            throw new IllegalArgumentException("No selective enforcement for " + permission);
18879        }
18880    }
18881
18882    @Override
18883    @Deprecated
18884    public boolean isPermissionEnforced(String permission) {
18885        return true;
18886    }
18887
18888    @Override
18889    public boolean isStorageLow() {
18890        final long token = Binder.clearCallingIdentity();
18891        try {
18892            final DeviceStorageMonitorInternal
18893                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18894            if (dsm != null) {
18895                return dsm.isMemoryLow();
18896            } else {
18897                return false;
18898            }
18899        } finally {
18900            Binder.restoreCallingIdentity(token);
18901        }
18902    }
18903
18904    @Override
18905    public IPackageInstaller getPackageInstaller() {
18906        return mInstallerService;
18907    }
18908
18909    private boolean userNeedsBadging(int userId) {
18910        int index = mUserNeedsBadging.indexOfKey(userId);
18911        if (index < 0) {
18912            final UserInfo userInfo;
18913            final long token = Binder.clearCallingIdentity();
18914            try {
18915                userInfo = sUserManager.getUserInfo(userId);
18916            } finally {
18917                Binder.restoreCallingIdentity(token);
18918            }
18919            final boolean b;
18920            if (userInfo != null && userInfo.isManagedProfile()) {
18921                b = true;
18922            } else {
18923                b = false;
18924            }
18925            mUserNeedsBadging.put(userId, b);
18926            return b;
18927        }
18928        return mUserNeedsBadging.valueAt(index);
18929    }
18930
18931    @Override
18932    public KeySet getKeySetByAlias(String packageName, String alias) {
18933        if (packageName == null || alias == null) {
18934            return null;
18935        }
18936        synchronized(mPackages) {
18937            final PackageParser.Package pkg = mPackages.get(packageName);
18938            if (pkg == null) {
18939                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18940                throw new IllegalArgumentException("Unknown package: " + packageName);
18941            }
18942            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18943            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18944        }
18945    }
18946
18947    @Override
18948    public KeySet getSigningKeySet(String packageName) {
18949        if (packageName == null) {
18950            return null;
18951        }
18952        synchronized(mPackages) {
18953            final PackageParser.Package pkg = mPackages.get(packageName);
18954            if (pkg == null) {
18955                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18956                throw new IllegalArgumentException("Unknown package: " + packageName);
18957            }
18958            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18959                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18960                throw new SecurityException("May not access signing KeySet of other apps.");
18961            }
18962            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18963            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18964        }
18965    }
18966
18967    @Override
18968    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18969        if (packageName == null || ks == null) {
18970            return false;
18971        }
18972        synchronized(mPackages) {
18973            final PackageParser.Package pkg = mPackages.get(packageName);
18974            if (pkg == null) {
18975                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18976                throw new IllegalArgumentException("Unknown package: " + packageName);
18977            }
18978            IBinder ksh = ks.getToken();
18979            if (ksh instanceof KeySetHandle) {
18980                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18981                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18982            }
18983            return false;
18984        }
18985    }
18986
18987    @Override
18988    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18989        if (packageName == null || ks == null) {
18990            return false;
18991        }
18992        synchronized(mPackages) {
18993            final PackageParser.Package pkg = mPackages.get(packageName);
18994            if (pkg == null) {
18995                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18996                throw new IllegalArgumentException("Unknown package: " + packageName);
18997            }
18998            IBinder ksh = ks.getToken();
18999            if (ksh instanceof KeySetHandle) {
19000                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19001                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19002            }
19003            return false;
19004        }
19005    }
19006
19007    private void deletePackageIfUnusedLPr(final String packageName) {
19008        PackageSetting ps = mSettings.mPackages.get(packageName);
19009        if (ps == null) {
19010            return;
19011        }
19012        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19013            // TODO Implement atomic delete if package is unused
19014            // It is currently possible that the package will be deleted even if it is installed
19015            // after this method returns.
19016            mHandler.post(new Runnable() {
19017                public void run() {
19018                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19019                }
19020            });
19021        }
19022    }
19023
19024    /**
19025     * Check and throw if the given before/after packages would be considered a
19026     * downgrade.
19027     */
19028    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19029            throws PackageManagerException {
19030        if (after.versionCode < before.mVersionCode) {
19031            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19032                    "Update version code " + after.versionCode + " is older than current "
19033                    + before.mVersionCode);
19034        } else if (after.versionCode == before.mVersionCode) {
19035            if (after.baseRevisionCode < before.baseRevisionCode) {
19036                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19037                        "Update base revision code " + after.baseRevisionCode
19038                        + " is older than current " + before.baseRevisionCode);
19039            }
19040
19041            if (!ArrayUtils.isEmpty(after.splitNames)) {
19042                for (int i = 0; i < after.splitNames.length; i++) {
19043                    final String splitName = after.splitNames[i];
19044                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19045                    if (j != -1) {
19046                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19047                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19048                                    "Update split " + splitName + " revision code "
19049                                    + after.splitRevisionCodes[i] + " is older than current "
19050                                    + before.splitRevisionCodes[j]);
19051                        }
19052                    }
19053                }
19054            }
19055        }
19056    }
19057
19058    private static class MoveCallbacks extends Handler {
19059        private static final int MSG_CREATED = 1;
19060        private static final int MSG_STATUS_CHANGED = 2;
19061
19062        private final RemoteCallbackList<IPackageMoveObserver>
19063                mCallbacks = new RemoteCallbackList<>();
19064
19065        private final SparseIntArray mLastStatus = new SparseIntArray();
19066
19067        public MoveCallbacks(Looper looper) {
19068            super(looper);
19069        }
19070
19071        public void register(IPackageMoveObserver callback) {
19072            mCallbacks.register(callback);
19073        }
19074
19075        public void unregister(IPackageMoveObserver callback) {
19076            mCallbacks.unregister(callback);
19077        }
19078
19079        @Override
19080        public void handleMessage(Message msg) {
19081            final SomeArgs args = (SomeArgs) msg.obj;
19082            final int n = mCallbacks.beginBroadcast();
19083            for (int i = 0; i < n; i++) {
19084                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19085                try {
19086                    invokeCallback(callback, msg.what, args);
19087                } catch (RemoteException ignored) {
19088                }
19089            }
19090            mCallbacks.finishBroadcast();
19091            args.recycle();
19092        }
19093
19094        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19095                throws RemoteException {
19096            switch (what) {
19097                case MSG_CREATED: {
19098                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19099                    break;
19100                }
19101                case MSG_STATUS_CHANGED: {
19102                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19103                    break;
19104                }
19105            }
19106        }
19107
19108        private void notifyCreated(int moveId, Bundle extras) {
19109            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19110
19111            final SomeArgs args = SomeArgs.obtain();
19112            args.argi1 = moveId;
19113            args.arg2 = extras;
19114            obtainMessage(MSG_CREATED, args).sendToTarget();
19115        }
19116
19117        private void notifyStatusChanged(int moveId, int status) {
19118            notifyStatusChanged(moveId, status, -1);
19119        }
19120
19121        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19122            Slog.v(TAG, "Move " + moveId + " status " + status);
19123
19124            final SomeArgs args = SomeArgs.obtain();
19125            args.argi1 = moveId;
19126            args.argi2 = status;
19127            args.arg3 = estMillis;
19128            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19129
19130            synchronized (mLastStatus) {
19131                mLastStatus.put(moveId, status);
19132            }
19133        }
19134    }
19135
19136    private final static class OnPermissionChangeListeners extends Handler {
19137        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19138
19139        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19140                new RemoteCallbackList<>();
19141
19142        public OnPermissionChangeListeners(Looper looper) {
19143            super(looper);
19144        }
19145
19146        @Override
19147        public void handleMessage(Message msg) {
19148            switch (msg.what) {
19149                case MSG_ON_PERMISSIONS_CHANGED: {
19150                    final int uid = msg.arg1;
19151                    handleOnPermissionsChanged(uid);
19152                } break;
19153            }
19154        }
19155
19156        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19157            mPermissionListeners.register(listener);
19158
19159        }
19160
19161        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19162            mPermissionListeners.unregister(listener);
19163        }
19164
19165        public void onPermissionsChanged(int uid) {
19166            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19167                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19168            }
19169        }
19170
19171        private void handleOnPermissionsChanged(int uid) {
19172            final int count = mPermissionListeners.beginBroadcast();
19173            try {
19174                for (int i = 0; i < count; i++) {
19175                    IOnPermissionsChangeListener callback = mPermissionListeners
19176                            .getBroadcastItem(i);
19177                    try {
19178                        callback.onPermissionsChanged(uid);
19179                    } catch (RemoteException e) {
19180                        Log.e(TAG, "Permission listener is dead", e);
19181                    }
19182                }
19183            } finally {
19184                mPermissionListeners.finishBroadcast();
19185            }
19186        }
19187    }
19188
19189    private class PackageManagerInternalImpl extends PackageManagerInternal {
19190        @Override
19191        public void setLocationPackagesProvider(PackagesProvider provider) {
19192            synchronized (mPackages) {
19193                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19194            }
19195        }
19196
19197        @Override
19198        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19199            synchronized (mPackages) {
19200                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19201            }
19202        }
19203
19204        @Override
19205        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19206            synchronized (mPackages) {
19207                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19208            }
19209        }
19210
19211        @Override
19212        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19213            synchronized (mPackages) {
19214                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19215            }
19216        }
19217
19218        @Override
19219        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19220            synchronized (mPackages) {
19221                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19222            }
19223        }
19224
19225        @Override
19226        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19227            synchronized (mPackages) {
19228                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19229            }
19230        }
19231
19232        @Override
19233        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19234            synchronized (mPackages) {
19235                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19236                        packageName, userId);
19237            }
19238        }
19239
19240        @Override
19241        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19242            synchronized (mPackages) {
19243                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19244                        packageName, userId);
19245            }
19246        }
19247
19248        @Override
19249        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19250            synchronized (mPackages) {
19251                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19252                        packageName, userId);
19253            }
19254        }
19255
19256        @Override
19257        public void setKeepUninstalledPackages(final List<String> packageList) {
19258            Preconditions.checkNotNull(packageList);
19259            List<String> removedFromList = null;
19260            synchronized (mPackages) {
19261                if (mKeepUninstalledPackages != null) {
19262                    final int packagesCount = mKeepUninstalledPackages.size();
19263                    for (int i = 0; i < packagesCount; i++) {
19264                        String oldPackage = mKeepUninstalledPackages.get(i);
19265                        if (packageList != null && packageList.contains(oldPackage)) {
19266                            continue;
19267                        }
19268                        if (removedFromList == null) {
19269                            removedFromList = new ArrayList<>();
19270                        }
19271                        removedFromList.add(oldPackage);
19272                    }
19273                }
19274                mKeepUninstalledPackages = new ArrayList<>(packageList);
19275                if (removedFromList != null) {
19276                    final int removedCount = removedFromList.size();
19277                    for (int i = 0; i < removedCount; i++) {
19278                        deletePackageIfUnusedLPr(removedFromList.get(i));
19279                    }
19280                }
19281            }
19282        }
19283
19284        @Override
19285        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19286            synchronized (mPackages) {
19287                // If we do not support permission review, done.
19288                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19289                    return false;
19290                }
19291
19292                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19293                if (packageSetting == null) {
19294                    return false;
19295                }
19296
19297                // Permission review applies only to apps not supporting the new permission model.
19298                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19299                    return false;
19300                }
19301
19302                // Legacy apps have the permission and get user consent on launch.
19303                PermissionsState permissionsState = packageSetting.getPermissionsState();
19304                return permissionsState.isPermissionReviewRequired(userId);
19305            }
19306        }
19307
19308        @Override
19309        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19310            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19311        }
19312
19313        @Override
19314        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19315                int userId) {
19316            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19317        }
19318    }
19319
19320    @Override
19321    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19322        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19323        synchronized (mPackages) {
19324            final long identity = Binder.clearCallingIdentity();
19325            try {
19326                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19327                        packageNames, userId);
19328            } finally {
19329                Binder.restoreCallingIdentity(identity);
19330            }
19331        }
19332    }
19333
19334    private static void enforceSystemOrPhoneCaller(String tag) {
19335        int callingUid = Binder.getCallingUid();
19336        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19337            throw new SecurityException(
19338                    "Cannot call " + tag + " from UID " + callingUid);
19339        }
19340    }
19341
19342    boolean isHistoricalPackageUsageAvailable() {
19343        return mPackageUsage.isHistoricalPackageUsageAvailable();
19344    }
19345
19346    /**
19347     * Return a <b>copy</b> of the collection of packages known to the package manager.
19348     * @return A copy of the values of mPackages.
19349     */
19350    Collection<PackageParser.Package> getPackages() {
19351        synchronized (mPackages) {
19352            return new ArrayList<>(mPackages.values());
19353        }
19354    }
19355}
19356