PackageManagerService.java revision e8498cd0066113068f2b0294144837546f213bd1
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.IDevicePolicyManager;
107import android.app.backup.IBackupManager;
108import android.content.BroadcastReceiver;
109import android.content.ComponentName;
110import android.content.Context;
111import android.content.IIntentReceiver;
112import android.content.Intent;
113import android.content.IntentFilter;
114import android.content.IntentSender;
115import android.content.IntentSender.SendIntentException;
116import android.content.ServiceConnection;
117import android.content.pm.ActivityInfo;
118import android.content.pm.ApplicationInfo;
119import android.content.pm.AppsQueryHelper;
120import android.content.pm.ComponentInfo;
121import android.content.pm.EphemeralApplicationInfo;
122import android.content.pm.EphemeralResolveInfo;
123import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
124import android.content.pm.FeatureInfo;
125import android.content.pm.IOnPermissionsChangeListener;
126import android.content.pm.IPackageDataObserver;
127import android.content.pm.IPackageDeleteObserver;
128import android.content.pm.IPackageDeleteObserver2;
129import android.content.pm.IPackageInstallObserver2;
130import android.content.pm.IPackageInstaller;
131import android.content.pm.IPackageManager;
132import android.content.pm.IPackageMoveObserver;
133import android.content.pm.IPackageStatsObserver;
134import android.content.pm.InstrumentationInfo;
135import android.content.pm.IntentFilterVerificationInfo;
136import android.content.pm.KeySet;
137import android.content.pm.PackageCleanItem;
138import android.content.pm.PackageInfo;
139import android.content.pm.PackageInfoLite;
140import android.content.pm.PackageInstaller;
141import android.content.pm.PackageManager;
142import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
143import android.content.pm.PackageManagerInternal;
144import android.content.pm.PackageParser;
145import android.content.pm.PackageParser.ActivityIntentInfo;
146import android.content.pm.PackageParser.PackageLite;
147import android.content.pm.PackageParser.PackageParserException;
148import android.content.pm.PackageStats;
149import android.content.pm.PackageUserState;
150import android.content.pm.ParceledListSlice;
151import android.content.pm.PermissionGroupInfo;
152import android.content.pm.PermissionInfo;
153import android.content.pm.ProviderInfo;
154import android.content.pm.ResolveInfo;
155import android.content.pm.ServiceInfo;
156import android.content.pm.Signature;
157import android.content.pm.UserInfo;
158import android.content.pm.VerifierDeviceIdentity;
159import android.content.pm.VerifierInfo;
160import android.content.res.Resources;
161import android.graphics.Bitmap;
162import android.hardware.display.DisplayManager;
163import android.net.Uri;
164import android.os.Binder;
165import android.os.Build;
166import android.os.Bundle;
167import android.os.Debug;
168import android.os.Environment;
169import android.os.Environment.UserEnvironment;
170import android.os.FileUtils;
171import android.os.Handler;
172import android.os.IBinder;
173import android.os.Looper;
174import android.os.Message;
175import android.os.Parcel;
176import android.os.ParcelFileDescriptor;
177import android.os.Parcelable;
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.isFileBasedEncryptionEnabled()) {
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 = queryIntentReceivers(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 = queryIntentActivities(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 = queryIntentReceivers(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 = queryIntentServices(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 = queryIntentActivities(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 = queryIntentActivities(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 = queryIntentActivities(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 List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3039        // reader
3040        synchronized (mPackages) {
3041            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3042            for (BasePermission p : mSettings.mPermissions.values()) {
3043                if (group == null) {
3044                    if (p.perm == null || p.perm.info.group == null) {
3045                        out.add(generatePermissionInfo(p, flags));
3046                    }
3047                } else {
3048                    if (p.perm != null && group.equals(p.perm.info.group)) {
3049                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3050                    }
3051                }
3052            }
3053
3054            if (out.size() > 0) {
3055                return out;
3056            }
3057            return mPermissionGroups.containsKey(group) ? out : null;
3058        }
3059    }
3060
3061    @Override
3062    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3063        // reader
3064        synchronized (mPackages) {
3065            return PackageParser.generatePermissionGroupInfo(
3066                    mPermissionGroups.get(name), flags);
3067        }
3068    }
3069
3070    @Override
3071    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3072        // reader
3073        synchronized (mPackages) {
3074            final int N = mPermissionGroups.size();
3075            ArrayList<PermissionGroupInfo> out
3076                    = new ArrayList<PermissionGroupInfo>(N);
3077            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3078                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3079            }
3080            return out;
3081        }
3082    }
3083
3084    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3085            int userId) {
3086        if (!sUserManager.exists(userId)) return null;
3087        PackageSetting ps = mSettings.mPackages.get(packageName);
3088        if (ps != null) {
3089            if (ps.pkg == null) {
3090                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3091                        flags, userId);
3092                if (pInfo != null) {
3093                    return pInfo.applicationInfo;
3094                }
3095                return null;
3096            }
3097            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3098                    ps.readUserState(userId), userId);
3099        }
3100        return null;
3101    }
3102
3103    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3104            int userId) {
3105        if (!sUserManager.exists(userId)) return null;
3106        PackageSetting ps = mSettings.mPackages.get(packageName);
3107        if (ps != null) {
3108            PackageParser.Package pkg = ps.pkg;
3109            if (pkg == null) {
3110                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3111                    return null;
3112                }
3113                // Only data remains, so we aren't worried about code paths
3114                pkg = new PackageParser.Package(packageName);
3115                pkg.applicationInfo.packageName = packageName;
3116                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3117                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3118                pkg.applicationInfo.uid = ps.appId;
3119                pkg.applicationInfo.initForUser(userId);
3120                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3121                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3122            }
3123            return generatePackageInfo(pkg, flags, userId);
3124        }
3125        return null;
3126    }
3127
3128    @Override
3129    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3130        if (!sUserManager.exists(userId)) return null;
3131        flags = updateFlagsForApplication(flags, userId, packageName);
3132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3133                false /* requireFullPermission */, false /* checkShell */, "get application info");
3134        // writer
3135        synchronized (mPackages) {
3136            PackageParser.Package p = mPackages.get(packageName);
3137            if (DEBUG_PACKAGE_INFO) Log.v(
3138                    TAG, "getApplicationInfo " + packageName
3139                    + ": " + p);
3140            if (p != null) {
3141                PackageSetting ps = mSettings.mPackages.get(packageName);
3142                if (ps == null) return null;
3143                // Note: isEnabledLP() does not apply here - always return info
3144                return PackageParser.generateApplicationInfo(
3145                        p, flags, ps.readUserState(userId), userId);
3146            }
3147            if ("android".equals(packageName)||"system".equals(packageName)) {
3148                return mAndroidApplication;
3149            }
3150            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3151                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3152            }
3153        }
3154        return null;
3155    }
3156
3157    @Override
3158    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3159            final IPackageDataObserver observer) {
3160        mContext.enforceCallingOrSelfPermission(
3161                android.Manifest.permission.CLEAR_APP_CACHE, null);
3162        // Queue up an async operation since clearing cache may take a little while.
3163        mHandler.post(new Runnable() {
3164            public void run() {
3165                mHandler.removeCallbacks(this);
3166                boolean success = true;
3167                synchronized (mInstallLock) {
3168                    try {
3169                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3170                    } catch (InstallerException e) {
3171                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3172                        success = false;
3173                    }
3174                }
3175                if (observer != null) {
3176                    try {
3177                        observer.onRemoveCompleted(null, success);
3178                    } catch (RemoteException e) {
3179                        Slog.w(TAG, "RemoveException when invoking call back");
3180                    }
3181                }
3182            }
3183        });
3184    }
3185
3186    @Override
3187    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3188            final IntentSender pi) {
3189        mContext.enforceCallingOrSelfPermission(
3190                android.Manifest.permission.CLEAR_APP_CACHE, null);
3191        // Queue up an async operation since clearing cache may take a little while.
3192        mHandler.post(new Runnable() {
3193            public void run() {
3194                mHandler.removeCallbacks(this);
3195                boolean success = true;
3196                synchronized (mInstallLock) {
3197                    try {
3198                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3199                    } catch (InstallerException e) {
3200                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3201                        success = false;
3202                    }
3203                }
3204                if(pi != null) {
3205                    try {
3206                        // Callback via pending intent
3207                        int code = success ? 1 : 0;
3208                        pi.sendIntent(null, code, null,
3209                                null, null);
3210                    } catch (SendIntentException e1) {
3211                        Slog.i(TAG, "Failed to send pending intent");
3212                    }
3213                }
3214            }
3215        });
3216    }
3217
3218    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3219        synchronized (mInstallLock) {
3220            try {
3221                mInstaller.freeCache(volumeUuid, freeStorageSize);
3222            } catch (InstallerException e) {
3223                throw new IOException("Failed to free enough space", e);
3224            }
3225        }
3226    }
3227
3228    /**
3229     * Return if the user key is currently unlocked.
3230     */
3231    private boolean isUserKeyUnlocked(int userId) {
3232        if (StorageManager.isFileBasedEncryptionEnabled()) {
3233            final IMountService mount = IMountService.Stub
3234                    .asInterface(ServiceManager.getService("mount"));
3235            if (mount == null) {
3236                Slog.w(TAG, "Early during boot, assuming locked");
3237                return false;
3238            }
3239            final long token = Binder.clearCallingIdentity();
3240            try {
3241                return mount.isUserKeyUnlocked(userId);
3242            } catch (RemoteException e) {
3243                throw e.rethrowAsRuntimeException();
3244            } finally {
3245                Binder.restoreCallingIdentity(token);
3246            }
3247        } else {
3248            return true;
3249        }
3250    }
3251
3252    /**
3253     * Update given flags based on encryption status of current user.
3254     */
3255    private int updateFlags(int flags, int userId) {
3256        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3257                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3258            // Caller expressed an explicit opinion about what encryption
3259            // aware/unaware components they want to see, so fall through and
3260            // give them what they want
3261        } else {
3262            // Caller expressed no opinion, so match based on user state
3263            if (isUserKeyUnlocked(userId)) {
3264                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3265            } else {
3266                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3267            }
3268        }
3269        return flags;
3270    }
3271
3272    /**
3273     * Update given flags when being used to request {@link PackageInfo}.
3274     */
3275    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3276        boolean triaged = true;
3277        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3278                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3279            // Caller is asking for component details, so they'd better be
3280            // asking for specific encryption matching behavior, or be triaged
3281            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3282                    | PackageManager.MATCH_ENCRYPTION_AWARE
3283                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3284                triaged = false;
3285            }
3286        }
3287        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3288                | PackageManager.MATCH_SYSTEM_ONLY
3289                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3290            triaged = false;
3291        }
3292        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3293            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3294                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3295        }
3296        return updateFlags(flags, userId);
3297    }
3298
3299    /**
3300     * Update given flags when being used to request {@link ApplicationInfo}.
3301     */
3302    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3303        return updateFlagsForPackage(flags, userId, cookie);
3304    }
3305
3306    /**
3307     * Update given flags when being used to request {@link ComponentInfo}.
3308     */
3309    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3310        if (cookie instanceof Intent) {
3311            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3312                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3313            }
3314        }
3315
3316        boolean triaged = true;
3317        // Caller is asking for component details, so they'd better be
3318        // asking for specific encryption matching behavior, or be triaged
3319        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3320                | PackageManager.MATCH_ENCRYPTION_AWARE
3321                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3322            triaged = false;
3323        }
3324        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3325            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3326                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3327        }
3328
3329        return updateFlags(flags, userId);
3330    }
3331
3332    /**
3333     * Update given flags when being used to request {@link ResolveInfo}.
3334     */
3335    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3336        // Safe mode means we shouldn't match any third-party components
3337        if (mSafeMode) {
3338            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3339        }
3340
3341        return updateFlagsForComponent(flags, userId, cookie);
3342    }
3343
3344    @Override
3345    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3346        if (!sUserManager.exists(userId)) return null;
3347        flags = updateFlagsForComponent(flags, userId, component);
3348        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3349                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3350        synchronized (mPackages) {
3351            PackageParser.Activity a = mActivities.mActivities.get(component);
3352
3353            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3354            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3355                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3356                if (ps == null) return null;
3357                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3358                        userId);
3359            }
3360            if (mResolveComponentName.equals(component)) {
3361                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3362                        new PackageUserState(), userId);
3363            }
3364        }
3365        return null;
3366    }
3367
3368    @Override
3369    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3370            String resolvedType) {
3371        synchronized (mPackages) {
3372            if (component.equals(mResolveComponentName)) {
3373                // The resolver supports EVERYTHING!
3374                return true;
3375            }
3376            PackageParser.Activity a = mActivities.mActivities.get(component);
3377            if (a == null) {
3378                return false;
3379            }
3380            for (int i=0; i<a.intents.size(); i++) {
3381                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3382                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3383                    return true;
3384                }
3385            }
3386            return false;
3387        }
3388    }
3389
3390    @Override
3391    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3392        if (!sUserManager.exists(userId)) return null;
3393        flags = updateFlagsForComponent(flags, userId, component);
3394        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3395                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3396        synchronized (mPackages) {
3397            PackageParser.Activity a = mReceivers.mActivities.get(component);
3398            if (DEBUG_PACKAGE_INFO) Log.v(
3399                TAG, "getReceiverInfo " + component + ": " + a);
3400            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3401                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3402                if (ps == null) return null;
3403                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3404                        userId);
3405            }
3406        }
3407        return null;
3408    }
3409
3410    @Override
3411    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3412        if (!sUserManager.exists(userId)) return null;
3413        flags = updateFlagsForComponent(flags, userId, component);
3414        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3415                false /* requireFullPermission */, false /* checkShell */, "get service info");
3416        synchronized (mPackages) {
3417            PackageParser.Service s = mServices.mServices.get(component);
3418            if (DEBUG_PACKAGE_INFO) Log.v(
3419                TAG, "getServiceInfo " + component + ": " + s);
3420            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3421                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3422                if (ps == null) return null;
3423                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3424                        userId);
3425            }
3426        }
3427        return null;
3428    }
3429
3430    @Override
3431    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3432        if (!sUserManager.exists(userId)) return null;
3433        flags = updateFlagsForComponent(flags, userId, component);
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3435                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3436        synchronized (mPackages) {
3437            PackageParser.Provider p = mProviders.mProviders.get(component);
3438            if (DEBUG_PACKAGE_INFO) Log.v(
3439                TAG, "getProviderInfo " + component + ": " + p);
3440            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3441                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3442                if (ps == null) return null;
3443                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3444                        userId);
3445            }
3446        }
3447        return null;
3448    }
3449
3450    @Override
3451    public String[] getSystemSharedLibraryNames() {
3452        Set<String> libSet;
3453        synchronized (mPackages) {
3454            libSet = mSharedLibraries.keySet();
3455            int size = libSet.size();
3456            if (size > 0) {
3457                String[] libs = new String[size];
3458                libSet.toArray(libs);
3459                return libs;
3460            }
3461        }
3462        return null;
3463    }
3464
3465    @Override
3466    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3467        synchronized (mPackages) {
3468            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3469                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3470            if (libraryEntry != null) {
3471                return libraryEntry.apk;
3472            }
3473        }
3474        return null;
3475    }
3476
3477    @Override
3478    public FeatureInfo[] getSystemAvailableFeatures() {
3479        Collection<FeatureInfo> featSet;
3480        synchronized (mPackages) {
3481            featSet = mAvailableFeatures.values();
3482            int size = featSet.size();
3483            if (size > 0) {
3484                FeatureInfo[] features = new FeatureInfo[size+1];
3485                featSet.toArray(features);
3486                FeatureInfo fi = new FeatureInfo();
3487                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3488                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3489                features[size] = fi;
3490                return features;
3491            }
3492        }
3493        return null;
3494    }
3495
3496    @Override
3497    public boolean hasSystemFeature(String name, int version) {
3498        synchronized (mPackages) {
3499            final FeatureInfo feat = mAvailableFeatures.get(name);
3500            if (feat == null) {
3501                return false;
3502            } else {
3503                return feat.version >= version;
3504            }
3505        }
3506    }
3507
3508    @Override
3509    public int checkPermission(String permName, String pkgName, int userId) {
3510        if (!sUserManager.exists(userId)) {
3511            return PackageManager.PERMISSION_DENIED;
3512        }
3513
3514        synchronized (mPackages) {
3515            final PackageParser.Package p = mPackages.get(pkgName);
3516            if (p != null && p.mExtras != null) {
3517                final PackageSetting ps = (PackageSetting) p.mExtras;
3518                final PermissionsState permissionsState = ps.getPermissionsState();
3519                if (permissionsState.hasPermission(permName, userId)) {
3520                    return PackageManager.PERMISSION_GRANTED;
3521                }
3522                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3523                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3524                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3525                    return PackageManager.PERMISSION_GRANTED;
3526                }
3527            }
3528        }
3529
3530        return PackageManager.PERMISSION_DENIED;
3531    }
3532
3533    @Override
3534    public int checkUidPermission(String permName, int uid) {
3535        final int userId = UserHandle.getUserId(uid);
3536
3537        if (!sUserManager.exists(userId)) {
3538            return PackageManager.PERMISSION_DENIED;
3539        }
3540
3541        synchronized (mPackages) {
3542            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3543            if (obj != null) {
3544                final SettingBase ps = (SettingBase) obj;
3545                final PermissionsState permissionsState = ps.getPermissionsState();
3546                if (permissionsState.hasPermission(permName, userId)) {
3547                    return PackageManager.PERMISSION_GRANTED;
3548                }
3549                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3550                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3551                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3552                    return PackageManager.PERMISSION_GRANTED;
3553                }
3554            } else {
3555                ArraySet<String> perms = mSystemPermissions.get(uid);
3556                if (perms != null) {
3557                    if (perms.contains(permName)) {
3558                        return PackageManager.PERMISSION_GRANTED;
3559                    }
3560                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3561                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3562                        return PackageManager.PERMISSION_GRANTED;
3563                    }
3564                }
3565            }
3566        }
3567
3568        return PackageManager.PERMISSION_DENIED;
3569    }
3570
3571    @Override
3572    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3573        if (UserHandle.getCallingUserId() != userId) {
3574            mContext.enforceCallingPermission(
3575                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3576                    "isPermissionRevokedByPolicy for user " + userId);
3577        }
3578
3579        if (checkPermission(permission, packageName, userId)
3580                == PackageManager.PERMISSION_GRANTED) {
3581            return false;
3582        }
3583
3584        final long identity = Binder.clearCallingIdentity();
3585        try {
3586            final int flags = getPermissionFlags(permission, packageName, userId);
3587            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3588        } finally {
3589            Binder.restoreCallingIdentity(identity);
3590        }
3591    }
3592
3593    @Override
3594    public String getPermissionControllerPackageName() {
3595        synchronized (mPackages) {
3596            return mRequiredInstallerPackage;
3597        }
3598    }
3599
3600    /**
3601     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3602     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3603     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3604     * @param message the message to log on security exception
3605     */
3606    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3607            boolean checkShell, String message) {
3608        if (userId < 0) {
3609            throw new IllegalArgumentException("Invalid userId " + userId);
3610        }
3611        if (checkShell) {
3612            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3613        }
3614        if (userId == UserHandle.getUserId(callingUid)) return;
3615        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3616            if (requireFullPermission) {
3617                mContext.enforceCallingOrSelfPermission(
3618                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3619            } else {
3620                try {
3621                    mContext.enforceCallingOrSelfPermission(
3622                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3623                } catch (SecurityException se) {
3624                    mContext.enforceCallingOrSelfPermission(
3625                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3626                }
3627            }
3628        }
3629    }
3630
3631    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3632        if (callingUid == Process.SHELL_UID) {
3633            if (userHandle >= 0
3634                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3635                throw new SecurityException("Shell does not have permission to access user "
3636                        + userHandle);
3637            } else if (userHandle < 0) {
3638                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3639                        + Debug.getCallers(3));
3640            }
3641        }
3642    }
3643
3644    private BasePermission findPermissionTreeLP(String permName) {
3645        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3646            if (permName.startsWith(bp.name) &&
3647                    permName.length() > bp.name.length() &&
3648                    permName.charAt(bp.name.length()) == '.') {
3649                return bp;
3650            }
3651        }
3652        return null;
3653    }
3654
3655    private BasePermission checkPermissionTreeLP(String permName) {
3656        if (permName != null) {
3657            BasePermission bp = findPermissionTreeLP(permName);
3658            if (bp != null) {
3659                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3660                    return bp;
3661                }
3662                throw new SecurityException("Calling uid "
3663                        + Binder.getCallingUid()
3664                        + " is not allowed to add to permission tree "
3665                        + bp.name + " owned by uid " + bp.uid);
3666            }
3667        }
3668        throw new SecurityException("No permission tree found for " + permName);
3669    }
3670
3671    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3672        if (s1 == null) {
3673            return s2 == null;
3674        }
3675        if (s2 == null) {
3676            return false;
3677        }
3678        if (s1.getClass() != s2.getClass()) {
3679            return false;
3680        }
3681        return s1.equals(s2);
3682    }
3683
3684    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3685        if (pi1.icon != pi2.icon) return false;
3686        if (pi1.logo != pi2.logo) return false;
3687        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3688        if (!compareStrings(pi1.name, pi2.name)) return false;
3689        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3690        // We'll take care of setting this one.
3691        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3692        // These are not currently stored in settings.
3693        //if (!compareStrings(pi1.group, pi2.group)) return false;
3694        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3695        //if (pi1.labelRes != pi2.labelRes) return false;
3696        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3697        return true;
3698    }
3699
3700    int permissionInfoFootprint(PermissionInfo info) {
3701        int size = info.name.length();
3702        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3703        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3704        return size;
3705    }
3706
3707    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3708        int size = 0;
3709        for (BasePermission perm : mSettings.mPermissions.values()) {
3710            if (perm.uid == tree.uid) {
3711                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3712            }
3713        }
3714        return size;
3715    }
3716
3717    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3718        // We calculate the max size of permissions defined by this uid and throw
3719        // if that plus the size of 'info' would exceed our stated maximum.
3720        if (tree.uid != Process.SYSTEM_UID) {
3721            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3722            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3723                throw new SecurityException("Permission tree size cap exceeded");
3724            }
3725        }
3726    }
3727
3728    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3729        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3730            throw new SecurityException("Label must be specified in permission");
3731        }
3732        BasePermission tree = checkPermissionTreeLP(info.name);
3733        BasePermission bp = mSettings.mPermissions.get(info.name);
3734        boolean added = bp == null;
3735        boolean changed = true;
3736        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3737        if (added) {
3738            enforcePermissionCapLocked(info, tree);
3739            bp = new BasePermission(info.name, tree.sourcePackage,
3740                    BasePermission.TYPE_DYNAMIC);
3741        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3742            throw new SecurityException(
3743                    "Not allowed to modify non-dynamic permission "
3744                    + info.name);
3745        } else {
3746            if (bp.protectionLevel == fixedLevel
3747                    && bp.perm.owner.equals(tree.perm.owner)
3748                    && bp.uid == tree.uid
3749                    && comparePermissionInfos(bp.perm.info, info)) {
3750                changed = false;
3751            }
3752        }
3753        bp.protectionLevel = fixedLevel;
3754        info = new PermissionInfo(info);
3755        info.protectionLevel = fixedLevel;
3756        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3757        bp.perm.info.packageName = tree.perm.info.packageName;
3758        bp.uid = tree.uid;
3759        if (added) {
3760            mSettings.mPermissions.put(info.name, bp);
3761        }
3762        if (changed) {
3763            if (!async) {
3764                mSettings.writeLPr();
3765            } else {
3766                scheduleWriteSettingsLocked();
3767            }
3768        }
3769        return added;
3770    }
3771
3772    @Override
3773    public boolean addPermission(PermissionInfo info) {
3774        synchronized (mPackages) {
3775            return addPermissionLocked(info, false);
3776        }
3777    }
3778
3779    @Override
3780    public boolean addPermissionAsync(PermissionInfo info) {
3781        synchronized (mPackages) {
3782            return addPermissionLocked(info, true);
3783        }
3784    }
3785
3786    @Override
3787    public void removePermission(String name) {
3788        synchronized (mPackages) {
3789            checkPermissionTreeLP(name);
3790            BasePermission bp = mSettings.mPermissions.get(name);
3791            if (bp != null) {
3792                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3793                    throw new SecurityException(
3794                            "Not allowed to modify non-dynamic permission "
3795                            + name);
3796                }
3797                mSettings.mPermissions.remove(name);
3798                mSettings.writeLPr();
3799            }
3800        }
3801    }
3802
3803    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3804            BasePermission bp) {
3805        int index = pkg.requestedPermissions.indexOf(bp.name);
3806        if (index == -1) {
3807            throw new SecurityException("Package " + pkg.packageName
3808                    + " has not requested permission " + bp.name);
3809        }
3810        if (!bp.isRuntime() && !bp.isDevelopment()) {
3811            throw new SecurityException("Permission " + bp.name
3812                    + " is not a changeable permission type");
3813        }
3814    }
3815
3816    @Override
3817    public void grantRuntimePermission(String packageName, String name, final int userId) {
3818        if (!sUserManager.exists(userId)) {
3819            Log.e(TAG, "No such user:" + userId);
3820            return;
3821        }
3822
3823        mContext.enforceCallingOrSelfPermission(
3824                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3825                "grantRuntimePermission");
3826
3827        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3828                true /* requireFullPermission */, true /* checkShell */,
3829                "grantRuntimePermission");
3830
3831        final int uid;
3832        final SettingBase sb;
3833
3834        synchronized (mPackages) {
3835            final PackageParser.Package pkg = mPackages.get(packageName);
3836            if (pkg == null) {
3837                throw new IllegalArgumentException("Unknown package: " + packageName);
3838            }
3839
3840            final BasePermission bp = mSettings.mPermissions.get(name);
3841            if (bp == null) {
3842                throw new IllegalArgumentException("Unknown permission: " + name);
3843            }
3844
3845            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3846
3847            // If a permission review is required for legacy apps we represent
3848            // their permissions as always granted runtime ones since we need
3849            // to keep the review required permission flag per user while an
3850            // install permission's state is shared across all users.
3851            if (Build.PERMISSIONS_REVIEW_REQUIRED
3852                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3853                    && bp.isRuntime()) {
3854                return;
3855            }
3856
3857            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3858            sb = (SettingBase) pkg.mExtras;
3859            if (sb == null) {
3860                throw new IllegalArgumentException("Unknown package: " + packageName);
3861            }
3862
3863            final PermissionsState permissionsState = sb.getPermissionsState();
3864
3865            final int flags = permissionsState.getPermissionFlags(name, userId);
3866            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3867                throw new SecurityException("Cannot grant system fixed permission "
3868                        + name + " for package " + packageName);
3869            }
3870
3871            if (bp.isDevelopment()) {
3872                // Development permissions must be handled specially, since they are not
3873                // normal runtime permissions.  For now they apply to all users.
3874                if (permissionsState.grantInstallPermission(bp) !=
3875                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3876                    scheduleWriteSettingsLocked();
3877                }
3878                return;
3879            }
3880
3881            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3882                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3883                return;
3884            }
3885
3886            final int result = permissionsState.grantRuntimePermission(bp, userId);
3887            switch (result) {
3888                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3889                    return;
3890                }
3891
3892                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3893                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3894                    mHandler.post(new Runnable() {
3895                        @Override
3896                        public void run() {
3897                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3898                        }
3899                    });
3900                }
3901                break;
3902            }
3903
3904            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3905
3906            // Not critical if that is lost - app has to request again.
3907            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3908        }
3909
3910        // Only need to do this if user is initialized. Otherwise it's a new user
3911        // and there are no processes running as the user yet and there's no need
3912        // to make an expensive call to remount processes for the changed permissions.
3913        if (READ_EXTERNAL_STORAGE.equals(name)
3914                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3915            final long token = Binder.clearCallingIdentity();
3916            try {
3917                if (sUserManager.isInitialized(userId)) {
3918                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3919                            MountServiceInternal.class);
3920                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3921                }
3922            } finally {
3923                Binder.restoreCallingIdentity(token);
3924            }
3925        }
3926    }
3927
3928    @Override
3929    public void revokeRuntimePermission(String packageName, String name, int userId) {
3930        if (!sUserManager.exists(userId)) {
3931            Log.e(TAG, "No such user:" + userId);
3932            return;
3933        }
3934
3935        mContext.enforceCallingOrSelfPermission(
3936                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3937                "revokeRuntimePermission");
3938
3939        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3940                true /* requireFullPermission */, true /* checkShell */,
3941                "revokeRuntimePermission");
3942
3943        final int appId;
3944
3945        synchronized (mPackages) {
3946            final PackageParser.Package pkg = mPackages.get(packageName);
3947            if (pkg == null) {
3948                throw new IllegalArgumentException("Unknown package: " + packageName);
3949            }
3950
3951            final BasePermission bp = mSettings.mPermissions.get(name);
3952            if (bp == null) {
3953                throw new IllegalArgumentException("Unknown permission: " + name);
3954            }
3955
3956            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3957
3958            // If a permission review is required for legacy apps we represent
3959            // their permissions as always granted runtime ones since we need
3960            // to keep the review required permission flag per user while an
3961            // install permission's state is shared across all users.
3962            if (Build.PERMISSIONS_REVIEW_REQUIRED
3963                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3964                    && bp.isRuntime()) {
3965                return;
3966            }
3967
3968            SettingBase sb = (SettingBase) pkg.mExtras;
3969            if (sb == null) {
3970                throw new IllegalArgumentException("Unknown package: " + packageName);
3971            }
3972
3973            final PermissionsState permissionsState = sb.getPermissionsState();
3974
3975            final int flags = permissionsState.getPermissionFlags(name, userId);
3976            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3977                throw new SecurityException("Cannot revoke system fixed permission "
3978                        + name + " for package " + packageName);
3979            }
3980
3981            if (bp.isDevelopment()) {
3982                // Development permissions must be handled specially, since they are not
3983                // normal runtime permissions.  For now they apply to all users.
3984                if (permissionsState.revokeInstallPermission(bp) !=
3985                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3986                    scheduleWriteSettingsLocked();
3987                }
3988                return;
3989            }
3990
3991            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3992                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3993                return;
3994            }
3995
3996            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3997
3998            // Critical, after this call app should never have the permission.
3999            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4000
4001            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4002        }
4003
4004        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4005    }
4006
4007    @Override
4008    public void resetRuntimePermissions() {
4009        mContext.enforceCallingOrSelfPermission(
4010                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4011                "revokeRuntimePermission");
4012
4013        int callingUid = Binder.getCallingUid();
4014        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4015            mContext.enforceCallingOrSelfPermission(
4016                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4017                    "resetRuntimePermissions");
4018        }
4019
4020        synchronized (mPackages) {
4021            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4022            for (int userId : UserManagerService.getInstance().getUserIds()) {
4023                final int packageCount = mPackages.size();
4024                for (int i = 0; i < packageCount; i++) {
4025                    PackageParser.Package pkg = mPackages.valueAt(i);
4026                    if (!(pkg.mExtras instanceof PackageSetting)) {
4027                        continue;
4028                    }
4029                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4030                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4031                }
4032            }
4033        }
4034    }
4035
4036    @Override
4037    public int getPermissionFlags(String name, String packageName, int userId) {
4038        if (!sUserManager.exists(userId)) {
4039            return 0;
4040        }
4041
4042        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4043
4044        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4045                true /* requireFullPermission */, false /* checkShell */,
4046                "getPermissionFlags");
4047
4048        synchronized (mPackages) {
4049            final PackageParser.Package pkg = mPackages.get(packageName);
4050            if (pkg == null) {
4051                throw new IllegalArgumentException("Unknown package: " + packageName);
4052            }
4053
4054            final BasePermission bp = mSettings.mPermissions.get(name);
4055            if (bp == null) {
4056                throw new IllegalArgumentException("Unknown permission: " + name);
4057            }
4058
4059            SettingBase sb = (SettingBase) pkg.mExtras;
4060            if (sb == null) {
4061                throw new IllegalArgumentException("Unknown package: " + packageName);
4062            }
4063
4064            PermissionsState permissionsState = sb.getPermissionsState();
4065            return permissionsState.getPermissionFlags(name, userId);
4066        }
4067    }
4068
4069    @Override
4070    public void updatePermissionFlags(String name, String packageName, int flagMask,
4071            int flagValues, int userId) {
4072        if (!sUserManager.exists(userId)) {
4073            return;
4074        }
4075
4076        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4077
4078        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4079                true /* requireFullPermission */, true /* checkShell */,
4080                "updatePermissionFlags");
4081
4082        // Only the system can change these flags and nothing else.
4083        if (getCallingUid() != Process.SYSTEM_UID) {
4084            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4085            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4086            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4087            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4088            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4089        }
4090
4091        synchronized (mPackages) {
4092            final PackageParser.Package pkg = mPackages.get(packageName);
4093            if (pkg == null) {
4094                throw new IllegalArgumentException("Unknown package: " + packageName);
4095            }
4096
4097            final BasePermission bp = mSettings.mPermissions.get(name);
4098            if (bp == null) {
4099                throw new IllegalArgumentException("Unknown permission: " + name);
4100            }
4101
4102            SettingBase sb = (SettingBase) pkg.mExtras;
4103            if (sb == null) {
4104                throw new IllegalArgumentException("Unknown package: " + packageName);
4105            }
4106
4107            PermissionsState permissionsState = sb.getPermissionsState();
4108
4109            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4110
4111            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4112                // Install and runtime permissions are stored in different places,
4113                // so figure out what permission changed and persist the change.
4114                if (permissionsState.getInstallPermissionState(name) != null) {
4115                    scheduleWriteSettingsLocked();
4116                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4117                        || hadState) {
4118                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4119                }
4120            }
4121        }
4122    }
4123
4124    /**
4125     * Update the permission flags for all packages and runtime permissions of a user in order
4126     * to allow device or profile owner to remove POLICY_FIXED.
4127     */
4128    @Override
4129    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4130        if (!sUserManager.exists(userId)) {
4131            return;
4132        }
4133
4134        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4135
4136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4137                true /* requireFullPermission */, true /* checkShell */,
4138                "updatePermissionFlagsForAllApps");
4139
4140        // Only the system can change system fixed flags.
4141        if (getCallingUid() != Process.SYSTEM_UID) {
4142            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4143            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4144        }
4145
4146        synchronized (mPackages) {
4147            boolean changed = false;
4148            final int packageCount = mPackages.size();
4149            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4150                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4151                SettingBase sb = (SettingBase) pkg.mExtras;
4152                if (sb == null) {
4153                    continue;
4154                }
4155                PermissionsState permissionsState = sb.getPermissionsState();
4156                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4157                        userId, flagMask, flagValues);
4158            }
4159            if (changed) {
4160                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4161            }
4162        }
4163    }
4164
4165    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4166        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4167                != PackageManager.PERMISSION_GRANTED
4168            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4169                != PackageManager.PERMISSION_GRANTED) {
4170            throw new SecurityException(message + " requires "
4171                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4172                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4173        }
4174    }
4175
4176    @Override
4177    public boolean shouldShowRequestPermissionRationale(String permissionName,
4178            String packageName, int userId) {
4179        if (UserHandle.getCallingUserId() != userId) {
4180            mContext.enforceCallingPermission(
4181                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4182                    "canShowRequestPermissionRationale for user " + userId);
4183        }
4184
4185        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4186        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4187            return false;
4188        }
4189
4190        if (checkPermission(permissionName, packageName, userId)
4191                == PackageManager.PERMISSION_GRANTED) {
4192            return false;
4193        }
4194
4195        final int flags;
4196
4197        final long identity = Binder.clearCallingIdentity();
4198        try {
4199            flags = getPermissionFlags(permissionName,
4200                    packageName, userId);
4201        } finally {
4202            Binder.restoreCallingIdentity(identity);
4203        }
4204
4205        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4206                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4207                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4208
4209        if ((flags & fixedFlags) != 0) {
4210            return false;
4211        }
4212
4213        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4214    }
4215
4216    @Override
4217    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4218        mContext.enforceCallingOrSelfPermission(
4219                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4220                "addOnPermissionsChangeListener");
4221
4222        synchronized (mPackages) {
4223            mOnPermissionChangeListeners.addListenerLocked(listener);
4224        }
4225    }
4226
4227    @Override
4228    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4229        synchronized (mPackages) {
4230            mOnPermissionChangeListeners.removeListenerLocked(listener);
4231        }
4232    }
4233
4234    @Override
4235    public boolean isProtectedBroadcast(String actionName) {
4236        synchronized (mPackages) {
4237            if (mProtectedBroadcasts.contains(actionName)) {
4238                return true;
4239            } else if (actionName != null) {
4240                // TODO: remove these terrible hacks
4241                if (actionName.startsWith("android.net.netmon.lingerExpired")
4242                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4243                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4244                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4245                    return true;
4246                }
4247            }
4248        }
4249        return false;
4250    }
4251
4252    @Override
4253    public int checkSignatures(String pkg1, String pkg2) {
4254        synchronized (mPackages) {
4255            final PackageParser.Package p1 = mPackages.get(pkg1);
4256            final PackageParser.Package p2 = mPackages.get(pkg2);
4257            if (p1 == null || p1.mExtras == null
4258                    || p2 == null || p2.mExtras == null) {
4259                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4260            }
4261            return compareSignatures(p1.mSignatures, p2.mSignatures);
4262        }
4263    }
4264
4265    @Override
4266    public int checkUidSignatures(int uid1, int uid2) {
4267        // Map to base uids.
4268        uid1 = UserHandle.getAppId(uid1);
4269        uid2 = UserHandle.getAppId(uid2);
4270        // reader
4271        synchronized (mPackages) {
4272            Signature[] s1;
4273            Signature[] s2;
4274            Object obj = mSettings.getUserIdLPr(uid1);
4275            if (obj != null) {
4276                if (obj instanceof SharedUserSetting) {
4277                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4278                } else if (obj instanceof PackageSetting) {
4279                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4280                } else {
4281                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4282                }
4283            } else {
4284                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4285            }
4286            obj = mSettings.getUserIdLPr(uid2);
4287            if (obj != null) {
4288                if (obj instanceof SharedUserSetting) {
4289                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4290                } else if (obj instanceof PackageSetting) {
4291                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4292                } else {
4293                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4294                }
4295            } else {
4296                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4297            }
4298            return compareSignatures(s1, s2);
4299        }
4300    }
4301
4302    private void killUid(int appId, int userId, String reason) {
4303        final long identity = Binder.clearCallingIdentity();
4304        try {
4305            IActivityManager am = ActivityManagerNative.getDefault();
4306            if (am != null) {
4307                try {
4308                    am.killUid(appId, userId, reason);
4309                } catch (RemoteException e) {
4310                    /* ignore - same process */
4311                }
4312            }
4313        } finally {
4314            Binder.restoreCallingIdentity(identity);
4315        }
4316    }
4317
4318    /**
4319     * Compares two sets of signatures. Returns:
4320     * <br />
4321     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4322     * <br />
4323     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4324     * <br />
4325     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4326     * <br />
4327     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4328     * <br />
4329     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4330     */
4331    static int compareSignatures(Signature[] s1, Signature[] s2) {
4332        if (s1 == null) {
4333            return s2 == null
4334                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4335                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4336        }
4337
4338        if (s2 == null) {
4339            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4340        }
4341
4342        if (s1.length != s2.length) {
4343            return PackageManager.SIGNATURE_NO_MATCH;
4344        }
4345
4346        // Since both signature sets are of size 1, we can compare without HashSets.
4347        if (s1.length == 1) {
4348            return s1[0].equals(s2[0]) ?
4349                    PackageManager.SIGNATURE_MATCH :
4350                    PackageManager.SIGNATURE_NO_MATCH;
4351        }
4352
4353        ArraySet<Signature> set1 = new ArraySet<Signature>();
4354        for (Signature sig : s1) {
4355            set1.add(sig);
4356        }
4357        ArraySet<Signature> set2 = new ArraySet<Signature>();
4358        for (Signature sig : s2) {
4359            set2.add(sig);
4360        }
4361        // Make sure s2 contains all signatures in s1.
4362        if (set1.equals(set2)) {
4363            return PackageManager.SIGNATURE_MATCH;
4364        }
4365        return PackageManager.SIGNATURE_NO_MATCH;
4366    }
4367
4368    /**
4369     * If the database version for this type of package (internal storage or
4370     * external storage) is less than the version where package signatures
4371     * were updated, return true.
4372     */
4373    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4374        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4375        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4376    }
4377
4378    /**
4379     * Used for backward compatibility to make sure any packages with
4380     * certificate chains get upgraded to the new style. {@code existingSigs}
4381     * will be in the old format (since they were stored on disk from before the
4382     * system upgrade) and {@code scannedSigs} will be in the newer format.
4383     */
4384    private int compareSignaturesCompat(PackageSignatures existingSigs,
4385            PackageParser.Package scannedPkg) {
4386        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4387            return PackageManager.SIGNATURE_NO_MATCH;
4388        }
4389
4390        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4391        for (Signature sig : existingSigs.mSignatures) {
4392            existingSet.add(sig);
4393        }
4394        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4395        for (Signature sig : scannedPkg.mSignatures) {
4396            try {
4397                Signature[] chainSignatures = sig.getChainSignatures();
4398                for (Signature chainSig : chainSignatures) {
4399                    scannedCompatSet.add(chainSig);
4400                }
4401            } catch (CertificateEncodingException e) {
4402                scannedCompatSet.add(sig);
4403            }
4404        }
4405        /*
4406         * Make sure the expanded scanned set contains all signatures in the
4407         * existing one.
4408         */
4409        if (scannedCompatSet.equals(existingSet)) {
4410            // Migrate the old signatures to the new scheme.
4411            existingSigs.assignSignatures(scannedPkg.mSignatures);
4412            // The new KeySets will be re-added later in the scanning process.
4413            synchronized (mPackages) {
4414                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4415            }
4416            return PackageManager.SIGNATURE_MATCH;
4417        }
4418        return PackageManager.SIGNATURE_NO_MATCH;
4419    }
4420
4421    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4422        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4423        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4424    }
4425
4426    private int compareSignaturesRecover(PackageSignatures existingSigs,
4427            PackageParser.Package scannedPkg) {
4428        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4429            return PackageManager.SIGNATURE_NO_MATCH;
4430        }
4431
4432        String msg = null;
4433        try {
4434            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4435                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4436                        + scannedPkg.packageName);
4437                return PackageManager.SIGNATURE_MATCH;
4438            }
4439        } catch (CertificateException e) {
4440            msg = e.getMessage();
4441        }
4442
4443        logCriticalInfo(Log.INFO,
4444                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4445        return PackageManager.SIGNATURE_NO_MATCH;
4446    }
4447
4448    @Override
4449    public String[] getPackagesForUid(int uid) {
4450        uid = UserHandle.getAppId(uid);
4451        // reader
4452        synchronized (mPackages) {
4453            Object obj = mSettings.getUserIdLPr(uid);
4454            if (obj instanceof SharedUserSetting) {
4455                final SharedUserSetting sus = (SharedUserSetting) obj;
4456                final int N = sus.packages.size();
4457                final String[] res = new String[N];
4458                final Iterator<PackageSetting> it = sus.packages.iterator();
4459                int i = 0;
4460                while (it.hasNext()) {
4461                    res[i++] = it.next().name;
4462                }
4463                return res;
4464            } else if (obj instanceof PackageSetting) {
4465                final PackageSetting ps = (PackageSetting) obj;
4466                return new String[] { ps.name };
4467            }
4468        }
4469        return null;
4470    }
4471
4472    @Override
4473    public String getNameForUid(int uid) {
4474        // reader
4475        synchronized (mPackages) {
4476            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4477            if (obj instanceof SharedUserSetting) {
4478                final SharedUserSetting sus = (SharedUserSetting) obj;
4479                return sus.name + ":" + sus.userId;
4480            } else if (obj instanceof PackageSetting) {
4481                final PackageSetting ps = (PackageSetting) obj;
4482                return ps.name;
4483            }
4484        }
4485        return null;
4486    }
4487
4488    @Override
4489    public int getUidForSharedUser(String sharedUserName) {
4490        if(sharedUserName == null) {
4491            return -1;
4492        }
4493        // reader
4494        synchronized (mPackages) {
4495            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4496            if (suid == null) {
4497                return -1;
4498            }
4499            return suid.userId;
4500        }
4501    }
4502
4503    @Override
4504    public int getFlagsForUid(int uid) {
4505        synchronized (mPackages) {
4506            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4507            if (obj instanceof SharedUserSetting) {
4508                final SharedUserSetting sus = (SharedUserSetting) obj;
4509                return sus.pkgFlags;
4510            } else if (obj instanceof PackageSetting) {
4511                final PackageSetting ps = (PackageSetting) obj;
4512                return ps.pkgFlags;
4513            }
4514        }
4515        return 0;
4516    }
4517
4518    @Override
4519    public int getPrivateFlagsForUid(int uid) {
4520        synchronized (mPackages) {
4521            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4522            if (obj instanceof SharedUserSetting) {
4523                final SharedUserSetting sus = (SharedUserSetting) obj;
4524                return sus.pkgPrivateFlags;
4525            } else if (obj instanceof PackageSetting) {
4526                final PackageSetting ps = (PackageSetting) obj;
4527                return ps.pkgPrivateFlags;
4528            }
4529        }
4530        return 0;
4531    }
4532
4533    @Override
4534    public boolean isUidPrivileged(int uid) {
4535        uid = UserHandle.getAppId(uid);
4536        // reader
4537        synchronized (mPackages) {
4538            Object obj = mSettings.getUserIdLPr(uid);
4539            if (obj instanceof SharedUserSetting) {
4540                final SharedUserSetting sus = (SharedUserSetting) obj;
4541                final Iterator<PackageSetting> it = sus.packages.iterator();
4542                while (it.hasNext()) {
4543                    if (it.next().isPrivileged()) {
4544                        return true;
4545                    }
4546                }
4547            } else if (obj instanceof PackageSetting) {
4548                final PackageSetting ps = (PackageSetting) obj;
4549                return ps.isPrivileged();
4550            }
4551        }
4552        return false;
4553    }
4554
4555    @Override
4556    public String[] getAppOpPermissionPackages(String permissionName) {
4557        synchronized (mPackages) {
4558            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4559            if (pkgs == null) {
4560                return null;
4561            }
4562            return pkgs.toArray(new String[pkgs.size()]);
4563        }
4564    }
4565
4566    @Override
4567    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4568            int flags, int userId) {
4569        if (!sUserManager.exists(userId)) return null;
4570        flags = updateFlagsForResolve(flags, userId, intent);
4571        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4572                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4573        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4574        final ResolveInfo bestChoice =
4575                chooseBestActivity(intent, resolvedType, flags, query, userId);
4576
4577        if (isEphemeralAllowed(intent, query, userId)) {
4578            final EphemeralResolveInfo ai =
4579                    getEphemeralResolveInfo(intent, resolvedType, userId);
4580            if (ai != null) {
4581                if (DEBUG_EPHEMERAL) {
4582                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4583                }
4584                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4585                bestChoice.ephemeralResolveInfo = ai;
4586            }
4587        }
4588        return bestChoice;
4589    }
4590
4591    @Override
4592    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4593            IntentFilter filter, int match, ComponentName activity) {
4594        final int userId = UserHandle.getCallingUserId();
4595        if (DEBUG_PREFERRED) {
4596            Log.v(TAG, "setLastChosenActivity intent=" + intent
4597                + " resolvedType=" + resolvedType
4598                + " flags=" + flags
4599                + " filter=" + filter
4600                + " match=" + match
4601                + " activity=" + activity);
4602            filter.dump(new PrintStreamPrinter(System.out), "    ");
4603        }
4604        intent.setComponent(null);
4605        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4606        // Find any earlier preferred or last chosen entries and nuke them
4607        findPreferredActivity(intent, resolvedType,
4608                flags, query, 0, false, true, false, userId);
4609        // Add the new activity as the last chosen for this filter
4610        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4611                "Setting last chosen");
4612    }
4613
4614    @Override
4615    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4616        final int userId = UserHandle.getCallingUserId();
4617        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4618        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4619        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4620                false, false, false, userId);
4621    }
4622
4623
4624    private boolean isEphemeralAllowed(
4625            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4626        // Short circuit and return early if possible.
4627        if (DISABLE_EPHEMERAL_APPS) {
4628            return false;
4629        }
4630        final int callingUser = UserHandle.getCallingUserId();
4631        if (callingUser != UserHandle.USER_SYSTEM) {
4632            return false;
4633        }
4634        if (mEphemeralResolverConnection == null) {
4635            return false;
4636        }
4637        if (intent.getComponent() != null) {
4638            return false;
4639        }
4640        if (intent.getPackage() != null) {
4641            return false;
4642        }
4643        final boolean isWebUri = hasWebURI(intent);
4644        if (!isWebUri) {
4645            return false;
4646        }
4647        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4648        synchronized (mPackages) {
4649            final int count = resolvedActivites.size();
4650            for (int n = 0; n < count; n++) {
4651                ResolveInfo info = resolvedActivites.get(n);
4652                String packageName = info.activityInfo.packageName;
4653                PackageSetting ps = mSettings.mPackages.get(packageName);
4654                if (ps != null) {
4655                    // Try to get the status from User settings first
4656                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4657                    int status = (int) (packedStatus >> 32);
4658                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4659                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4660                        if (DEBUG_EPHEMERAL) {
4661                            Slog.v(TAG, "DENY ephemeral apps;"
4662                                + " pkg: " + packageName + ", status: " + status);
4663                        }
4664                        return false;
4665                    }
4666                }
4667            }
4668        }
4669        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4670        return true;
4671    }
4672
4673    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4674            int userId) {
4675        MessageDigest digest = null;
4676        try {
4677            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4678        } catch (NoSuchAlgorithmException e) {
4679            // If we can't create a digest, ignore ephemeral apps.
4680            return null;
4681        }
4682
4683        final byte[] hostBytes = intent.getData().getHost().getBytes();
4684        final byte[] digestBytes = digest.digest(hostBytes);
4685        int shaPrefix =
4686                digestBytes[0] << 24
4687                | digestBytes[1] << 16
4688                | digestBytes[2] << 8
4689                | digestBytes[3] << 0;
4690        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4691                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4692        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4693            // No hash prefix match; there are no ephemeral apps for this domain.
4694            return null;
4695        }
4696        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4697            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4698            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4699                continue;
4700            }
4701            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4702            // No filters; this should never happen.
4703            if (filters.isEmpty()) {
4704                continue;
4705            }
4706            // We have a domain match; resolve the filters to see if anything matches.
4707            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4708            for (int j = filters.size() - 1; j >= 0; --j) {
4709                final EphemeralResolveIntentInfo intentInfo =
4710                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4711                ephemeralResolver.addFilter(intentInfo);
4712            }
4713            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4714                    intent, resolvedType, false /*defaultOnly*/, userId);
4715            if (!matchedResolveInfoList.isEmpty()) {
4716                return matchedResolveInfoList.get(0);
4717            }
4718        }
4719        // Hash or filter mis-match; no ephemeral apps for this domain.
4720        return null;
4721    }
4722
4723    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4724            int flags, List<ResolveInfo> query, int userId) {
4725        if (query != null) {
4726            final int N = query.size();
4727            if (N == 1) {
4728                return query.get(0);
4729            } else if (N > 1) {
4730                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4731                // If there is more than one activity with the same priority,
4732                // then let the user decide between them.
4733                ResolveInfo r0 = query.get(0);
4734                ResolveInfo r1 = query.get(1);
4735                if (DEBUG_INTENT_MATCHING || debug) {
4736                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4737                            + r1.activityInfo.name + "=" + r1.priority);
4738                }
4739                // If the first activity has a higher priority, or a different
4740                // default, then it is always desirable to pick it.
4741                if (r0.priority != r1.priority
4742                        || r0.preferredOrder != r1.preferredOrder
4743                        || r0.isDefault != r1.isDefault) {
4744                    return query.get(0);
4745                }
4746                // If we have saved a preference for a preferred activity for
4747                // this Intent, use that.
4748                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4749                        flags, query, r0.priority, true, false, debug, userId);
4750                if (ri != null) {
4751                    return ri;
4752                }
4753                ri = new ResolveInfo(mResolveInfo);
4754                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4755                ri.activityInfo.applicationInfo = new ApplicationInfo(
4756                        ri.activityInfo.applicationInfo);
4757                if (userId != 0) {
4758                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4759                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4760                }
4761                // Make sure that the resolver is displayable in car mode
4762                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4763                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4764                return ri;
4765            }
4766        }
4767        return null;
4768    }
4769
4770    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4771            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4772        final int N = query.size();
4773        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4774                .get(userId);
4775        // Get the list of persistent preferred activities that handle the intent
4776        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4777        List<PersistentPreferredActivity> pprefs = ppir != null
4778                ? ppir.queryIntent(intent, resolvedType,
4779                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4780                : null;
4781        if (pprefs != null && pprefs.size() > 0) {
4782            final int M = pprefs.size();
4783            for (int i=0; i<M; i++) {
4784                final PersistentPreferredActivity ppa = pprefs.get(i);
4785                if (DEBUG_PREFERRED || debug) {
4786                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4787                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4788                            + "\n  component=" + ppa.mComponent);
4789                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4790                }
4791                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4792                        flags | MATCH_DISABLED_COMPONENTS, userId);
4793                if (DEBUG_PREFERRED || debug) {
4794                    Slog.v(TAG, "Found persistent preferred activity:");
4795                    if (ai != null) {
4796                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4797                    } else {
4798                        Slog.v(TAG, "  null");
4799                    }
4800                }
4801                if (ai == null) {
4802                    // This previously registered persistent preferred activity
4803                    // component is no longer known. Ignore it and do NOT remove it.
4804                    continue;
4805                }
4806                for (int j=0; j<N; j++) {
4807                    final ResolveInfo ri = query.get(j);
4808                    if (!ri.activityInfo.applicationInfo.packageName
4809                            .equals(ai.applicationInfo.packageName)) {
4810                        continue;
4811                    }
4812                    if (!ri.activityInfo.name.equals(ai.name)) {
4813                        continue;
4814                    }
4815                    //  Found a persistent preference that can handle the intent.
4816                    if (DEBUG_PREFERRED || debug) {
4817                        Slog.v(TAG, "Returning persistent preferred activity: " +
4818                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4819                    }
4820                    return ri;
4821                }
4822            }
4823        }
4824        return null;
4825    }
4826
4827    // TODO: handle preferred activities missing while user has amnesia
4828    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4829            List<ResolveInfo> query, int priority, boolean always,
4830            boolean removeMatches, boolean debug, int userId) {
4831        if (!sUserManager.exists(userId)) return null;
4832        flags = updateFlagsForResolve(flags, userId, intent);
4833        // writer
4834        synchronized (mPackages) {
4835            if (intent.getSelector() != null) {
4836                intent = intent.getSelector();
4837            }
4838            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4839
4840            // Try to find a matching persistent preferred activity.
4841            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4842                    debug, userId);
4843
4844            // If a persistent preferred activity matched, use it.
4845            if (pri != null) {
4846                return pri;
4847            }
4848
4849            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4850            // Get the list of preferred activities that handle the intent
4851            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4852            List<PreferredActivity> prefs = pir != null
4853                    ? pir.queryIntent(intent, resolvedType,
4854                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4855                    : null;
4856            if (prefs != null && prefs.size() > 0) {
4857                boolean changed = false;
4858                try {
4859                    // First figure out how good the original match set is.
4860                    // We will only allow preferred activities that came
4861                    // from the same match quality.
4862                    int match = 0;
4863
4864                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4865
4866                    final int N = query.size();
4867                    for (int j=0; j<N; j++) {
4868                        final ResolveInfo ri = query.get(j);
4869                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4870                                + ": 0x" + Integer.toHexString(match));
4871                        if (ri.match > match) {
4872                            match = ri.match;
4873                        }
4874                    }
4875
4876                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4877                            + Integer.toHexString(match));
4878
4879                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4880                    final int M = prefs.size();
4881                    for (int i=0; i<M; i++) {
4882                        final PreferredActivity pa = prefs.get(i);
4883                        if (DEBUG_PREFERRED || debug) {
4884                            Slog.v(TAG, "Checking PreferredActivity ds="
4885                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4886                                    + "\n  component=" + pa.mPref.mComponent);
4887                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4888                        }
4889                        if (pa.mPref.mMatch != match) {
4890                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4891                                    + Integer.toHexString(pa.mPref.mMatch));
4892                            continue;
4893                        }
4894                        // If it's not an "always" type preferred activity and that's what we're
4895                        // looking for, skip it.
4896                        if (always && !pa.mPref.mAlways) {
4897                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4898                            continue;
4899                        }
4900                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4901                                flags | MATCH_DISABLED_COMPONENTS, userId);
4902                        if (DEBUG_PREFERRED || debug) {
4903                            Slog.v(TAG, "Found preferred activity:");
4904                            if (ai != null) {
4905                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4906                            } else {
4907                                Slog.v(TAG, "  null");
4908                            }
4909                        }
4910                        if (ai == null) {
4911                            // This previously registered preferred activity
4912                            // component is no longer known.  Most likely an update
4913                            // to the app was installed and in the new version this
4914                            // component no longer exists.  Clean it up by removing
4915                            // it from the preferred activities list, and skip it.
4916                            Slog.w(TAG, "Removing dangling preferred activity: "
4917                                    + pa.mPref.mComponent);
4918                            pir.removeFilter(pa);
4919                            changed = true;
4920                            continue;
4921                        }
4922                        for (int j=0; j<N; j++) {
4923                            final ResolveInfo ri = query.get(j);
4924                            if (!ri.activityInfo.applicationInfo.packageName
4925                                    .equals(ai.applicationInfo.packageName)) {
4926                                continue;
4927                            }
4928                            if (!ri.activityInfo.name.equals(ai.name)) {
4929                                continue;
4930                            }
4931
4932                            if (removeMatches) {
4933                                pir.removeFilter(pa);
4934                                changed = true;
4935                                if (DEBUG_PREFERRED) {
4936                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4937                                }
4938                                break;
4939                            }
4940
4941                            // Okay we found a previously set preferred or last chosen app.
4942                            // If the result set is different from when this
4943                            // was created, we need to clear it and re-ask the
4944                            // user their preference, if we're looking for an "always" type entry.
4945                            if (always && !pa.mPref.sameSet(query)) {
4946                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4947                                        + intent + " type " + resolvedType);
4948                                if (DEBUG_PREFERRED) {
4949                                    Slog.v(TAG, "Removing preferred activity since set changed "
4950                                            + pa.mPref.mComponent);
4951                                }
4952                                pir.removeFilter(pa);
4953                                // Re-add the filter as a "last chosen" entry (!always)
4954                                PreferredActivity lastChosen = new PreferredActivity(
4955                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4956                                pir.addFilter(lastChosen);
4957                                changed = true;
4958                                return null;
4959                            }
4960
4961                            // Yay! Either the set matched or we're looking for the last chosen
4962                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4963                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4964                            return ri;
4965                        }
4966                    }
4967                } finally {
4968                    if (changed) {
4969                        if (DEBUG_PREFERRED) {
4970                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4971                        }
4972                        scheduleWritePackageRestrictionsLocked(userId);
4973                    }
4974                }
4975            }
4976        }
4977        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4978        return null;
4979    }
4980
4981    /*
4982     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4983     */
4984    @Override
4985    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4986            int targetUserId) {
4987        mContext.enforceCallingOrSelfPermission(
4988                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4989        List<CrossProfileIntentFilter> matches =
4990                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4991        if (matches != null) {
4992            int size = matches.size();
4993            for (int i = 0; i < size; i++) {
4994                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4995            }
4996        }
4997        if (hasWebURI(intent)) {
4998            // cross-profile app linking works only towards the parent.
4999            final UserInfo parent = getProfileParent(sourceUserId);
5000            synchronized(mPackages) {
5001                int flags = updateFlagsForResolve(0, parent.id, intent);
5002                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5003                        intent, resolvedType, flags, sourceUserId, parent.id);
5004                return xpDomainInfo != null;
5005            }
5006        }
5007        return false;
5008    }
5009
5010    private UserInfo getProfileParent(int userId) {
5011        final long identity = Binder.clearCallingIdentity();
5012        try {
5013            return sUserManager.getProfileParent(userId);
5014        } finally {
5015            Binder.restoreCallingIdentity(identity);
5016        }
5017    }
5018
5019    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5020            String resolvedType, int userId) {
5021        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5022        if (resolver != null) {
5023            return resolver.queryIntent(intent, resolvedType, false, userId);
5024        }
5025        return null;
5026    }
5027
5028    @Override
5029    public List<ResolveInfo> queryIntentActivities(Intent intent,
5030            String resolvedType, int flags, int userId) {
5031        if (!sUserManager.exists(userId)) return Collections.emptyList();
5032        flags = updateFlagsForResolve(flags, userId, intent);
5033        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5034                false /* requireFullPermission */, false /* checkShell */,
5035                "query intent activities");
5036        ComponentName comp = intent.getComponent();
5037        if (comp == null) {
5038            if (intent.getSelector() != null) {
5039                intent = intent.getSelector();
5040                comp = intent.getComponent();
5041            }
5042        }
5043
5044        if (comp != null) {
5045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5046            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5047            if (ai != null) {
5048                final ResolveInfo ri = new ResolveInfo();
5049                ri.activityInfo = ai;
5050                list.add(ri);
5051            }
5052            return list;
5053        }
5054
5055        // reader
5056        synchronized (mPackages) {
5057            final String pkgName = intent.getPackage();
5058            if (pkgName == null) {
5059                List<CrossProfileIntentFilter> matchingFilters =
5060                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5061                // Check for results that need to skip the current profile.
5062                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5063                        resolvedType, flags, userId);
5064                if (xpResolveInfo != null) {
5065                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5066                    result.add(xpResolveInfo);
5067                    return filterIfNotSystemUser(result, userId);
5068                }
5069
5070                // Check for results in the current profile.
5071                List<ResolveInfo> result = mActivities.queryIntent(
5072                        intent, resolvedType, flags, userId);
5073                result = filterIfNotSystemUser(result, userId);
5074
5075                // Check for cross profile results.
5076                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5077                xpResolveInfo = queryCrossProfileIntents(
5078                        matchingFilters, intent, resolvedType, flags, userId,
5079                        hasNonNegativePriorityResult);
5080                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5081                    boolean isVisibleToUser = filterIfNotSystemUser(
5082                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5083                    if (isVisibleToUser) {
5084                        result.add(xpResolveInfo);
5085                        Collections.sort(result, mResolvePrioritySorter);
5086                    }
5087                }
5088                if (hasWebURI(intent)) {
5089                    CrossProfileDomainInfo xpDomainInfo = null;
5090                    final UserInfo parent = getProfileParent(userId);
5091                    if (parent != null) {
5092                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5093                                flags, userId, parent.id);
5094                    }
5095                    if (xpDomainInfo != null) {
5096                        if (xpResolveInfo != null) {
5097                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5098                            // in the result.
5099                            result.remove(xpResolveInfo);
5100                        }
5101                        if (result.size() == 0) {
5102                            result.add(xpDomainInfo.resolveInfo);
5103                            return result;
5104                        }
5105                    } else if (result.size() <= 1) {
5106                        return result;
5107                    }
5108                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5109                            xpDomainInfo, userId);
5110                    Collections.sort(result, mResolvePrioritySorter);
5111                }
5112                return result;
5113            }
5114            final PackageParser.Package pkg = mPackages.get(pkgName);
5115            if (pkg != null) {
5116                return filterIfNotSystemUser(
5117                        mActivities.queryIntentForPackage(
5118                                intent, resolvedType, flags, pkg.activities, userId),
5119                        userId);
5120            }
5121            return new ArrayList<ResolveInfo>();
5122        }
5123    }
5124
5125    private static class CrossProfileDomainInfo {
5126        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5127        ResolveInfo resolveInfo;
5128        /* Best domain verification status of the activities found in the other profile */
5129        int bestDomainVerificationStatus;
5130    }
5131
5132    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5133            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5134        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5135                sourceUserId)) {
5136            return null;
5137        }
5138        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5139                resolvedType, flags, parentUserId);
5140
5141        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5142            return null;
5143        }
5144        CrossProfileDomainInfo result = null;
5145        int size = resultTargetUser.size();
5146        for (int i = 0; i < size; i++) {
5147            ResolveInfo riTargetUser = resultTargetUser.get(i);
5148            // Intent filter verification is only for filters that specify a host. So don't return
5149            // those that handle all web uris.
5150            if (riTargetUser.handleAllWebDataURI) {
5151                continue;
5152            }
5153            String packageName = riTargetUser.activityInfo.packageName;
5154            PackageSetting ps = mSettings.mPackages.get(packageName);
5155            if (ps == null) {
5156                continue;
5157            }
5158            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5159            int status = (int)(verificationState >> 32);
5160            if (result == null) {
5161                result = new CrossProfileDomainInfo();
5162                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5163                        sourceUserId, parentUserId);
5164                result.bestDomainVerificationStatus = status;
5165            } else {
5166                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5167                        result.bestDomainVerificationStatus);
5168            }
5169        }
5170        // Don't consider matches with status NEVER across profiles.
5171        if (result != null && result.bestDomainVerificationStatus
5172                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5173            return null;
5174        }
5175        return result;
5176    }
5177
5178    /**
5179     * Verification statuses are ordered from the worse to the best, except for
5180     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5181     */
5182    private int bestDomainVerificationStatus(int status1, int status2) {
5183        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5184            return status2;
5185        }
5186        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5187            return status1;
5188        }
5189        return (int) MathUtils.max(status1, status2);
5190    }
5191
5192    private boolean isUserEnabled(int userId) {
5193        long callingId = Binder.clearCallingIdentity();
5194        try {
5195            UserInfo userInfo = sUserManager.getUserInfo(userId);
5196            return userInfo != null && userInfo.isEnabled();
5197        } finally {
5198            Binder.restoreCallingIdentity(callingId);
5199        }
5200    }
5201
5202    /**
5203     * Filter out activities with systemUserOnly flag set, when current user is not System.
5204     *
5205     * @return filtered list
5206     */
5207    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5208        if (userId == UserHandle.USER_SYSTEM) {
5209            return resolveInfos;
5210        }
5211        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5212            ResolveInfo info = resolveInfos.get(i);
5213            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5214                resolveInfos.remove(i);
5215            }
5216        }
5217        return resolveInfos;
5218    }
5219
5220    /**
5221     * @param resolveInfos list of resolve infos in descending priority order
5222     * @return if the list contains a resolve info with non-negative priority
5223     */
5224    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5225        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5226    }
5227
5228    private static boolean hasWebURI(Intent intent) {
5229        if (intent.getData() == null) {
5230            return false;
5231        }
5232        final String scheme = intent.getScheme();
5233        if (TextUtils.isEmpty(scheme)) {
5234            return false;
5235        }
5236        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5237    }
5238
5239    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5240            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5241            int userId) {
5242        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5243
5244        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5245            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5246                    candidates.size());
5247        }
5248
5249        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5250        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5251        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5252        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5253        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5254        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5255
5256        synchronized (mPackages) {
5257            final int count = candidates.size();
5258            // First, try to use linked apps. Partition the candidates into four lists:
5259            // one for the final results, one for the "do not use ever", one for "undefined status"
5260            // and finally one for "browser app type".
5261            for (int n=0; n<count; n++) {
5262                ResolveInfo info = candidates.get(n);
5263                String packageName = info.activityInfo.packageName;
5264                PackageSetting ps = mSettings.mPackages.get(packageName);
5265                if (ps != null) {
5266                    // Add to the special match all list (Browser use case)
5267                    if (info.handleAllWebDataURI) {
5268                        matchAllList.add(info);
5269                        continue;
5270                    }
5271                    // Try to get the status from User settings first
5272                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5273                    int status = (int)(packedStatus >> 32);
5274                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5275                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5276                        if (DEBUG_DOMAIN_VERIFICATION) {
5277                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5278                                    + " : linkgen=" + linkGeneration);
5279                        }
5280                        // Use link-enabled generation as preferredOrder, i.e.
5281                        // prefer newly-enabled over earlier-enabled.
5282                        info.preferredOrder = linkGeneration;
5283                        alwaysList.add(info);
5284                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5285                        if (DEBUG_DOMAIN_VERIFICATION) {
5286                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5287                        }
5288                        neverList.add(info);
5289                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5290                        if (DEBUG_DOMAIN_VERIFICATION) {
5291                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5292                        }
5293                        alwaysAskList.add(info);
5294                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5295                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5296                        if (DEBUG_DOMAIN_VERIFICATION) {
5297                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5298                        }
5299                        undefinedList.add(info);
5300                    }
5301                }
5302            }
5303
5304            // We'll want to include browser possibilities in a few cases
5305            boolean includeBrowser = false;
5306
5307            // First try to add the "always" resolution(s) for the current user, if any
5308            if (alwaysList.size() > 0) {
5309                result.addAll(alwaysList);
5310            } else {
5311                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5312                result.addAll(undefinedList);
5313                // Maybe add one for the other profile.
5314                if (xpDomainInfo != null && (
5315                        xpDomainInfo.bestDomainVerificationStatus
5316                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5317                    result.add(xpDomainInfo.resolveInfo);
5318                }
5319                includeBrowser = true;
5320            }
5321
5322            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5323            // If there were 'always' entries their preferred order has been set, so we also
5324            // back that off to make the alternatives equivalent
5325            if (alwaysAskList.size() > 0) {
5326                for (ResolveInfo i : result) {
5327                    i.preferredOrder = 0;
5328                }
5329                result.addAll(alwaysAskList);
5330                includeBrowser = true;
5331            }
5332
5333            if (includeBrowser) {
5334                // Also add browsers (all of them or only the default one)
5335                if (DEBUG_DOMAIN_VERIFICATION) {
5336                    Slog.v(TAG, "   ...including browsers in candidate set");
5337                }
5338                if ((matchFlags & MATCH_ALL) != 0) {
5339                    result.addAll(matchAllList);
5340                } else {
5341                    // Browser/generic handling case.  If there's a default browser, go straight
5342                    // to that (but only if there is no other higher-priority match).
5343                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5344                    int maxMatchPrio = 0;
5345                    ResolveInfo defaultBrowserMatch = null;
5346                    final int numCandidates = matchAllList.size();
5347                    for (int n = 0; n < numCandidates; n++) {
5348                        ResolveInfo info = matchAllList.get(n);
5349                        // track the highest overall match priority...
5350                        if (info.priority > maxMatchPrio) {
5351                            maxMatchPrio = info.priority;
5352                        }
5353                        // ...and the highest-priority default browser match
5354                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5355                            if (defaultBrowserMatch == null
5356                                    || (defaultBrowserMatch.priority < info.priority)) {
5357                                if (debug) {
5358                                    Slog.v(TAG, "Considering default browser match " + info);
5359                                }
5360                                defaultBrowserMatch = info;
5361                            }
5362                        }
5363                    }
5364                    if (defaultBrowserMatch != null
5365                            && defaultBrowserMatch.priority >= maxMatchPrio
5366                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5367                    {
5368                        if (debug) {
5369                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5370                        }
5371                        result.add(defaultBrowserMatch);
5372                    } else {
5373                        result.addAll(matchAllList);
5374                    }
5375                }
5376
5377                // If there is nothing selected, add all candidates and remove the ones that the user
5378                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5379                if (result.size() == 0) {
5380                    result.addAll(candidates);
5381                    result.removeAll(neverList);
5382                }
5383            }
5384        }
5385        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5386            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5387                    result.size());
5388            for (ResolveInfo info : result) {
5389                Slog.v(TAG, "  + " + info.activityInfo);
5390            }
5391        }
5392        return result;
5393    }
5394
5395    // Returns a packed value as a long:
5396    //
5397    // high 'int'-sized word: link status: undefined/ask/never/always.
5398    // low 'int'-sized word: relative priority among 'always' results.
5399    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5400        long result = ps.getDomainVerificationStatusForUser(userId);
5401        // if none available, get the master status
5402        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5403            if (ps.getIntentFilterVerificationInfo() != null) {
5404                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5405            }
5406        }
5407        return result;
5408    }
5409
5410    private ResolveInfo querySkipCurrentProfileIntents(
5411            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5412            int flags, int sourceUserId) {
5413        if (matchingFilters != null) {
5414            int size = matchingFilters.size();
5415            for (int i = 0; i < size; i ++) {
5416                CrossProfileIntentFilter filter = matchingFilters.get(i);
5417                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5418                    // Checking if there are activities in the target user that can handle the
5419                    // intent.
5420                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5421                            resolvedType, flags, sourceUserId);
5422                    if (resolveInfo != null) {
5423                        return resolveInfo;
5424                    }
5425                }
5426            }
5427        }
5428        return null;
5429    }
5430
5431    // Return matching ResolveInfo in target user if any.
5432    private ResolveInfo queryCrossProfileIntents(
5433            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5434            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5435        if (matchingFilters != null) {
5436            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5437            // match the same intent. For performance reasons, it is better not to
5438            // run queryIntent twice for the same userId
5439            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5440            int size = matchingFilters.size();
5441            for (int i = 0; i < size; i++) {
5442                CrossProfileIntentFilter filter = matchingFilters.get(i);
5443                int targetUserId = filter.getTargetUserId();
5444                boolean skipCurrentProfile =
5445                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5446                boolean skipCurrentProfileIfNoMatchFound =
5447                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5448                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5449                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5450                    // Checking if there are activities in the target user that can handle the
5451                    // intent.
5452                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5453                            resolvedType, flags, sourceUserId);
5454                    if (resolveInfo != null) return resolveInfo;
5455                    alreadyTriedUserIds.put(targetUserId, true);
5456                }
5457            }
5458        }
5459        return null;
5460    }
5461
5462    /**
5463     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5464     * will forward the intent to the filter's target user.
5465     * Otherwise, returns null.
5466     */
5467    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5468            String resolvedType, int flags, int sourceUserId) {
5469        int targetUserId = filter.getTargetUserId();
5470        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5471                resolvedType, flags, targetUserId);
5472        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5473            // If all the matches in the target profile are suspended, return null.
5474            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5475                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5476                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5477                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5478                            targetUserId);
5479                }
5480            }
5481        }
5482        return null;
5483    }
5484
5485    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5486            int sourceUserId, int targetUserId) {
5487        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5488        long ident = Binder.clearCallingIdentity();
5489        boolean targetIsProfile;
5490        try {
5491            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5492        } finally {
5493            Binder.restoreCallingIdentity(ident);
5494        }
5495        String className;
5496        if (targetIsProfile) {
5497            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5498        } else {
5499            className = FORWARD_INTENT_TO_PARENT;
5500        }
5501        ComponentName forwardingActivityComponentName = new ComponentName(
5502                mAndroidApplication.packageName, className);
5503        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5504                sourceUserId);
5505        if (!targetIsProfile) {
5506            forwardingActivityInfo.showUserIcon = targetUserId;
5507            forwardingResolveInfo.noResourceId = true;
5508        }
5509        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5510        forwardingResolveInfo.priority = 0;
5511        forwardingResolveInfo.preferredOrder = 0;
5512        forwardingResolveInfo.match = 0;
5513        forwardingResolveInfo.isDefault = true;
5514        forwardingResolveInfo.filter = filter;
5515        forwardingResolveInfo.targetUserId = targetUserId;
5516        return forwardingResolveInfo;
5517    }
5518
5519    @Override
5520    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5521            Intent[] specifics, String[] specificTypes, Intent intent,
5522            String resolvedType, int flags, int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = updateFlagsForResolve(flags, userId, intent);
5525        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5526                false /* requireFullPermission */, false /* checkShell */,
5527                "query intent activity options");
5528        final String resultsAction = intent.getAction();
5529
5530        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5531                | PackageManager.GET_RESOLVED_FILTER, userId);
5532
5533        if (DEBUG_INTENT_MATCHING) {
5534            Log.v(TAG, "Query " + intent + ": " + results);
5535        }
5536
5537        int specificsPos = 0;
5538        int N;
5539
5540        // todo: note that the algorithm used here is O(N^2).  This
5541        // isn't a problem in our current environment, but if we start running
5542        // into situations where we have more than 5 or 10 matches then this
5543        // should probably be changed to something smarter...
5544
5545        // First we go through and resolve each of the specific items
5546        // that were supplied, taking care of removing any corresponding
5547        // duplicate items in the generic resolve list.
5548        if (specifics != null) {
5549            for (int i=0; i<specifics.length; i++) {
5550                final Intent sintent = specifics[i];
5551                if (sintent == null) {
5552                    continue;
5553                }
5554
5555                if (DEBUG_INTENT_MATCHING) {
5556                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5557                }
5558
5559                String action = sintent.getAction();
5560                if (resultsAction != null && resultsAction.equals(action)) {
5561                    // If this action was explicitly requested, then don't
5562                    // remove things that have it.
5563                    action = null;
5564                }
5565
5566                ResolveInfo ri = null;
5567                ActivityInfo ai = null;
5568
5569                ComponentName comp = sintent.getComponent();
5570                if (comp == null) {
5571                    ri = resolveIntent(
5572                        sintent,
5573                        specificTypes != null ? specificTypes[i] : null,
5574                            flags, userId);
5575                    if (ri == null) {
5576                        continue;
5577                    }
5578                    if (ri == mResolveInfo) {
5579                        // ACK!  Must do something better with this.
5580                    }
5581                    ai = ri.activityInfo;
5582                    comp = new ComponentName(ai.applicationInfo.packageName,
5583                            ai.name);
5584                } else {
5585                    ai = getActivityInfo(comp, flags, userId);
5586                    if (ai == null) {
5587                        continue;
5588                    }
5589                }
5590
5591                // Look for any generic query activities that are duplicates
5592                // of this specific one, and remove them from the results.
5593                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5594                N = results.size();
5595                int j;
5596                for (j=specificsPos; j<N; j++) {
5597                    ResolveInfo sri = results.get(j);
5598                    if ((sri.activityInfo.name.equals(comp.getClassName())
5599                            && sri.activityInfo.applicationInfo.packageName.equals(
5600                                    comp.getPackageName()))
5601                        || (action != null && sri.filter.matchAction(action))) {
5602                        results.remove(j);
5603                        if (DEBUG_INTENT_MATCHING) Log.v(
5604                            TAG, "Removing duplicate item from " + j
5605                            + " due to specific " + specificsPos);
5606                        if (ri == null) {
5607                            ri = sri;
5608                        }
5609                        j--;
5610                        N--;
5611                    }
5612                }
5613
5614                // Add this specific item to its proper place.
5615                if (ri == null) {
5616                    ri = new ResolveInfo();
5617                    ri.activityInfo = ai;
5618                }
5619                results.add(specificsPos, ri);
5620                ri.specificIndex = i;
5621                specificsPos++;
5622            }
5623        }
5624
5625        // Now we go through the remaining generic results and remove any
5626        // duplicate actions that are found here.
5627        N = results.size();
5628        for (int i=specificsPos; i<N-1; i++) {
5629            final ResolveInfo rii = results.get(i);
5630            if (rii.filter == null) {
5631                continue;
5632            }
5633
5634            // Iterate over all of the actions of this result's intent
5635            // filter...  typically this should be just one.
5636            final Iterator<String> it = rii.filter.actionsIterator();
5637            if (it == null) {
5638                continue;
5639            }
5640            while (it.hasNext()) {
5641                final String action = it.next();
5642                if (resultsAction != null && resultsAction.equals(action)) {
5643                    // If this action was explicitly requested, then don't
5644                    // remove things that have it.
5645                    continue;
5646                }
5647                for (int j=i+1; j<N; j++) {
5648                    final ResolveInfo rij = results.get(j);
5649                    if (rij.filter != null && rij.filter.hasAction(action)) {
5650                        results.remove(j);
5651                        if (DEBUG_INTENT_MATCHING) Log.v(
5652                            TAG, "Removing duplicate item from " + j
5653                            + " due to action " + action + " at " + i);
5654                        j--;
5655                        N--;
5656                    }
5657                }
5658            }
5659
5660            // If the caller didn't request filter information, drop it now
5661            // so we don't have to marshall/unmarshall it.
5662            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5663                rii.filter = null;
5664            }
5665        }
5666
5667        // Filter out the caller activity if so requested.
5668        if (caller != null) {
5669            N = results.size();
5670            for (int i=0; i<N; i++) {
5671                ActivityInfo ainfo = results.get(i).activityInfo;
5672                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5673                        && caller.getClassName().equals(ainfo.name)) {
5674                    results.remove(i);
5675                    break;
5676                }
5677            }
5678        }
5679
5680        // If the caller didn't request filter information,
5681        // drop them now so we don't have to
5682        // marshall/unmarshall it.
5683        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5684            N = results.size();
5685            for (int i=0; i<N; i++) {
5686                results.get(i).filter = null;
5687            }
5688        }
5689
5690        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5691        return results;
5692    }
5693
5694    @Override
5695    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5696            int userId) {
5697        if (!sUserManager.exists(userId)) return Collections.emptyList();
5698        flags = updateFlagsForResolve(flags, userId, intent);
5699        ComponentName comp = intent.getComponent();
5700        if (comp == null) {
5701            if (intent.getSelector() != null) {
5702                intent = intent.getSelector();
5703                comp = intent.getComponent();
5704            }
5705        }
5706        if (comp != null) {
5707            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5708            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5709            if (ai != null) {
5710                ResolveInfo ri = new ResolveInfo();
5711                ri.activityInfo = ai;
5712                list.add(ri);
5713            }
5714            return list;
5715        }
5716
5717        // reader
5718        synchronized (mPackages) {
5719            String pkgName = intent.getPackage();
5720            if (pkgName == null) {
5721                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5722            }
5723            final PackageParser.Package pkg = mPackages.get(pkgName);
5724            if (pkg != null) {
5725                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5726                        userId);
5727            }
5728            return null;
5729        }
5730    }
5731
5732    @Override
5733    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5734        if (!sUserManager.exists(userId)) return null;
5735        flags = updateFlagsForResolve(flags, userId, intent);
5736        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5737        if (query != null) {
5738            if (query.size() >= 1) {
5739                // If there is more than one service with the same priority,
5740                // just arbitrarily pick the first one.
5741                return query.get(0);
5742            }
5743        }
5744        return null;
5745    }
5746
5747    @Override
5748    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5749            int userId) {
5750        if (!sUserManager.exists(userId)) return Collections.emptyList();
5751        flags = updateFlagsForResolve(flags, userId, intent);
5752        ComponentName comp = intent.getComponent();
5753        if (comp == null) {
5754            if (intent.getSelector() != null) {
5755                intent = intent.getSelector();
5756                comp = intent.getComponent();
5757            }
5758        }
5759        if (comp != null) {
5760            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5761            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5762            if (si != null) {
5763                final ResolveInfo ri = new ResolveInfo();
5764                ri.serviceInfo = si;
5765                list.add(ri);
5766            }
5767            return list;
5768        }
5769
5770        // reader
5771        synchronized (mPackages) {
5772            String pkgName = intent.getPackage();
5773            if (pkgName == null) {
5774                return mServices.queryIntent(intent, resolvedType, flags, userId);
5775            }
5776            final PackageParser.Package pkg = mPackages.get(pkgName);
5777            if (pkg != null) {
5778                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5779                        userId);
5780            }
5781            return null;
5782        }
5783    }
5784
5785    @Override
5786    public List<ResolveInfo> queryIntentContentProviders(
5787            Intent intent, String resolvedType, int flags, int userId) {
5788        if (!sUserManager.exists(userId)) return Collections.emptyList();
5789        flags = updateFlagsForResolve(flags, userId, intent);
5790        ComponentName comp = intent.getComponent();
5791        if (comp == null) {
5792            if (intent.getSelector() != null) {
5793                intent = intent.getSelector();
5794                comp = intent.getComponent();
5795            }
5796        }
5797        if (comp != null) {
5798            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5799            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5800            if (pi != null) {
5801                final ResolveInfo ri = new ResolveInfo();
5802                ri.providerInfo = pi;
5803                list.add(ri);
5804            }
5805            return list;
5806        }
5807
5808        // reader
5809        synchronized (mPackages) {
5810            String pkgName = intent.getPackage();
5811            if (pkgName == null) {
5812                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5813            }
5814            final PackageParser.Package pkg = mPackages.get(pkgName);
5815            if (pkg != null) {
5816                return mProviders.queryIntentForPackage(
5817                        intent, resolvedType, flags, pkg.providers, userId);
5818            }
5819            return null;
5820        }
5821    }
5822
5823    @Override
5824    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5825        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5826        flags = updateFlagsForPackage(flags, userId, null);
5827        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5828        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5829                true /* requireFullPermission */, false /* checkShell */,
5830                "get installed packages");
5831
5832        // writer
5833        synchronized (mPackages) {
5834            ArrayList<PackageInfo> list;
5835            if (listUninstalled) {
5836                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5837                for (PackageSetting ps : mSettings.mPackages.values()) {
5838                    PackageInfo pi;
5839                    if (ps.pkg != null) {
5840                        pi = generatePackageInfo(ps.pkg, flags, userId);
5841                    } else {
5842                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5843                    }
5844                    if (pi != null) {
5845                        list.add(pi);
5846                    }
5847                }
5848            } else {
5849                list = new ArrayList<PackageInfo>(mPackages.size());
5850                for (PackageParser.Package p : mPackages.values()) {
5851                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5852                    if (pi != null) {
5853                        list.add(pi);
5854                    }
5855                }
5856            }
5857
5858            return new ParceledListSlice<PackageInfo>(list);
5859        }
5860    }
5861
5862    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5863            String[] permissions, boolean[] tmp, int flags, int userId) {
5864        int numMatch = 0;
5865        final PermissionsState permissionsState = ps.getPermissionsState();
5866        for (int i=0; i<permissions.length; i++) {
5867            final String permission = permissions[i];
5868            if (permissionsState.hasPermission(permission, userId)) {
5869                tmp[i] = true;
5870                numMatch++;
5871            } else {
5872                tmp[i] = false;
5873            }
5874        }
5875        if (numMatch == 0) {
5876            return;
5877        }
5878        PackageInfo pi;
5879        if (ps.pkg != null) {
5880            pi = generatePackageInfo(ps.pkg, flags, userId);
5881        } else {
5882            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5883        }
5884        // The above might return null in cases of uninstalled apps or install-state
5885        // skew across users/profiles.
5886        if (pi != null) {
5887            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5888                if (numMatch == permissions.length) {
5889                    pi.requestedPermissions = permissions;
5890                } else {
5891                    pi.requestedPermissions = new String[numMatch];
5892                    numMatch = 0;
5893                    for (int i=0; i<permissions.length; i++) {
5894                        if (tmp[i]) {
5895                            pi.requestedPermissions[numMatch] = permissions[i];
5896                            numMatch++;
5897                        }
5898                    }
5899                }
5900            }
5901            list.add(pi);
5902        }
5903    }
5904
5905    @Override
5906    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5907            String[] permissions, int flags, int userId) {
5908        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5909        flags = updateFlagsForPackage(flags, userId, permissions);
5910        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5911
5912        // writer
5913        synchronized (mPackages) {
5914            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5915            boolean[] tmpBools = new boolean[permissions.length];
5916            if (listUninstalled) {
5917                for (PackageSetting ps : mSettings.mPackages.values()) {
5918                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5919                }
5920            } else {
5921                for (PackageParser.Package pkg : mPackages.values()) {
5922                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5923                    if (ps != null) {
5924                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5925                                userId);
5926                    }
5927                }
5928            }
5929
5930            return new ParceledListSlice<PackageInfo>(list);
5931        }
5932    }
5933
5934    @Override
5935    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5936        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5937        flags = updateFlagsForApplication(flags, userId, null);
5938        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5939
5940        // writer
5941        synchronized (mPackages) {
5942            ArrayList<ApplicationInfo> list;
5943            if (listUninstalled) {
5944                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5945                for (PackageSetting ps : mSettings.mPackages.values()) {
5946                    ApplicationInfo ai;
5947                    if (ps.pkg != null) {
5948                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5949                                ps.readUserState(userId), userId);
5950                    } else {
5951                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5952                    }
5953                    if (ai != null) {
5954                        list.add(ai);
5955                    }
5956                }
5957            } else {
5958                list = new ArrayList<ApplicationInfo>(mPackages.size());
5959                for (PackageParser.Package p : mPackages.values()) {
5960                    if (p.mExtras != null) {
5961                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5962                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5963                        if (ai != null) {
5964                            list.add(ai);
5965                        }
5966                    }
5967                }
5968            }
5969
5970            return new ParceledListSlice<ApplicationInfo>(list);
5971        }
5972    }
5973
5974    @Override
5975    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5976        if (DISABLE_EPHEMERAL_APPS) {
5977            return null;
5978        }
5979
5980        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5981                "getEphemeralApplications");
5982        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5983                true /* requireFullPermission */, false /* checkShell */,
5984                "getEphemeralApplications");
5985        synchronized (mPackages) {
5986            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5987                    .getEphemeralApplicationsLPw(userId);
5988            if (ephemeralApps != null) {
5989                return new ParceledListSlice<>(ephemeralApps);
5990            }
5991        }
5992        return null;
5993    }
5994
5995    @Override
5996    public boolean isEphemeralApplication(String packageName, int userId) {
5997        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5998                true /* requireFullPermission */, false /* checkShell */,
5999                "isEphemeral");
6000        if (DISABLE_EPHEMERAL_APPS) {
6001            return false;
6002        }
6003
6004        if (!isCallerSameApp(packageName)) {
6005            return false;
6006        }
6007        synchronized (mPackages) {
6008            PackageParser.Package pkg = mPackages.get(packageName);
6009            if (pkg != null) {
6010                return pkg.applicationInfo.isEphemeralApp();
6011            }
6012        }
6013        return false;
6014    }
6015
6016    @Override
6017    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6018        if (DISABLE_EPHEMERAL_APPS) {
6019            return null;
6020        }
6021
6022        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6023                true /* requireFullPermission */, false /* checkShell */,
6024                "getCookie");
6025        if (!isCallerSameApp(packageName)) {
6026            return null;
6027        }
6028        synchronized (mPackages) {
6029            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6030                    packageName, userId);
6031        }
6032    }
6033
6034    @Override
6035    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6036        if (DISABLE_EPHEMERAL_APPS) {
6037            return true;
6038        }
6039
6040        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6041                true /* requireFullPermission */, true /* checkShell */,
6042                "setCookie");
6043        if (!isCallerSameApp(packageName)) {
6044            return false;
6045        }
6046        synchronized (mPackages) {
6047            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6048                    packageName, cookie, userId);
6049        }
6050    }
6051
6052    @Override
6053    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6054        if (DISABLE_EPHEMERAL_APPS) {
6055            return null;
6056        }
6057
6058        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6059                "getEphemeralApplicationIcon");
6060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6061                true /* requireFullPermission */, false /* checkShell */,
6062                "getEphemeralApplicationIcon");
6063        synchronized (mPackages) {
6064            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6065                    packageName, userId);
6066        }
6067    }
6068
6069    private boolean isCallerSameApp(String packageName) {
6070        PackageParser.Package pkg = mPackages.get(packageName);
6071        return pkg != null
6072                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6073    }
6074
6075    public List<ApplicationInfo> getPersistentApplications(int flags) {
6076        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6077
6078        // reader
6079        synchronized (mPackages) {
6080            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6081            final int userId = UserHandle.getCallingUserId();
6082            while (i.hasNext()) {
6083                final PackageParser.Package p = i.next();
6084                if (p.applicationInfo == null) continue;
6085
6086                final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0)
6087                        && !p.applicationInfo.isEncryptionAware();
6088                final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0)
6089                        && p.applicationInfo.isEncryptionAware();
6090
6091                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6092                        && (!mSafeMode || isSystemApp(p))
6093                        && (matchesUnaware || matchesAware)) {
6094                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6095                    if (ps != null) {
6096                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6097                                ps.readUserState(userId), userId);
6098                        if (ai != null) {
6099                            finalList.add(ai);
6100                        }
6101                    }
6102                }
6103            }
6104        }
6105
6106        return finalList;
6107    }
6108
6109    @Override
6110    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6111        if (!sUserManager.exists(userId)) return null;
6112        flags = updateFlagsForComponent(flags, userId, name);
6113        // reader
6114        synchronized (mPackages) {
6115            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6116            PackageSetting ps = provider != null
6117                    ? mSettings.mPackages.get(provider.owner.packageName)
6118                    : null;
6119            return ps != null
6120                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6121                    ? PackageParser.generateProviderInfo(provider, flags,
6122                            ps.readUserState(userId), userId)
6123                    : null;
6124        }
6125    }
6126
6127    /**
6128     * @deprecated
6129     */
6130    @Deprecated
6131    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6132        // reader
6133        synchronized (mPackages) {
6134            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6135                    .entrySet().iterator();
6136            final int userId = UserHandle.getCallingUserId();
6137            while (i.hasNext()) {
6138                Map.Entry<String, PackageParser.Provider> entry = i.next();
6139                PackageParser.Provider p = entry.getValue();
6140                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6141
6142                if (ps != null && p.syncable
6143                        && (!mSafeMode || (p.info.applicationInfo.flags
6144                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6145                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6146                            ps.readUserState(userId), userId);
6147                    if (info != null) {
6148                        outNames.add(entry.getKey());
6149                        outInfo.add(info);
6150                    }
6151                }
6152            }
6153        }
6154    }
6155
6156    @Override
6157    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6158            int uid, int flags) {
6159        final int userId = processName != null ? UserHandle.getUserId(uid)
6160                : UserHandle.getCallingUserId();
6161        if (!sUserManager.exists(userId)) return null;
6162        flags = updateFlagsForComponent(flags, userId, processName);
6163
6164        ArrayList<ProviderInfo> finalList = null;
6165        // reader
6166        synchronized (mPackages) {
6167            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6168            while (i.hasNext()) {
6169                final PackageParser.Provider p = i.next();
6170                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6171                if (ps != null && p.info.authority != null
6172                        && (processName == null
6173                                || (p.info.processName.equals(processName)
6174                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6175                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6176                    if (finalList == null) {
6177                        finalList = new ArrayList<ProviderInfo>(3);
6178                    }
6179                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6180                            ps.readUserState(userId), userId);
6181                    if (info != null) {
6182                        finalList.add(info);
6183                    }
6184                }
6185            }
6186        }
6187
6188        if (finalList != null) {
6189            Collections.sort(finalList, mProviderInitOrderSorter);
6190            return new ParceledListSlice<ProviderInfo>(finalList);
6191        }
6192
6193        return null;
6194    }
6195
6196    @Override
6197    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6198        // reader
6199        synchronized (mPackages) {
6200            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6201            return PackageParser.generateInstrumentationInfo(i, flags);
6202        }
6203    }
6204
6205    @Override
6206    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6207            int flags) {
6208        ArrayList<InstrumentationInfo> finalList =
6209            new ArrayList<InstrumentationInfo>();
6210
6211        // reader
6212        synchronized (mPackages) {
6213            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6214            while (i.hasNext()) {
6215                final PackageParser.Instrumentation p = i.next();
6216                if (targetPackage == null
6217                        || targetPackage.equals(p.info.targetPackage)) {
6218                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6219                            flags);
6220                    if (ii != null) {
6221                        finalList.add(ii);
6222                    }
6223                }
6224            }
6225        }
6226
6227        return finalList;
6228    }
6229
6230    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6231        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6232        if (overlays == null) {
6233            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6234            return;
6235        }
6236        for (PackageParser.Package opkg : overlays.values()) {
6237            // Not much to do if idmap fails: we already logged the error
6238            // and we certainly don't want to abort installation of pkg simply
6239            // because an overlay didn't fit properly. For these reasons,
6240            // ignore the return value of createIdmapForPackagePairLI.
6241            createIdmapForPackagePairLI(pkg, opkg);
6242        }
6243    }
6244
6245    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6246            PackageParser.Package opkg) {
6247        if (!opkg.mTrustedOverlay) {
6248            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6249                    opkg.baseCodePath + ": overlay not trusted");
6250            return false;
6251        }
6252        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6253        if (overlaySet == null) {
6254            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6255                    opkg.baseCodePath + " but target package has no known overlays");
6256            return false;
6257        }
6258        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6259        // TODO: generate idmap for split APKs
6260        try {
6261            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6262        } catch (InstallerException e) {
6263            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6264                    + opkg.baseCodePath);
6265            return false;
6266        }
6267        PackageParser.Package[] overlayArray =
6268            overlaySet.values().toArray(new PackageParser.Package[0]);
6269        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6270            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6271                return p1.mOverlayPriority - p2.mOverlayPriority;
6272            }
6273        };
6274        Arrays.sort(overlayArray, cmp);
6275
6276        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6277        int i = 0;
6278        for (PackageParser.Package p : overlayArray) {
6279            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6280        }
6281        return true;
6282    }
6283
6284    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6286        try {
6287            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6288        } finally {
6289            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6290        }
6291    }
6292
6293    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6294        final File[] files = dir.listFiles();
6295        if (ArrayUtils.isEmpty(files)) {
6296            Log.d(TAG, "No files in app dir " + dir);
6297            return;
6298        }
6299
6300        if (DEBUG_PACKAGE_SCANNING) {
6301            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6302                    + " flags=0x" + Integer.toHexString(parseFlags));
6303        }
6304
6305        for (File file : files) {
6306            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6307                    && !PackageInstallerService.isStageName(file.getName());
6308            if (!isPackage) {
6309                // Ignore entries which are not packages
6310                continue;
6311            }
6312            try {
6313                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6314                        scanFlags, currentTime, null);
6315            } catch (PackageManagerException e) {
6316                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6317
6318                // Delete invalid userdata apps
6319                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6320                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6321                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6322                    removeCodePathLI(file);
6323                }
6324            }
6325        }
6326    }
6327
6328    private static File getSettingsProblemFile() {
6329        File dataDir = Environment.getDataDirectory();
6330        File systemDir = new File(dataDir, "system");
6331        File fname = new File(systemDir, "uiderrors.txt");
6332        return fname;
6333    }
6334
6335    static void reportSettingsProblem(int priority, String msg) {
6336        logCriticalInfo(priority, msg);
6337    }
6338
6339    static void logCriticalInfo(int priority, String msg) {
6340        Slog.println(priority, TAG, msg);
6341        EventLogTags.writePmCriticalInfo(msg);
6342        try {
6343            File fname = getSettingsProblemFile();
6344            FileOutputStream out = new FileOutputStream(fname, true);
6345            PrintWriter pw = new FastPrintWriter(out);
6346            SimpleDateFormat formatter = new SimpleDateFormat();
6347            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6348            pw.println(dateString + ": " + msg);
6349            pw.close();
6350            FileUtils.setPermissions(
6351                    fname.toString(),
6352                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6353                    -1, -1);
6354        } catch (java.io.IOException e) {
6355        }
6356    }
6357
6358    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6359            int parseFlags) throws PackageManagerException {
6360        if (ps != null
6361                && ps.codePath.equals(srcFile)
6362                && ps.timeStamp == srcFile.lastModified()
6363                && !isCompatSignatureUpdateNeeded(pkg)
6364                && !isRecoverSignatureUpdateNeeded(pkg)) {
6365            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6366            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6367            ArraySet<PublicKey> signingKs;
6368            synchronized (mPackages) {
6369                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6370            }
6371            if (ps.signatures.mSignatures != null
6372                    && ps.signatures.mSignatures.length != 0
6373                    && signingKs != null) {
6374                // Optimization: reuse the existing cached certificates
6375                // if the package appears to be unchanged.
6376                pkg.mSignatures = ps.signatures.mSignatures;
6377                pkg.mSigningKeys = signingKs;
6378                return;
6379            }
6380
6381            Slog.w(TAG, "PackageSetting for " + ps.name
6382                    + " is missing signatures.  Collecting certs again to recover them.");
6383        } else {
6384            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6385        }
6386
6387        try {
6388            PackageParser.collectCertificates(pkg, parseFlags);
6389        } catch (PackageParserException e) {
6390            throw PackageManagerException.from(e);
6391        }
6392    }
6393
6394    /**
6395     *  Traces a package scan.
6396     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6397     */
6398    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6399            long currentTime, UserHandle user) throws PackageManagerException {
6400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6401        try {
6402            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6403        } finally {
6404            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6405        }
6406    }
6407
6408    /**
6409     *  Scans a package and returns the newly parsed package.
6410     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6411     */
6412    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6413            long currentTime, UserHandle user) throws PackageManagerException {
6414        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6415        parseFlags |= mDefParseFlags;
6416        PackageParser pp = new PackageParser();
6417        pp.setSeparateProcesses(mSeparateProcesses);
6418        pp.setOnlyCoreApps(mOnlyCore);
6419        pp.setDisplayMetrics(mMetrics);
6420
6421        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6422            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6423        }
6424
6425        final PackageParser.Package pkg;
6426        try {
6427            pkg = pp.parsePackage(scanFile, parseFlags);
6428        } catch (PackageParserException e) {
6429            throw PackageManagerException.from(e);
6430        }
6431
6432        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6433    }
6434
6435    /**
6436     *  Scans a package and returns the newly parsed package.
6437     *  @throws PackageManagerException on a parse error.
6438     */
6439    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6440            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6441            throws PackageManagerException {
6442        // If the package has children and this is the first dive in the function
6443        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6444        // packages (parent and children) would be successfully scanned before the
6445        // actual scan since scanning mutates internal state and we want to atomically
6446        // install the package and its children.
6447        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6448            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6449                scanFlags |= SCAN_CHECK_ONLY;
6450            }
6451        } else {
6452            scanFlags &= ~SCAN_CHECK_ONLY;
6453        }
6454
6455        // Scan the parent
6456        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6457                scanFlags, currentTime, user);
6458
6459        // Scan the children
6460        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6461        for (int i = 0; i < childCount; i++) {
6462            PackageParser.Package childPackage = pkg.childPackages.get(i);
6463            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6464                    currentTime, user);
6465        }
6466
6467
6468        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6469            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6470        }
6471
6472        return scannedPkg;
6473    }
6474
6475    /**
6476     *  Scans a package and returns the newly parsed package.
6477     *  @throws PackageManagerException on a parse error.
6478     */
6479    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6480            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6481            throws PackageManagerException {
6482        PackageSetting ps = null;
6483        PackageSetting updatedPkg;
6484        // reader
6485        synchronized (mPackages) {
6486            // Look to see if we already know about this package.
6487            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6488            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6489                // This package has been renamed to its original name.  Let's
6490                // use that.
6491                ps = mSettings.peekPackageLPr(oldName);
6492            }
6493            // If there was no original package, see one for the real package name.
6494            if (ps == null) {
6495                ps = mSettings.peekPackageLPr(pkg.packageName);
6496            }
6497            // Check to see if this package could be hiding/updating a system
6498            // package.  Must look for it either under the original or real
6499            // package name depending on our state.
6500            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6501            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6502
6503            // If this is a package we don't know about on the system partition, we
6504            // may need to remove disabled child packages on the system partition
6505            // or may need to not add child packages if the parent apk is updated
6506            // on the data partition and no longer defines this child package.
6507            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6508                // If this is a parent package for an updated system app and this system
6509                // app got an OTA update which no longer defines some of the child packages
6510                // we have to prune them from the disabled system packages.
6511                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6512                if (disabledPs != null) {
6513                    final int scannedChildCount = (pkg.childPackages != null)
6514                            ? pkg.childPackages.size() : 0;
6515                    final int disabledChildCount = disabledPs.childPackageNames != null
6516                            ? disabledPs.childPackageNames.size() : 0;
6517                    for (int i = 0; i < disabledChildCount; i++) {
6518                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6519                        boolean disabledPackageAvailable = false;
6520                        for (int j = 0; j < scannedChildCount; j++) {
6521                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6522                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6523                                disabledPackageAvailable = true;
6524                                break;
6525                            }
6526                         }
6527                         if (!disabledPackageAvailable) {
6528                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6529                         }
6530                    }
6531                }
6532            }
6533        }
6534
6535        boolean updatedPkgBetter = false;
6536        // First check if this is a system package that may involve an update
6537        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6538            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6539            // it needs to drop FLAG_PRIVILEGED.
6540            if (locationIsPrivileged(scanFile)) {
6541                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6542            } else {
6543                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6544            }
6545
6546            if (ps != null && !ps.codePath.equals(scanFile)) {
6547                // The path has changed from what was last scanned...  check the
6548                // version of the new path against what we have stored to determine
6549                // what to do.
6550                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6551                if (pkg.mVersionCode <= ps.versionCode) {
6552                    // The system package has been updated and the code path does not match
6553                    // Ignore entry. Skip it.
6554                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6555                            + " ignored: updated version " + ps.versionCode
6556                            + " better than this " + pkg.mVersionCode);
6557                    if (!updatedPkg.codePath.equals(scanFile)) {
6558                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6559                                + ps.name + " changing from " + updatedPkg.codePathString
6560                                + " to " + scanFile);
6561                        updatedPkg.codePath = scanFile;
6562                        updatedPkg.codePathString = scanFile.toString();
6563                        updatedPkg.resourcePath = scanFile;
6564                        updatedPkg.resourcePathString = scanFile.toString();
6565                    }
6566                    updatedPkg.pkg = pkg;
6567                    updatedPkg.versionCode = pkg.mVersionCode;
6568
6569                    // Update the disabled system child packages to point to the package too.
6570                    final int childCount = updatedPkg.childPackageNames != null
6571                            ? updatedPkg.childPackageNames.size() : 0;
6572                    for (int i = 0; i < childCount; i++) {
6573                        String childPackageName = updatedPkg.childPackageNames.get(i);
6574                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6575                                childPackageName);
6576                        if (updatedChildPkg != null) {
6577                            updatedChildPkg.pkg = pkg;
6578                            updatedChildPkg.versionCode = pkg.mVersionCode;
6579                        }
6580                    }
6581
6582                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6583                            + scanFile + " ignored: updated version " + ps.versionCode
6584                            + " better than this " + pkg.mVersionCode);
6585                } else {
6586                    // The current app on the system partition is better than
6587                    // what we have updated to on the data partition; switch
6588                    // back to the system partition version.
6589                    // At this point, its safely assumed that package installation for
6590                    // apps in system partition will go through. If not there won't be a working
6591                    // version of the app
6592                    // writer
6593                    synchronized (mPackages) {
6594                        // Just remove the loaded entries from package lists.
6595                        mPackages.remove(ps.name);
6596                    }
6597
6598                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6599                            + " reverting from " + ps.codePathString
6600                            + ": new version " + pkg.mVersionCode
6601                            + " better than installed " + ps.versionCode);
6602
6603                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6604                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6605                    synchronized (mInstallLock) {
6606                        args.cleanUpResourcesLI();
6607                    }
6608                    synchronized (mPackages) {
6609                        mSettings.enableSystemPackageLPw(ps.name);
6610                    }
6611                    updatedPkgBetter = true;
6612                }
6613            }
6614        }
6615
6616        if (updatedPkg != null) {
6617            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6618            // initially
6619            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6620
6621            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6622            // flag set initially
6623            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6624                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6625            }
6626        }
6627
6628        // Verify certificates against what was last scanned
6629        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6630
6631        /*
6632         * A new system app appeared, but we already had a non-system one of the
6633         * same name installed earlier.
6634         */
6635        boolean shouldHideSystemApp = false;
6636        if (updatedPkg == null && ps != null
6637                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6638            /*
6639             * Check to make sure the signatures match first. If they don't,
6640             * wipe the installed application and its data.
6641             */
6642            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6643                    != PackageManager.SIGNATURE_MATCH) {
6644                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6645                        + " signatures don't match existing userdata copy; removing");
6646                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6647                ps = null;
6648            } else {
6649                /*
6650                 * If the newly-added system app is an older version than the
6651                 * already installed version, hide it. It will be scanned later
6652                 * and re-added like an update.
6653                 */
6654                if (pkg.mVersionCode <= ps.versionCode) {
6655                    shouldHideSystemApp = true;
6656                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6657                            + " but new version " + pkg.mVersionCode + " better than installed "
6658                            + ps.versionCode + "; hiding system");
6659                } else {
6660                    /*
6661                     * The newly found system app is a newer version that the
6662                     * one previously installed. Simply remove the
6663                     * already-installed application and replace it with our own
6664                     * while keeping the application data.
6665                     */
6666                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6667                            + " reverting from " + ps.codePathString + ": new version "
6668                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6669                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6670                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6671                    synchronized (mInstallLock) {
6672                        args.cleanUpResourcesLI();
6673                    }
6674                }
6675            }
6676        }
6677
6678        // The apk is forward locked (not public) if its code and resources
6679        // are kept in different files. (except for app in either system or
6680        // vendor path).
6681        // TODO grab this value from PackageSettings
6682        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6683            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6684                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6685            }
6686        }
6687
6688        // TODO: extend to support forward-locked splits
6689        String resourcePath = null;
6690        String baseResourcePath = null;
6691        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6692            if (ps != null && ps.resourcePathString != null) {
6693                resourcePath = ps.resourcePathString;
6694                baseResourcePath = ps.resourcePathString;
6695            } else {
6696                // Should not happen at all. Just log an error.
6697                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6698            }
6699        } else {
6700            resourcePath = pkg.codePath;
6701            baseResourcePath = pkg.baseCodePath;
6702        }
6703
6704        // Set application objects path explicitly.
6705        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6706        pkg.setApplicationInfoCodePath(pkg.codePath);
6707        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6708        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6709        pkg.setApplicationInfoResourcePath(resourcePath);
6710        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6711        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6712
6713        // Note that we invoke the following method only if we are about to unpack an application
6714        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6715                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6716
6717        /*
6718         * If the system app should be overridden by a previously installed
6719         * data, hide the system app now and let the /data/app scan pick it up
6720         * again.
6721         */
6722        if (shouldHideSystemApp) {
6723            synchronized (mPackages) {
6724                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6725            }
6726        }
6727
6728        return scannedPkg;
6729    }
6730
6731    private static String fixProcessName(String defProcessName,
6732            String processName, int uid) {
6733        if (processName == null) {
6734            return defProcessName;
6735        }
6736        return processName;
6737    }
6738
6739    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6740            throws PackageManagerException {
6741        if (pkgSetting.signatures.mSignatures != null) {
6742            // Already existing package. Make sure signatures match
6743            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6744                    == PackageManager.SIGNATURE_MATCH;
6745            if (!match) {
6746                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6747                        == PackageManager.SIGNATURE_MATCH;
6748            }
6749            if (!match) {
6750                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6751                        == PackageManager.SIGNATURE_MATCH;
6752            }
6753            if (!match) {
6754                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6755                        + pkg.packageName + " signatures do not match the "
6756                        + "previously installed version; ignoring!");
6757            }
6758        }
6759
6760        // Check for shared user signatures
6761        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6762            // Already existing package. Make sure signatures match
6763            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6764                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6765            if (!match) {
6766                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6767                        == PackageManager.SIGNATURE_MATCH;
6768            }
6769            if (!match) {
6770                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6771                        == PackageManager.SIGNATURE_MATCH;
6772            }
6773            if (!match) {
6774                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6775                        "Package " + pkg.packageName
6776                        + " has no signatures that match those in shared user "
6777                        + pkgSetting.sharedUser.name + "; ignoring!");
6778            }
6779        }
6780    }
6781
6782    /**
6783     * Enforces that only the system UID or root's UID can call a method exposed
6784     * via Binder.
6785     *
6786     * @param message used as message if SecurityException is thrown
6787     * @throws SecurityException if the caller is not system or root
6788     */
6789    private static final void enforceSystemOrRoot(String message) {
6790        final int uid = Binder.getCallingUid();
6791        if (uid != Process.SYSTEM_UID && uid != 0) {
6792            throw new SecurityException(message);
6793        }
6794    }
6795
6796    @Override
6797    public void performFstrimIfNeeded() {
6798        enforceSystemOrRoot("Only the system can request fstrim");
6799
6800        // Before everything else, see whether we need to fstrim.
6801        try {
6802            IMountService ms = PackageHelper.getMountService();
6803            if (ms != null) {
6804                final boolean isUpgrade = isUpgrade();
6805                boolean doTrim = isUpgrade;
6806                if (doTrim) {
6807                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6808                } else {
6809                    final long interval = android.provider.Settings.Global.getLong(
6810                            mContext.getContentResolver(),
6811                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6812                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6813                    if (interval > 0) {
6814                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6815                        if (timeSinceLast > interval) {
6816                            doTrim = true;
6817                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6818                                    + "; running immediately");
6819                        }
6820                    }
6821                }
6822                if (doTrim) {
6823                    if (!isFirstBoot()) {
6824                        try {
6825                            ActivityManagerNative.getDefault().showBootMessage(
6826                                    mContext.getResources().getString(
6827                                            R.string.android_upgrading_fstrim), true);
6828                        } catch (RemoteException e) {
6829                        }
6830                    }
6831                    ms.runMaintenance();
6832                }
6833            } else {
6834                Slog.e(TAG, "Mount service unavailable!");
6835            }
6836        } catch (RemoteException e) {
6837            // Can't happen; MountService is local
6838        }
6839    }
6840
6841    @Override
6842    public void extractPackagesIfNeeded() {
6843        enforceSystemOrRoot("Only the system can request package extraction");
6844
6845        // Extract pacakges only if profile-guided compilation is enabled because
6846        // otherwise BackgroundDexOptService will not dexopt them later.
6847        if (!isUpgrade()) {
6848            return;
6849        }
6850
6851        List<PackageParser.Package> pkgs;
6852        synchronized (mPackages) {
6853            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6854        }
6855
6856        int curr = 0;
6857        int total = pkgs.size();
6858        for (PackageParser.Package pkg : pkgs) {
6859            curr++;
6860
6861            if (DEBUG_DEXOPT) {
6862                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6863            }
6864
6865            if (!isFirstBoot()) {
6866                try {
6867                    ActivityManagerNative.getDefault().showBootMessage(
6868                            mContext.getResources().getString(R.string.android_upgrading_apk,
6869                                    curr, total), true);
6870                } catch (RemoteException e) {
6871                }
6872            }
6873
6874            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6875                performDexOpt(pkg.packageName, null /* instructionSet */,
6876                         false /* useProfiles */, true /* extractOnly */, false /* force */);
6877            }
6878        }
6879    }
6880
6881    @Override
6882    public void notifyPackageUse(String packageName) {
6883        synchronized (mPackages) {
6884            PackageParser.Package p = mPackages.get(packageName);
6885            if (p == null) {
6886                return;
6887            }
6888            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6889        }
6890    }
6891
6892    // TODO: this is not used nor needed. Delete it.
6893    @Override
6894    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6895        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6896                false /* extractOnly */, false /* force */);
6897    }
6898
6899    @Override
6900    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6901            boolean extractOnly, boolean force) {
6902        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6903    }
6904
6905    private boolean performDexOptTraced(String packageName, String instructionSet,
6906                boolean useProfiles, boolean extractOnly, boolean force) {
6907        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6908        try {
6909            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6910                    force);
6911        } finally {
6912            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6913        }
6914    }
6915
6916    private boolean performDexOptInternal(String packageName, String instructionSet,
6917                boolean useProfiles, boolean extractOnly, boolean force) {
6918        PackageParser.Package p;
6919        final String targetInstructionSet;
6920        synchronized (mPackages) {
6921            p = mPackages.get(packageName);
6922            if (p == null) {
6923                return false;
6924            }
6925            mPackageUsage.write(false);
6926
6927            targetInstructionSet = instructionSet != null ? instructionSet :
6928                    getPrimaryInstructionSet(p.applicationInfo);
6929        }
6930        long callingId = Binder.clearCallingIdentity();
6931        try {
6932            synchronized (mInstallLock) {
6933                final String[] instructionSets = new String[] { targetInstructionSet };
6934                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6935                        useProfiles, extractOnly, force);
6936                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6937            }
6938        } finally {
6939            Binder.restoreCallingIdentity(callingId);
6940        }
6941    }
6942
6943    public ArraySet<String> getOptimizablePackages() {
6944        ArraySet<String> pkgs = new ArraySet<String>();
6945        synchronized (mPackages) {
6946            for (PackageParser.Package p : mPackages.values()) {
6947                if (PackageDexOptimizer.canOptimizePackage(p)) {
6948                    pkgs.add(p.packageName);
6949                }
6950            }
6951        }
6952        return pkgs;
6953    }
6954
6955    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6956            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6957        // Select the dex optimizer based on the force parameter.
6958        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6959        //       allocate an object here.
6960        PackageDexOptimizer pdo = force
6961                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6962                : mPackageDexOptimizer;
6963
6964        // Optimize all dependencies first. Note: we ignore the return value and march on
6965        // on errors.
6966        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6967        if (!deps.isEmpty()) {
6968            for (PackageParser.Package depPackage : deps) {
6969                // TODO: Analyze and investigate if we (should) profile libraries.
6970                // Currently this will do a full compilation of the library.
6971                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6972                        false /* extractOnly */);
6973            }
6974        }
6975
6976        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6977    }
6978
6979    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6980        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6981            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6982            Set<String> collectedNames = new HashSet<>();
6983            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6984
6985            retValue.remove(p);
6986
6987            return retValue;
6988        } else {
6989            return Collections.emptyList();
6990        }
6991    }
6992
6993    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6994            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6995        if (!collectedNames.contains(p.packageName)) {
6996            collectedNames.add(p.packageName);
6997            collected.add(p);
6998
6999            if (p.usesLibraries != null) {
7000                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7001            }
7002            if (p.usesOptionalLibraries != null) {
7003                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7004                        collectedNames);
7005            }
7006        }
7007    }
7008
7009    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7010            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7011        for (String libName : libs) {
7012            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7013            if (libPkg != null) {
7014                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7015            }
7016        }
7017    }
7018
7019    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7020        synchronized (mPackages) {
7021            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7022            if (lib != null && lib.apk != null) {
7023                return mPackages.get(lib.apk);
7024            }
7025        }
7026        return null;
7027    }
7028
7029    public void shutdown() {
7030        mPackageUsage.write(true);
7031    }
7032
7033    @Override
7034    public void forceDexOpt(String packageName) {
7035        enforceSystemOrRoot("forceDexOpt");
7036
7037        PackageParser.Package pkg;
7038        synchronized (mPackages) {
7039            pkg = mPackages.get(packageName);
7040            if (pkg == null) {
7041                throw new IllegalArgumentException("Unknown package: " + packageName);
7042            }
7043        }
7044
7045        synchronized (mInstallLock) {
7046            final String[] instructionSets = new String[] {
7047                    getPrimaryInstructionSet(pkg.applicationInfo) };
7048
7049            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7050
7051            // Whoever is calling forceDexOpt wants a fully compiled package.
7052            // Don't use profiles since that may cause compilation to be skipped.
7053            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7054                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7055
7056            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7057            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7058                throw new IllegalStateException("Failed to dexopt: " + res);
7059            }
7060        }
7061    }
7062
7063    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7064        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7065            Slog.w(TAG, "Unable to update from " + oldPkg.name
7066                    + " to " + newPkg.packageName
7067                    + ": old package not in system partition");
7068            return false;
7069        } else if (mPackages.get(oldPkg.name) != null) {
7070            Slog.w(TAG, "Unable to update from " + oldPkg.name
7071                    + " to " + newPkg.packageName
7072                    + ": old package still exists");
7073            return false;
7074        }
7075        return true;
7076    }
7077
7078    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7079        // TODO: triage flags as part of 26466827
7080        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7081
7082        boolean res = true;
7083        final int[] users = sUserManager.getUserIds();
7084        for (int user : users) {
7085            try {
7086                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7087            } catch (InstallerException e) {
7088                Slog.w(TAG, "Failed to delete data directory", e);
7089                res = false;
7090            }
7091        }
7092        return res;
7093    }
7094
7095    void removeCodePathLI(File codePath) {
7096        if (codePath.isDirectory()) {
7097            try {
7098                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7099            } catch (InstallerException e) {
7100                Slog.w(TAG, "Failed to remove code path", e);
7101            }
7102        } else {
7103            codePath.delete();
7104        }
7105    }
7106
7107    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7108        try {
7109            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7110        } catch (InstallerException e) {
7111            Slog.w(TAG, "Failed to destroy app data", e);
7112        }
7113    }
7114
7115    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7116            int appId, String seinfo) {
7117        try {
7118            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7119        } catch (InstallerException e) {
7120            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7121        }
7122    }
7123
7124    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7125        final PackageParser.Package pkg;
7126        synchronized (mPackages) {
7127            pkg = mPackages.get(packageName);
7128        }
7129        if (pkg == null) {
7130            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7131            return;
7132        }
7133        deleteCodeCacheDirsLI(pkg);
7134    }
7135
7136    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7137        // TODO: triage flags as part of 26466827
7138        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7139
7140        int[] users = sUserManager.getUserIds();
7141        int res = 0;
7142        for (int user : users) {
7143            // Remove the parent code cache
7144            try {
7145                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7146                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7147            } catch (InstallerException e) {
7148                Slog.w(TAG, "Failed to delete code cache directory", e);
7149            }
7150            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7151            for (int i = 0; i < childCount; i++) {
7152                PackageParser.Package childPkg = pkg.childPackages.get(i);
7153                // Remove the child code cache
7154                try {
7155                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7156                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7157                } catch (InstallerException e) {
7158                    Slog.w(TAG, "Failed to delete code cache directory", e);
7159                }
7160            }
7161        }
7162    }
7163
7164    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7165            long lastUpdateTime) {
7166        // Set parent install/update time
7167        PackageSetting ps = (PackageSetting) pkg.mExtras;
7168        if (ps != null) {
7169            ps.firstInstallTime = firstInstallTime;
7170            ps.lastUpdateTime = lastUpdateTime;
7171        }
7172        // Set children install/update time
7173        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7174        for (int i = 0; i < childCount; i++) {
7175            PackageParser.Package childPkg = pkg.childPackages.get(i);
7176            ps = (PackageSetting) childPkg.mExtras;
7177            if (ps != null) {
7178                ps.firstInstallTime = firstInstallTime;
7179                ps.lastUpdateTime = lastUpdateTime;
7180            }
7181        }
7182    }
7183
7184    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7185            PackageParser.Package changingLib) {
7186        if (file.path != null) {
7187            usesLibraryFiles.add(file.path);
7188            return;
7189        }
7190        PackageParser.Package p = mPackages.get(file.apk);
7191        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7192            // If we are doing this while in the middle of updating a library apk,
7193            // then we need to make sure to use that new apk for determining the
7194            // dependencies here.  (We haven't yet finished committing the new apk
7195            // to the package manager state.)
7196            if (p == null || p.packageName.equals(changingLib.packageName)) {
7197                p = changingLib;
7198            }
7199        }
7200        if (p != null) {
7201            usesLibraryFiles.addAll(p.getAllCodePaths());
7202        }
7203    }
7204
7205    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7206            PackageParser.Package changingLib) throws PackageManagerException {
7207        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7208            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7209            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7210            for (int i=0; i<N; i++) {
7211                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7212                if (file == null) {
7213                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7214                            "Package " + pkg.packageName + " requires unavailable shared library "
7215                            + pkg.usesLibraries.get(i) + "; failing!");
7216                }
7217                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7218            }
7219            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7220            for (int i=0; i<N; i++) {
7221                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7222                if (file == null) {
7223                    Slog.w(TAG, "Package " + pkg.packageName
7224                            + " desires unavailable shared library "
7225                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7226                } else {
7227                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7228                }
7229            }
7230            N = usesLibraryFiles.size();
7231            if (N > 0) {
7232                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7233            } else {
7234                pkg.usesLibraryFiles = null;
7235            }
7236        }
7237    }
7238
7239    private static boolean hasString(List<String> list, List<String> which) {
7240        if (list == null) {
7241            return false;
7242        }
7243        for (int i=list.size()-1; i>=0; i--) {
7244            for (int j=which.size()-1; j>=0; j--) {
7245                if (which.get(j).equals(list.get(i))) {
7246                    return true;
7247                }
7248            }
7249        }
7250        return false;
7251    }
7252
7253    private void updateAllSharedLibrariesLPw() {
7254        for (PackageParser.Package pkg : mPackages.values()) {
7255            try {
7256                updateSharedLibrariesLPw(pkg, null);
7257            } catch (PackageManagerException e) {
7258                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7259            }
7260        }
7261    }
7262
7263    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7264            PackageParser.Package changingPkg) {
7265        ArrayList<PackageParser.Package> res = null;
7266        for (PackageParser.Package pkg : mPackages.values()) {
7267            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7268                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7269                if (res == null) {
7270                    res = new ArrayList<PackageParser.Package>();
7271                }
7272                res.add(pkg);
7273                try {
7274                    updateSharedLibrariesLPw(pkg, changingPkg);
7275                } catch (PackageManagerException e) {
7276                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7277                }
7278            }
7279        }
7280        return res;
7281    }
7282
7283    /**
7284     * Derive the value of the {@code cpuAbiOverride} based on the provided
7285     * value and an optional stored value from the package settings.
7286     */
7287    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7288        String cpuAbiOverride = null;
7289
7290        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7291            cpuAbiOverride = null;
7292        } else if (abiOverride != null) {
7293            cpuAbiOverride = abiOverride;
7294        } else if (settings != null) {
7295            cpuAbiOverride = settings.cpuAbiOverrideString;
7296        }
7297
7298        return cpuAbiOverride;
7299    }
7300
7301    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7302            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7303        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7304        // If the package has children and this is the first dive in the function
7305        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7306        // whether all packages (parent and children) would be successfully scanned
7307        // before the actual scan since scanning mutates internal state and we want
7308        // to atomically install the package and its children.
7309        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7310            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7311                scanFlags |= SCAN_CHECK_ONLY;
7312            }
7313        } else {
7314            scanFlags &= ~SCAN_CHECK_ONLY;
7315        }
7316
7317        final PackageParser.Package scannedPkg;
7318        try {
7319            // Scan the parent
7320            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7321            // Scan the children
7322            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7323            for (int i = 0; i < childCount; i++) {
7324                PackageParser.Package childPkg = pkg.childPackages.get(i);
7325                scanPackageLI(childPkg, parseFlags,
7326                        scanFlags, currentTime, user);
7327            }
7328        } finally {
7329            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7330        }
7331
7332        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7333            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7334        }
7335
7336        return scannedPkg;
7337    }
7338
7339    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7340            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7341        boolean success = false;
7342        try {
7343            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7344                    currentTime, user);
7345            success = true;
7346            return res;
7347        } finally {
7348            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7349                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7350            }
7351        }
7352    }
7353
7354    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7355            int scanFlags, long currentTime, UserHandle user)
7356            throws PackageManagerException {
7357        final File scanFile = new File(pkg.codePath);
7358        if (pkg.applicationInfo.getCodePath() == null ||
7359                pkg.applicationInfo.getResourcePath() == null) {
7360            // Bail out. The resource and code paths haven't been set.
7361            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7362                    "Code and resource paths haven't been set correctly");
7363        }
7364
7365        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7366            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7367        } else {
7368            // Only allow system apps to be flagged as core apps.
7369            pkg.coreApp = false;
7370        }
7371
7372        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7373            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7374        }
7375
7376        if (mCustomResolverComponentName != null &&
7377                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7378            setUpCustomResolverActivity(pkg);
7379        }
7380
7381        if (pkg.packageName.equals("android")) {
7382            synchronized (mPackages) {
7383                if (mAndroidApplication != null) {
7384                    Slog.w(TAG, "*************************************************");
7385                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7386                    Slog.w(TAG, " file=" + scanFile);
7387                    Slog.w(TAG, "*************************************************");
7388                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7389                            "Core android package being redefined.  Skipping.");
7390                }
7391
7392                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7393                    // Set up information for our fall-back user intent resolution activity.
7394                    mPlatformPackage = pkg;
7395                    pkg.mVersionCode = mSdkVersion;
7396                    mAndroidApplication = pkg.applicationInfo;
7397
7398                    if (!mResolverReplaced) {
7399                        mResolveActivity.applicationInfo = mAndroidApplication;
7400                        mResolveActivity.name = ResolverActivity.class.getName();
7401                        mResolveActivity.packageName = mAndroidApplication.packageName;
7402                        mResolveActivity.processName = "system:ui";
7403                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7404                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7405                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7406                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7407                        mResolveActivity.exported = true;
7408                        mResolveActivity.enabled = true;
7409                        mResolveInfo.activityInfo = mResolveActivity;
7410                        mResolveInfo.priority = 0;
7411                        mResolveInfo.preferredOrder = 0;
7412                        mResolveInfo.match = 0;
7413                        mResolveComponentName = new ComponentName(
7414                                mAndroidApplication.packageName, mResolveActivity.name);
7415                    }
7416                }
7417            }
7418        }
7419
7420        if (DEBUG_PACKAGE_SCANNING) {
7421            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7422                Log.d(TAG, "Scanning package " + pkg.packageName);
7423        }
7424
7425        synchronized (mPackages) {
7426            if (mPackages.containsKey(pkg.packageName)
7427                    || mSharedLibraries.containsKey(pkg.packageName)) {
7428                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7429                        "Application package " + pkg.packageName
7430                                + " already installed.  Skipping duplicate.");
7431            }
7432
7433            // If we're only installing presumed-existing packages, require that the
7434            // scanned APK is both already known and at the path previously established
7435            // for it.  Previously unknown packages we pick up normally, but if we have an
7436            // a priori expectation about this package's install presence, enforce it.
7437            // With a singular exception for new system packages. When an OTA contains
7438            // a new system package, we allow the codepath to change from a system location
7439            // to the user-installed location. If we don't allow this change, any newer,
7440            // user-installed version of the application will be ignored.
7441            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7442                if (mExpectingBetter.containsKey(pkg.packageName)) {
7443                    logCriticalInfo(Log.WARN,
7444                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7445                } else {
7446                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7447                    if (known != null) {
7448                        if (DEBUG_PACKAGE_SCANNING) {
7449                            Log.d(TAG, "Examining " + pkg.codePath
7450                                    + " and requiring known paths " + known.codePathString
7451                                    + " & " + known.resourcePathString);
7452                        }
7453                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7454                                || !pkg.applicationInfo.getResourcePath().equals(
7455                                known.resourcePathString)) {
7456                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7457                                    "Application package " + pkg.packageName
7458                                            + " found at " + pkg.applicationInfo.getCodePath()
7459                                            + " but expected at " + known.codePathString
7460                                            + "; ignoring.");
7461                        }
7462                    }
7463                }
7464            }
7465        }
7466
7467        // Initialize package source and resource directories
7468        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7469        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7470
7471        SharedUserSetting suid = null;
7472        PackageSetting pkgSetting = null;
7473
7474        if (!isSystemApp(pkg)) {
7475            // Only system apps can use these features.
7476            pkg.mOriginalPackages = null;
7477            pkg.mRealPackage = null;
7478            pkg.mAdoptPermissions = null;
7479        }
7480
7481        // Getting the package setting may have a side-effect, so if we
7482        // are only checking if scan would succeed, stash a copy of the
7483        // old setting to restore at the end.
7484        PackageSetting nonMutatedPs = null;
7485
7486        // writer
7487        synchronized (mPackages) {
7488            if (pkg.mSharedUserId != null) {
7489                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7490                if (suid == null) {
7491                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7492                            "Creating application package " + pkg.packageName
7493                            + " for shared user failed");
7494                }
7495                if (DEBUG_PACKAGE_SCANNING) {
7496                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7497                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7498                                + "): packages=" + suid.packages);
7499                }
7500            }
7501
7502            // Check if we are renaming from an original package name.
7503            PackageSetting origPackage = null;
7504            String realName = null;
7505            if (pkg.mOriginalPackages != null) {
7506                // This package may need to be renamed to a previously
7507                // installed name.  Let's check on that...
7508                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7509                if (pkg.mOriginalPackages.contains(renamed)) {
7510                    // This package had originally been installed as the
7511                    // original name, and we have already taken care of
7512                    // transitioning to the new one.  Just update the new
7513                    // one to continue using the old name.
7514                    realName = pkg.mRealPackage;
7515                    if (!pkg.packageName.equals(renamed)) {
7516                        // Callers into this function may have already taken
7517                        // care of renaming the package; only do it here if
7518                        // it is not already done.
7519                        pkg.setPackageName(renamed);
7520                    }
7521
7522                } else {
7523                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7524                        if ((origPackage = mSettings.peekPackageLPr(
7525                                pkg.mOriginalPackages.get(i))) != null) {
7526                            // We do have the package already installed under its
7527                            // original name...  should we use it?
7528                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7529                                // New package is not compatible with original.
7530                                origPackage = null;
7531                                continue;
7532                            } else if (origPackage.sharedUser != null) {
7533                                // Make sure uid is compatible between packages.
7534                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7535                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7536                                            + " to " + pkg.packageName + ": old uid "
7537                                            + origPackage.sharedUser.name
7538                                            + " differs from " + pkg.mSharedUserId);
7539                                    origPackage = null;
7540                                    continue;
7541                                }
7542                            } else {
7543                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7544                                        + pkg.packageName + " to old name " + origPackage.name);
7545                            }
7546                            break;
7547                        }
7548                    }
7549                }
7550            }
7551
7552            if (mTransferedPackages.contains(pkg.packageName)) {
7553                Slog.w(TAG, "Package " + pkg.packageName
7554                        + " was transferred to another, but its .apk remains");
7555            }
7556
7557            // See comments in nonMutatedPs declaration
7558            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7559                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7560                if (foundPs != null) {
7561                    nonMutatedPs = new PackageSetting(foundPs);
7562                }
7563            }
7564
7565            // Just create the setting, don't add it yet. For already existing packages
7566            // the PkgSetting exists already and doesn't have to be created.
7567            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7568                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7569                    pkg.applicationInfo.primaryCpuAbi,
7570                    pkg.applicationInfo.secondaryCpuAbi,
7571                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7572                    user, false);
7573            if (pkgSetting == null) {
7574                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7575                        "Creating application package " + pkg.packageName + " failed");
7576            }
7577
7578            if (pkgSetting.origPackage != null) {
7579                // If we are first transitioning from an original package,
7580                // fix up the new package's name now.  We need to do this after
7581                // looking up the package under its new name, so getPackageLP
7582                // can take care of fiddling things correctly.
7583                pkg.setPackageName(origPackage.name);
7584
7585                // File a report about this.
7586                String msg = "New package " + pkgSetting.realName
7587                        + " renamed to replace old package " + pkgSetting.name;
7588                reportSettingsProblem(Log.WARN, msg);
7589
7590                // Make a note of it.
7591                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7592                    mTransferedPackages.add(origPackage.name);
7593                }
7594
7595                // No longer need to retain this.
7596                pkgSetting.origPackage = null;
7597            }
7598
7599            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7600                // Make a note of it.
7601                mTransferedPackages.add(pkg.packageName);
7602            }
7603
7604            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7605                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7606            }
7607
7608            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7609                // Check all shared libraries and map to their actual file path.
7610                // We only do this here for apps not on a system dir, because those
7611                // are the only ones that can fail an install due to this.  We
7612                // will take care of the system apps by updating all of their
7613                // library paths after the scan is done.
7614                updateSharedLibrariesLPw(pkg, null);
7615            }
7616
7617            if (mFoundPolicyFile) {
7618                SELinuxMMAC.assignSeinfoValue(pkg);
7619            }
7620
7621            pkg.applicationInfo.uid = pkgSetting.appId;
7622            pkg.mExtras = pkgSetting;
7623            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7624                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7625                    // We just determined the app is signed correctly, so bring
7626                    // over the latest parsed certs.
7627                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7628                } else {
7629                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7630                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7631                                "Package " + pkg.packageName + " upgrade keys do not match the "
7632                                + "previously installed version");
7633                    } else {
7634                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7635                        String msg = "System package " + pkg.packageName
7636                            + " signature changed; retaining data.";
7637                        reportSettingsProblem(Log.WARN, msg);
7638                    }
7639                }
7640            } else {
7641                try {
7642                    verifySignaturesLP(pkgSetting, pkg);
7643                    // We just determined the app is signed correctly, so bring
7644                    // over the latest parsed certs.
7645                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7646                } catch (PackageManagerException e) {
7647                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7648                        throw e;
7649                    }
7650                    // The signature has changed, but this package is in the system
7651                    // image...  let's recover!
7652                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7653                    // However...  if this package is part of a shared user, but it
7654                    // doesn't match the signature of the shared user, let's fail.
7655                    // What this means is that you can't change the signatures
7656                    // associated with an overall shared user, which doesn't seem all
7657                    // that unreasonable.
7658                    if (pkgSetting.sharedUser != null) {
7659                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7660                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7661                            throw new PackageManagerException(
7662                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7663                                            "Signature mismatch for shared user: "
7664                                            + pkgSetting.sharedUser);
7665                        }
7666                    }
7667                    // File a report about this.
7668                    String msg = "System package " + pkg.packageName
7669                        + " signature changed; retaining data.";
7670                    reportSettingsProblem(Log.WARN, msg);
7671                }
7672            }
7673            // Verify that this new package doesn't have any content providers
7674            // that conflict with existing packages.  Only do this if the
7675            // package isn't already installed, since we don't want to break
7676            // things that are installed.
7677            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7678                final int N = pkg.providers.size();
7679                int i;
7680                for (i=0; i<N; i++) {
7681                    PackageParser.Provider p = pkg.providers.get(i);
7682                    if (p.info.authority != null) {
7683                        String names[] = p.info.authority.split(";");
7684                        for (int j = 0; j < names.length; j++) {
7685                            if (mProvidersByAuthority.containsKey(names[j])) {
7686                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7687                                final String otherPackageName =
7688                                        ((other != null && other.getComponentName() != null) ?
7689                                                other.getComponentName().getPackageName() : "?");
7690                                throw new PackageManagerException(
7691                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7692                                                "Can't install because provider name " + names[j]
7693                                                + " (in package " + pkg.applicationInfo.packageName
7694                                                + ") is already used by " + otherPackageName);
7695                            }
7696                        }
7697                    }
7698                }
7699            }
7700
7701            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7702                // This package wants to adopt ownership of permissions from
7703                // another package.
7704                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7705                    final String origName = pkg.mAdoptPermissions.get(i);
7706                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7707                    if (orig != null) {
7708                        if (verifyPackageUpdateLPr(orig, pkg)) {
7709                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7710                                    + pkg.packageName);
7711                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7712                        }
7713                    }
7714                }
7715            }
7716        }
7717
7718        final String pkgName = pkg.packageName;
7719
7720        final long scanFileTime = scanFile.lastModified();
7721        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7722        pkg.applicationInfo.processName = fixProcessName(
7723                pkg.applicationInfo.packageName,
7724                pkg.applicationInfo.processName,
7725                pkg.applicationInfo.uid);
7726
7727        if (pkg != mPlatformPackage) {
7728            // Get all of our default paths setup
7729            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7730        }
7731
7732        final String path = scanFile.getPath();
7733        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7734
7735        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7736            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7737
7738            // Some system apps still use directory structure for native libraries
7739            // in which case we might end up not detecting abi solely based on apk
7740            // structure. Try to detect abi based on directory structure.
7741            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7742                    pkg.applicationInfo.primaryCpuAbi == null) {
7743                setBundledAppAbisAndRoots(pkg, pkgSetting);
7744                setNativeLibraryPaths(pkg);
7745            }
7746
7747        } else {
7748            if ((scanFlags & SCAN_MOVE) != 0) {
7749                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7750                // but we already have this packages package info in the PackageSetting. We just
7751                // use that and derive the native library path based on the new codepath.
7752                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7753                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7754            }
7755
7756            // Set native library paths again. For moves, the path will be updated based on the
7757            // ABIs we've determined above. For non-moves, the path will be updated based on the
7758            // ABIs we determined during compilation, but the path will depend on the final
7759            // package path (after the rename away from the stage path).
7760            setNativeLibraryPaths(pkg);
7761        }
7762
7763        // This is a special case for the "system" package, where the ABI is
7764        // dictated by the zygote configuration (and init.rc). We should keep track
7765        // of this ABI so that we can deal with "normal" applications that run under
7766        // the same UID correctly.
7767        if (mPlatformPackage == pkg) {
7768            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7769                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7770        }
7771
7772        // If there's a mismatch between the abi-override in the package setting
7773        // and the abiOverride specified for the install. Warn about this because we
7774        // would've already compiled the app without taking the package setting into
7775        // account.
7776        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7777            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7778                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7779                        " for package " + pkg.packageName);
7780            }
7781        }
7782
7783        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7784        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7785        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7786
7787        // Copy the derived override back to the parsed package, so that we can
7788        // update the package settings accordingly.
7789        pkg.cpuAbiOverride = cpuAbiOverride;
7790
7791        if (DEBUG_ABI_SELECTION) {
7792            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7793                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7794                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7795        }
7796
7797        // Push the derived path down into PackageSettings so we know what to
7798        // clean up at uninstall time.
7799        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7800
7801        if (DEBUG_ABI_SELECTION) {
7802            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7803                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7804                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7805        }
7806
7807        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7808            // We don't do this here during boot because we can do it all
7809            // at once after scanning all existing packages.
7810            //
7811            // We also do this *before* we perform dexopt on this package, so that
7812            // we can avoid redundant dexopts, and also to make sure we've got the
7813            // code and package path correct.
7814            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7815                    pkg, true /* boot complete */);
7816        }
7817
7818        if (mFactoryTest && pkg.requestedPermissions.contains(
7819                android.Manifest.permission.FACTORY_TEST)) {
7820            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7821        }
7822
7823        ArrayList<PackageParser.Package> clientLibPkgs = null;
7824
7825        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7826            if (nonMutatedPs != null) {
7827                synchronized (mPackages) {
7828                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7829                }
7830            }
7831            return pkg;
7832        }
7833
7834        // Only privileged apps and updated privileged apps can add child packages.
7835        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7836            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7837                throw new PackageManagerException("Only privileged apps and updated "
7838                        + "privileged apps can add child packages. Ignoring package "
7839                        + pkg.packageName);
7840            }
7841            final int childCount = pkg.childPackages.size();
7842            for (int i = 0; i < childCount; i++) {
7843                PackageParser.Package childPkg = pkg.childPackages.get(i);
7844                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7845                        childPkg.packageName)) {
7846                    throw new PackageManagerException("Cannot override a child package of "
7847                            + "another disabled system app. Ignoring package " + pkg.packageName);
7848                }
7849            }
7850        }
7851
7852        // writer
7853        synchronized (mPackages) {
7854            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7855                // Only system apps can add new shared libraries.
7856                if (pkg.libraryNames != null) {
7857                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7858                        String name = pkg.libraryNames.get(i);
7859                        boolean allowed = false;
7860                        if (pkg.isUpdatedSystemApp()) {
7861                            // New library entries can only be added through the
7862                            // system image.  This is important to get rid of a lot
7863                            // of nasty edge cases: for example if we allowed a non-
7864                            // system update of the app to add a library, then uninstalling
7865                            // the update would make the library go away, and assumptions
7866                            // we made such as through app install filtering would now
7867                            // have allowed apps on the device which aren't compatible
7868                            // with it.  Better to just have the restriction here, be
7869                            // conservative, and create many fewer cases that can negatively
7870                            // impact the user experience.
7871                            final PackageSetting sysPs = mSettings
7872                                    .getDisabledSystemPkgLPr(pkg.packageName);
7873                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7874                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7875                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7876                                        allowed = true;
7877                                        break;
7878                                    }
7879                                }
7880                            }
7881                        } else {
7882                            allowed = true;
7883                        }
7884                        if (allowed) {
7885                            if (!mSharedLibraries.containsKey(name)) {
7886                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7887                            } else if (!name.equals(pkg.packageName)) {
7888                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7889                                        + name + " already exists; skipping");
7890                            }
7891                        } else {
7892                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7893                                    + name + " that is not declared on system image; skipping");
7894                        }
7895                    }
7896                    if ((scanFlags & SCAN_BOOTING) == 0) {
7897                        // If we are not booting, we need to update any applications
7898                        // that are clients of our shared library.  If we are booting,
7899                        // this will all be done once the scan is complete.
7900                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7901                    }
7902                }
7903            }
7904        }
7905
7906        // Request the ActivityManager to kill the process(only for existing packages)
7907        // so that we do not end up in a confused state while the user is still using the older
7908        // version of the application while the new one gets installed.
7909        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
7910        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
7911        if (killApp) {
7912            if (isReplacing) {
7913                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7914
7915                killApplication(pkg.applicationInfo.packageName,
7916                            pkg.applicationInfo.uid, "replace pkg");
7917
7918                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7919            }
7920        }
7921
7922        // Also need to kill any apps that are dependent on the library.
7923        if (clientLibPkgs != null) {
7924            for (int i=0; i<clientLibPkgs.size(); i++) {
7925                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7926                killApplication(clientPkg.applicationInfo.packageName,
7927                        clientPkg.applicationInfo.uid, "update lib");
7928            }
7929        }
7930
7931        // Make sure we're not adding any bogus keyset info
7932        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7933        ksms.assertScannedPackageValid(pkg);
7934
7935        // writer
7936        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7937
7938        boolean createIdmapFailed = false;
7939        synchronized (mPackages) {
7940            // We don't expect installation to fail beyond this point
7941
7942            // Add the new setting to mSettings
7943            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7944            // Add the new setting to mPackages
7945            mPackages.put(pkg.applicationInfo.packageName, pkg);
7946            // Make sure we don't accidentally delete its data.
7947            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7948            while (iter.hasNext()) {
7949                PackageCleanItem item = iter.next();
7950                if (pkgName.equals(item.packageName)) {
7951                    iter.remove();
7952                }
7953            }
7954
7955            // Take care of first install / last update times.
7956            if (currentTime != 0) {
7957                if (pkgSetting.firstInstallTime == 0) {
7958                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7959                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7960                    pkgSetting.lastUpdateTime = currentTime;
7961                }
7962            } else if (pkgSetting.firstInstallTime == 0) {
7963                // We need *something*.  Take time time stamp of the file.
7964                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7965            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7966                if (scanFileTime != pkgSetting.timeStamp) {
7967                    // A package on the system image has changed; consider this
7968                    // to be an update.
7969                    pkgSetting.lastUpdateTime = scanFileTime;
7970                }
7971            }
7972
7973            // Add the package's KeySets to the global KeySetManagerService
7974            ksms.addScannedPackageLPw(pkg);
7975
7976            int N = pkg.providers.size();
7977            StringBuilder r = null;
7978            int i;
7979            for (i=0; i<N; i++) {
7980                PackageParser.Provider p = pkg.providers.get(i);
7981                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7982                        p.info.processName, pkg.applicationInfo.uid);
7983                mProviders.addProvider(p);
7984                p.syncable = p.info.isSyncable;
7985                if (p.info.authority != null) {
7986                    String names[] = p.info.authority.split(";");
7987                    p.info.authority = null;
7988                    for (int j = 0; j < names.length; j++) {
7989                        if (j == 1 && p.syncable) {
7990                            // We only want the first authority for a provider to possibly be
7991                            // syncable, so if we already added this provider using a different
7992                            // authority clear the syncable flag. We copy the provider before
7993                            // changing it because the mProviders object contains a reference
7994                            // to a provider that we don't want to change.
7995                            // Only do this for the second authority since the resulting provider
7996                            // object can be the same for all future authorities for this provider.
7997                            p = new PackageParser.Provider(p);
7998                            p.syncable = false;
7999                        }
8000                        if (!mProvidersByAuthority.containsKey(names[j])) {
8001                            mProvidersByAuthority.put(names[j], p);
8002                            if (p.info.authority == null) {
8003                                p.info.authority = names[j];
8004                            } else {
8005                                p.info.authority = p.info.authority + ";" + names[j];
8006                            }
8007                            if (DEBUG_PACKAGE_SCANNING) {
8008                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8009                                    Log.d(TAG, "Registered content provider: " + names[j]
8010                                            + ", className = " + p.info.name + ", isSyncable = "
8011                                            + p.info.isSyncable);
8012                            }
8013                        } else {
8014                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8015                            Slog.w(TAG, "Skipping provider name " + names[j] +
8016                                    " (in package " + pkg.applicationInfo.packageName +
8017                                    "): name already used by "
8018                                    + ((other != null && other.getComponentName() != null)
8019                                            ? other.getComponentName().getPackageName() : "?"));
8020                        }
8021                    }
8022                }
8023                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8024                    if (r == null) {
8025                        r = new StringBuilder(256);
8026                    } else {
8027                        r.append(' ');
8028                    }
8029                    r.append(p.info.name);
8030                }
8031            }
8032            if (r != null) {
8033                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8034            }
8035
8036            N = pkg.services.size();
8037            r = null;
8038            for (i=0; i<N; i++) {
8039                PackageParser.Service s = pkg.services.get(i);
8040                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8041                        s.info.processName, pkg.applicationInfo.uid);
8042                mServices.addService(s);
8043                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8044                    if (r == null) {
8045                        r = new StringBuilder(256);
8046                    } else {
8047                        r.append(' ');
8048                    }
8049                    r.append(s.info.name);
8050                }
8051            }
8052            if (r != null) {
8053                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8054            }
8055
8056            N = pkg.receivers.size();
8057            r = null;
8058            for (i=0; i<N; i++) {
8059                PackageParser.Activity a = pkg.receivers.get(i);
8060                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8061                        a.info.processName, pkg.applicationInfo.uid);
8062                mReceivers.addActivity(a, "receiver");
8063                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8064                    if (r == null) {
8065                        r = new StringBuilder(256);
8066                    } else {
8067                        r.append(' ');
8068                    }
8069                    r.append(a.info.name);
8070                }
8071            }
8072            if (r != null) {
8073                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8074            }
8075
8076            N = pkg.activities.size();
8077            r = null;
8078            for (i=0; i<N; i++) {
8079                PackageParser.Activity a = pkg.activities.get(i);
8080                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8081                        a.info.processName, pkg.applicationInfo.uid);
8082                mActivities.addActivity(a, "activity");
8083                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8084                    if (r == null) {
8085                        r = new StringBuilder(256);
8086                    } else {
8087                        r.append(' ');
8088                    }
8089                    r.append(a.info.name);
8090                }
8091            }
8092            if (r != null) {
8093                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8094            }
8095
8096            N = pkg.permissionGroups.size();
8097            r = null;
8098            for (i=0; i<N; i++) {
8099                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8100                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8101                if (cur == null) {
8102                    mPermissionGroups.put(pg.info.name, pg);
8103                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8104                        if (r == null) {
8105                            r = new StringBuilder(256);
8106                        } else {
8107                            r.append(' ');
8108                        }
8109                        r.append(pg.info.name);
8110                    }
8111                } else {
8112                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8113                            + pg.info.packageName + " ignored: original from "
8114                            + cur.info.packageName);
8115                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8116                        if (r == null) {
8117                            r = new StringBuilder(256);
8118                        } else {
8119                            r.append(' ');
8120                        }
8121                        r.append("DUP:");
8122                        r.append(pg.info.name);
8123                    }
8124                }
8125            }
8126            if (r != null) {
8127                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8128            }
8129
8130            N = pkg.permissions.size();
8131            r = null;
8132            for (i=0; i<N; i++) {
8133                PackageParser.Permission p = pkg.permissions.get(i);
8134
8135                // Assume by default that we did not install this permission into the system.
8136                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8137
8138                // Now that permission groups have a special meaning, we ignore permission
8139                // groups for legacy apps to prevent unexpected behavior. In particular,
8140                // permissions for one app being granted to someone just becase they happen
8141                // to be in a group defined by another app (before this had no implications).
8142                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8143                    p.group = mPermissionGroups.get(p.info.group);
8144                    // Warn for a permission in an unknown group.
8145                    if (p.info.group != null && p.group == null) {
8146                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8147                                + p.info.packageName + " in an unknown group " + p.info.group);
8148                    }
8149                }
8150
8151                ArrayMap<String, BasePermission> permissionMap =
8152                        p.tree ? mSettings.mPermissionTrees
8153                                : mSettings.mPermissions;
8154                BasePermission bp = permissionMap.get(p.info.name);
8155
8156                // Allow system apps to redefine non-system permissions
8157                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8158                    final boolean currentOwnerIsSystem = (bp.perm != null
8159                            && isSystemApp(bp.perm.owner));
8160                    if (isSystemApp(p.owner)) {
8161                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8162                            // It's a built-in permission and no owner, take ownership now
8163                            bp.packageSetting = pkgSetting;
8164                            bp.perm = p;
8165                            bp.uid = pkg.applicationInfo.uid;
8166                            bp.sourcePackage = p.info.packageName;
8167                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8168                        } else if (!currentOwnerIsSystem) {
8169                            String msg = "New decl " + p.owner + " of permission  "
8170                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8171                            reportSettingsProblem(Log.WARN, msg);
8172                            bp = null;
8173                        }
8174                    }
8175                }
8176
8177                if (bp == null) {
8178                    bp = new BasePermission(p.info.name, p.info.packageName,
8179                            BasePermission.TYPE_NORMAL);
8180                    permissionMap.put(p.info.name, bp);
8181                }
8182
8183                if (bp.perm == null) {
8184                    if (bp.sourcePackage == null
8185                            || bp.sourcePackage.equals(p.info.packageName)) {
8186                        BasePermission tree = findPermissionTreeLP(p.info.name);
8187                        if (tree == null
8188                                || tree.sourcePackage.equals(p.info.packageName)) {
8189                            bp.packageSetting = pkgSetting;
8190                            bp.perm = p;
8191                            bp.uid = pkg.applicationInfo.uid;
8192                            bp.sourcePackage = p.info.packageName;
8193                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8194                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8195                                if (r == null) {
8196                                    r = new StringBuilder(256);
8197                                } else {
8198                                    r.append(' ');
8199                                }
8200                                r.append(p.info.name);
8201                            }
8202                        } else {
8203                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8204                                    + p.info.packageName + " ignored: base tree "
8205                                    + tree.name + " is from package "
8206                                    + tree.sourcePackage);
8207                        }
8208                    } else {
8209                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8210                                + p.info.packageName + " ignored: original from "
8211                                + bp.sourcePackage);
8212                    }
8213                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8214                    if (r == null) {
8215                        r = new StringBuilder(256);
8216                    } else {
8217                        r.append(' ');
8218                    }
8219                    r.append("DUP:");
8220                    r.append(p.info.name);
8221                }
8222                if (bp.perm == p) {
8223                    bp.protectionLevel = p.info.protectionLevel;
8224                }
8225            }
8226
8227            if (r != null) {
8228                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8229            }
8230
8231            N = pkg.instrumentation.size();
8232            r = null;
8233            for (i=0; i<N; i++) {
8234                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8235                a.info.packageName = pkg.applicationInfo.packageName;
8236                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8237                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8238                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8239                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8240                a.info.dataDir = pkg.applicationInfo.dataDir;
8241                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8242                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8243
8244                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8245                // need other information about the application, like the ABI and what not ?
8246                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8247                mInstrumentation.put(a.getComponentName(), a);
8248                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8249                    if (r == null) {
8250                        r = new StringBuilder(256);
8251                    } else {
8252                        r.append(' ');
8253                    }
8254                    r.append(a.info.name);
8255                }
8256            }
8257            if (r != null) {
8258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8259            }
8260
8261            if (pkg.protectedBroadcasts != null) {
8262                N = pkg.protectedBroadcasts.size();
8263                for (i=0; i<N; i++) {
8264                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8265                }
8266            }
8267
8268            pkgSetting.setTimeStamp(scanFileTime);
8269
8270            // Create idmap files for pairs of (packages, overlay packages).
8271            // Note: "android", ie framework-res.apk, is handled by native layers.
8272            if (pkg.mOverlayTarget != null) {
8273                // This is an overlay package.
8274                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8275                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8276                        mOverlays.put(pkg.mOverlayTarget,
8277                                new ArrayMap<String, PackageParser.Package>());
8278                    }
8279                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8280                    map.put(pkg.packageName, pkg);
8281                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8282                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8283                        createIdmapFailed = true;
8284                    }
8285                }
8286            } else if (mOverlays.containsKey(pkg.packageName) &&
8287                    !pkg.packageName.equals("android")) {
8288                // This is a regular package, with one or more known overlay packages.
8289                createIdmapsForPackageLI(pkg);
8290            }
8291        }
8292
8293        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8294
8295        if (createIdmapFailed) {
8296            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8297                    "scanPackageLI failed to createIdmap");
8298        }
8299        return pkg;
8300    }
8301
8302    /**
8303     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8304     * is derived purely on the basis of the contents of {@code scanFile} and
8305     * {@code cpuAbiOverride}.
8306     *
8307     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8308     */
8309    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8310                                 String cpuAbiOverride, boolean extractLibs)
8311            throws PackageManagerException {
8312        // TODO: We can probably be smarter about this stuff. For installed apps,
8313        // we can calculate this information at install time once and for all. For
8314        // system apps, we can probably assume that this information doesn't change
8315        // after the first boot scan. As things stand, we do lots of unnecessary work.
8316
8317        // Give ourselves some initial paths; we'll come back for another
8318        // pass once we've determined ABI below.
8319        setNativeLibraryPaths(pkg);
8320
8321        // We would never need to extract libs for forward-locked and external packages,
8322        // since the container service will do it for us. We shouldn't attempt to
8323        // extract libs from system app when it was not updated.
8324        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8325                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8326            extractLibs = false;
8327        }
8328
8329        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8330        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8331
8332        NativeLibraryHelper.Handle handle = null;
8333        try {
8334            handle = NativeLibraryHelper.Handle.create(pkg);
8335            // TODO(multiArch): This can be null for apps that didn't go through the
8336            // usual installation process. We can calculate it again, like we
8337            // do during install time.
8338            //
8339            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8340            // unnecessary.
8341            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8342
8343            // Null out the abis so that they can be recalculated.
8344            pkg.applicationInfo.primaryCpuAbi = null;
8345            pkg.applicationInfo.secondaryCpuAbi = null;
8346            if (isMultiArch(pkg.applicationInfo)) {
8347                // Warn if we've set an abiOverride for multi-lib packages..
8348                // By definition, we need to copy both 32 and 64 bit libraries for
8349                // such packages.
8350                if (pkg.cpuAbiOverride != null
8351                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8352                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8353                }
8354
8355                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8356                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8357                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8358                    if (extractLibs) {
8359                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8360                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8361                                useIsaSpecificSubdirs);
8362                    } else {
8363                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8364                    }
8365                }
8366
8367                maybeThrowExceptionForMultiArchCopy(
8368                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8369
8370                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8371                    if (extractLibs) {
8372                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8373                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8374                                useIsaSpecificSubdirs);
8375                    } else {
8376                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8377                    }
8378                }
8379
8380                maybeThrowExceptionForMultiArchCopy(
8381                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8382
8383                if (abi64 >= 0) {
8384                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8385                }
8386
8387                if (abi32 >= 0) {
8388                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8389                    if (abi64 >= 0) {
8390                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8391                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8392                            pkg.applicationInfo.primaryCpuAbi = abi;
8393                        } else {
8394                            pkg.applicationInfo.secondaryCpuAbi = abi;
8395                        }
8396                    } else {
8397                        pkg.applicationInfo.primaryCpuAbi = abi;
8398                    }
8399                }
8400
8401            } else {
8402                String[] abiList = (cpuAbiOverride != null) ?
8403                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8404
8405                // Enable gross and lame hacks for apps that are built with old
8406                // SDK tools. We must scan their APKs for renderscript bitcode and
8407                // not launch them if it's present. Don't bother checking on devices
8408                // that don't have 64 bit support.
8409                boolean needsRenderScriptOverride = false;
8410                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8411                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8412                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8413                    needsRenderScriptOverride = true;
8414                }
8415
8416                final int copyRet;
8417                if (extractLibs) {
8418                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8419                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8420                } else {
8421                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8422                }
8423
8424                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8425                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8426                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8427                }
8428
8429                if (copyRet >= 0) {
8430                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8431                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8432                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8433                } else if (needsRenderScriptOverride) {
8434                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8435                }
8436            }
8437        } catch (IOException ioe) {
8438            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8439        } finally {
8440            IoUtils.closeQuietly(handle);
8441        }
8442
8443        // Now that we've calculated the ABIs and determined if it's an internal app,
8444        // we will go ahead and populate the nativeLibraryPath.
8445        setNativeLibraryPaths(pkg);
8446    }
8447
8448    /**
8449     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8450     * i.e, so that all packages can be run inside a single process if required.
8451     *
8452     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8453     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8454     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8455     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8456     * updating a package that belongs to a shared user.
8457     *
8458     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8459     * adds unnecessary complexity.
8460     */
8461    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8462            PackageParser.Package scannedPackage, boolean bootComplete) {
8463        String requiredInstructionSet = null;
8464        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8465            requiredInstructionSet = VMRuntime.getInstructionSet(
8466                     scannedPackage.applicationInfo.primaryCpuAbi);
8467        }
8468
8469        PackageSetting requirer = null;
8470        for (PackageSetting ps : packagesForUser) {
8471            // If packagesForUser contains scannedPackage, we skip it. This will happen
8472            // when scannedPackage is an update of an existing package. Without this check,
8473            // we will never be able to change the ABI of any package belonging to a shared
8474            // user, even if it's compatible with other packages.
8475            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8476                if (ps.primaryCpuAbiString == null) {
8477                    continue;
8478                }
8479
8480                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8481                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8482                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8483                    // this but there's not much we can do.
8484                    String errorMessage = "Instruction set mismatch, "
8485                            + ((requirer == null) ? "[caller]" : requirer)
8486                            + " requires " + requiredInstructionSet + " whereas " + ps
8487                            + " requires " + instructionSet;
8488                    Slog.w(TAG, errorMessage);
8489                }
8490
8491                if (requiredInstructionSet == null) {
8492                    requiredInstructionSet = instructionSet;
8493                    requirer = ps;
8494                }
8495            }
8496        }
8497
8498        if (requiredInstructionSet != null) {
8499            String adjustedAbi;
8500            if (requirer != null) {
8501                // requirer != null implies that either scannedPackage was null or that scannedPackage
8502                // did not require an ABI, in which case we have to adjust scannedPackage to match
8503                // the ABI of the set (which is the same as requirer's ABI)
8504                adjustedAbi = requirer.primaryCpuAbiString;
8505                if (scannedPackage != null) {
8506                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8507                }
8508            } else {
8509                // requirer == null implies that we're updating all ABIs in the set to
8510                // match scannedPackage.
8511                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8512            }
8513
8514            for (PackageSetting ps : packagesForUser) {
8515                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8516                    if (ps.primaryCpuAbiString != null) {
8517                        continue;
8518                    }
8519
8520                    ps.primaryCpuAbiString = adjustedAbi;
8521                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8522                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8523                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8524                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8525                                + " (requirer="
8526                                + (requirer == null ? "null" : requirer.pkg.packageName)
8527                                + ", scannedPackage="
8528                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8529                                + ")");
8530                        try {
8531                            mInstaller.rmdex(ps.codePathString,
8532                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8533                        } catch (InstallerException ignored) {
8534                        }
8535                    }
8536                }
8537            }
8538        }
8539    }
8540
8541    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8542        synchronized (mPackages) {
8543            mResolverReplaced = true;
8544            // Set up information for custom user intent resolution activity.
8545            mResolveActivity.applicationInfo = pkg.applicationInfo;
8546            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8547            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8548            mResolveActivity.processName = pkg.applicationInfo.packageName;
8549            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8550            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8551                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8552            mResolveActivity.theme = 0;
8553            mResolveActivity.exported = true;
8554            mResolveActivity.enabled = true;
8555            mResolveInfo.activityInfo = mResolveActivity;
8556            mResolveInfo.priority = 0;
8557            mResolveInfo.preferredOrder = 0;
8558            mResolveInfo.match = 0;
8559            mResolveComponentName = mCustomResolverComponentName;
8560            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8561                    mResolveComponentName);
8562        }
8563    }
8564
8565    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8566        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8567
8568        // Set up information for ephemeral installer activity
8569        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8570        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8571        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8572        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8573        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8574        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8575                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8576        mEphemeralInstallerActivity.theme = 0;
8577        mEphemeralInstallerActivity.exported = true;
8578        mEphemeralInstallerActivity.enabled = true;
8579        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8580        mEphemeralInstallerInfo.priority = 0;
8581        mEphemeralInstallerInfo.preferredOrder = 0;
8582        mEphemeralInstallerInfo.match = 0;
8583
8584        if (DEBUG_EPHEMERAL) {
8585            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8586        }
8587    }
8588
8589    private static String calculateBundledApkRoot(final String codePathString) {
8590        final File codePath = new File(codePathString);
8591        final File codeRoot;
8592        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8593            codeRoot = Environment.getRootDirectory();
8594        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8595            codeRoot = Environment.getOemDirectory();
8596        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8597            codeRoot = Environment.getVendorDirectory();
8598        } else {
8599            // Unrecognized code path; take its top real segment as the apk root:
8600            // e.g. /something/app/blah.apk => /something
8601            try {
8602                File f = codePath.getCanonicalFile();
8603                File parent = f.getParentFile();    // non-null because codePath is a file
8604                File tmp;
8605                while ((tmp = parent.getParentFile()) != null) {
8606                    f = parent;
8607                    parent = tmp;
8608                }
8609                codeRoot = f;
8610                Slog.w(TAG, "Unrecognized code path "
8611                        + codePath + " - using " + codeRoot);
8612            } catch (IOException e) {
8613                // Can't canonicalize the code path -- shenanigans?
8614                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8615                return Environment.getRootDirectory().getPath();
8616            }
8617        }
8618        return codeRoot.getPath();
8619    }
8620
8621    /**
8622     * Derive and set the location of native libraries for the given package,
8623     * which varies depending on where and how the package was installed.
8624     */
8625    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8626        final ApplicationInfo info = pkg.applicationInfo;
8627        final String codePath = pkg.codePath;
8628        final File codeFile = new File(codePath);
8629        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8630        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8631
8632        info.nativeLibraryRootDir = null;
8633        info.nativeLibraryRootRequiresIsa = false;
8634        info.nativeLibraryDir = null;
8635        info.secondaryNativeLibraryDir = null;
8636
8637        if (isApkFile(codeFile)) {
8638            // Monolithic install
8639            if (bundledApp) {
8640                // If "/system/lib64/apkname" exists, assume that is the per-package
8641                // native library directory to use; otherwise use "/system/lib/apkname".
8642                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8643                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8644                        getPrimaryInstructionSet(info));
8645
8646                // This is a bundled system app so choose the path based on the ABI.
8647                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8648                // is just the default path.
8649                final String apkName = deriveCodePathName(codePath);
8650                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8651                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8652                        apkName).getAbsolutePath();
8653
8654                if (info.secondaryCpuAbi != null) {
8655                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8656                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8657                            secondaryLibDir, apkName).getAbsolutePath();
8658                }
8659            } else if (asecApp) {
8660                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8661                        .getAbsolutePath();
8662            } else {
8663                final String apkName = deriveCodePathName(codePath);
8664                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8665                        .getAbsolutePath();
8666            }
8667
8668            info.nativeLibraryRootRequiresIsa = false;
8669            info.nativeLibraryDir = info.nativeLibraryRootDir;
8670        } else {
8671            // Cluster install
8672            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8673            info.nativeLibraryRootRequiresIsa = true;
8674
8675            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8676                    getPrimaryInstructionSet(info)).getAbsolutePath();
8677
8678            if (info.secondaryCpuAbi != null) {
8679                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8680                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8681            }
8682        }
8683    }
8684
8685    /**
8686     * Calculate the abis and roots for a bundled app. These can uniquely
8687     * be determined from the contents of the system partition, i.e whether
8688     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8689     * of this information, and instead assume that the system was built
8690     * sensibly.
8691     */
8692    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8693                                           PackageSetting pkgSetting) {
8694        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8695
8696        // If "/system/lib64/apkname" exists, assume that is the per-package
8697        // native library directory to use; otherwise use "/system/lib/apkname".
8698        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8699        setBundledAppAbi(pkg, apkRoot, apkName);
8700        // pkgSetting might be null during rescan following uninstall of updates
8701        // to a bundled app, so accommodate that possibility.  The settings in
8702        // that case will be established later from the parsed package.
8703        //
8704        // If the settings aren't null, sync them up with what we've just derived.
8705        // note that apkRoot isn't stored in the package settings.
8706        if (pkgSetting != null) {
8707            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8708            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8709        }
8710    }
8711
8712    /**
8713     * Deduces the ABI of a bundled app and sets the relevant fields on the
8714     * parsed pkg object.
8715     *
8716     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8717     *        under which system libraries are installed.
8718     * @param apkName the name of the installed package.
8719     */
8720    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8721        final File codeFile = new File(pkg.codePath);
8722
8723        final boolean has64BitLibs;
8724        final boolean has32BitLibs;
8725        if (isApkFile(codeFile)) {
8726            // Monolithic install
8727            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8728            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8729        } else {
8730            // Cluster install
8731            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8732            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8733                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8734                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8735                has64BitLibs = (new File(rootDir, isa)).exists();
8736            } else {
8737                has64BitLibs = false;
8738            }
8739            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8740                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8741                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8742                has32BitLibs = (new File(rootDir, isa)).exists();
8743            } else {
8744                has32BitLibs = false;
8745            }
8746        }
8747
8748        if (has64BitLibs && !has32BitLibs) {
8749            // The package has 64 bit libs, but not 32 bit libs. Its primary
8750            // ABI should be 64 bit. We can safely assume here that the bundled
8751            // native libraries correspond to the most preferred ABI in the list.
8752
8753            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8754            pkg.applicationInfo.secondaryCpuAbi = null;
8755        } else if (has32BitLibs && !has64BitLibs) {
8756            // The package has 32 bit libs but not 64 bit libs. Its primary
8757            // ABI should be 32 bit.
8758
8759            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8760            pkg.applicationInfo.secondaryCpuAbi = null;
8761        } else if (has32BitLibs && has64BitLibs) {
8762            // The application has both 64 and 32 bit bundled libraries. We check
8763            // here that the app declares multiArch support, and warn if it doesn't.
8764            //
8765            // We will be lenient here and record both ABIs. The primary will be the
8766            // ABI that's higher on the list, i.e, a device that's configured to prefer
8767            // 64 bit apps will see a 64 bit primary ABI,
8768
8769            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8770                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8771            }
8772
8773            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8774                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8775                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8776            } else {
8777                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8778                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8779            }
8780        } else {
8781            pkg.applicationInfo.primaryCpuAbi = null;
8782            pkg.applicationInfo.secondaryCpuAbi = null;
8783        }
8784    }
8785
8786    private void killPackage(PackageParser.Package pkg, String reason) {
8787        // Kill the parent package
8788        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8789        // Kill the child packages
8790        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8791        for (int i = 0; i < childCount; i++) {
8792            PackageParser.Package childPkg = pkg.childPackages.get(i);
8793            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8794        }
8795    }
8796
8797    private void killApplication(String pkgName, int appId, String reason) {
8798        // Request the ActivityManager to kill the process(only for existing packages)
8799        // so that we do not end up in a confused state while the user is still using the older
8800        // version of the application while the new one gets installed.
8801        IActivityManager am = ActivityManagerNative.getDefault();
8802        if (am != null) {
8803            try {
8804                am.killApplicationWithAppId(pkgName, appId, reason);
8805            } catch (RemoteException e) {
8806            }
8807        }
8808    }
8809
8810    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8811        // Remove the parent package setting
8812        PackageSetting ps = (PackageSetting) pkg.mExtras;
8813        if (ps != null) {
8814            removePackageLI(ps, chatty);
8815        }
8816        // Remove the child package setting
8817        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8818        for (int i = 0; i < childCount; i++) {
8819            PackageParser.Package childPkg = pkg.childPackages.get(i);
8820            ps = (PackageSetting) childPkg.mExtras;
8821            if (ps != null) {
8822                removePackageLI(ps, chatty);
8823            }
8824        }
8825    }
8826
8827    void removePackageLI(PackageSetting ps, boolean chatty) {
8828        if (DEBUG_INSTALL) {
8829            if (chatty)
8830                Log.d(TAG, "Removing package " + ps.name);
8831        }
8832
8833        // writer
8834        synchronized (mPackages) {
8835            mPackages.remove(ps.name);
8836            final PackageParser.Package pkg = ps.pkg;
8837            if (pkg != null) {
8838                cleanPackageDataStructuresLILPw(pkg, chatty);
8839            }
8840        }
8841    }
8842
8843    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8844        if (DEBUG_INSTALL) {
8845            if (chatty)
8846                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8847        }
8848
8849        // writer
8850        synchronized (mPackages) {
8851            // Remove the parent package
8852            mPackages.remove(pkg.applicationInfo.packageName);
8853            cleanPackageDataStructuresLILPw(pkg, chatty);
8854
8855            // Remove the child packages
8856            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8857            for (int i = 0; i < childCount; i++) {
8858                PackageParser.Package childPkg = pkg.childPackages.get(i);
8859                mPackages.remove(childPkg.applicationInfo.packageName);
8860                cleanPackageDataStructuresLILPw(childPkg, chatty);
8861            }
8862        }
8863    }
8864
8865    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8866        int N = pkg.providers.size();
8867        StringBuilder r = null;
8868        int i;
8869        for (i=0; i<N; i++) {
8870            PackageParser.Provider p = pkg.providers.get(i);
8871            mProviders.removeProvider(p);
8872            if (p.info.authority == null) {
8873
8874                /* There was another ContentProvider with this authority when
8875                 * this app was installed so this authority is null,
8876                 * Ignore it as we don't have to unregister the provider.
8877                 */
8878                continue;
8879            }
8880            String names[] = p.info.authority.split(";");
8881            for (int j = 0; j < names.length; j++) {
8882                if (mProvidersByAuthority.get(names[j]) == p) {
8883                    mProvidersByAuthority.remove(names[j]);
8884                    if (DEBUG_REMOVE) {
8885                        if (chatty)
8886                            Log.d(TAG, "Unregistered content provider: " + names[j]
8887                                    + ", className = " + p.info.name + ", isSyncable = "
8888                                    + p.info.isSyncable);
8889                    }
8890                }
8891            }
8892            if (DEBUG_REMOVE && chatty) {
8893                if (r == null) {
8894                    r = new StringBuilder(256);
8895                } else {
8896                    r.append(' ');
8897                }
8898                r.append(p.info.name);
8899            }
8900        }
8901        if (r != null) {
8902            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8903        }
8904
8905        N = pkg.services.size();
8906        r = null;
8907        for (i=0; i<N; i++) {
8908            PackageParser.Service s = pkg.services.get(i);
8909            mServices.removeService(s);
8910            if (chatty) {
8911                if (r == null) {
8912                    r = new StringBuilder(256);
8913                } else {
8914                    r.append(' ');
8915                }
8916                r.append(s.info.name);
8917            }
8918        }
8919        if (r != null) {
8920            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8921        }
8922
8923        N = pkg.receivers.size();
8924        r = null;
8925        for (i=0; i<N; i++) {
8926            PackageParser.Activity a = pkg.receivers.get(i);
8927            mReceivers.removeActivity(a, "receiver");
8928            if (DEBUG_REMOVE && chatty) {
8929                if (r == null) {
8930                    r = new StringBuilder(256);
8931                } else {
8932                    r.append(' ');
8933                }
8934                r.append(a.info.name);
8935            }
8936        }
8937        if (r != null) {
8938            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8939        }
8940
8941        N = pkg.activities.size();
8942        r = null;
8943        for (i=0; i<N; i++) {
8944            PackageParser.Activity a = pkg.activities.get(i);
8945            mActivities.removeActivity(a, "activity");
8946            if (DEBUG_REMOVE && chatty) {
8947                if (r == null) {
8948                    r = new StringBuilder(256);
8949                } else {
8950                    r.append(' ');
8951                }
8952                r.append(a.info.name);
8953            }
8954        }
8955        if (r != null) {
8956            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8957        }
8958
8959        N = pkg.permissions.size();
8960        r = null;
8961        for (i=0; i<N; i++) {
8962            PackageParser.Permission p = pkg.permissions.get(i);
8963            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8964            if (bp == null) {
8965                bp = mSettings.mPermissionTrees.get(p.info.name);
8966            }
8967            if (bp != null && bp.perm == p) {
8968                bp.perm = null;
8969                if (DEBUG_REMOVE && chatty) {
8970                    if (r == null) {
8971                        r = new StringBuilder(256);
8972                    } else {
8973                        r.append(' ');
8974                    }
8975                    r.append(p.info.name);
8976                }
8977            }
8978            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8979                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8980                if (appOpPkgs != null) {
8981                    appOpPkgs.remove(pkg.packageName);
8982                }
8983            }
8984        }
8985        if (r != null) {
8986            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8987        }
8988
8989        N = pkg.requestedPermissions.size();
8990        r = null;
8991        for (i=0; i<N; i++) {
8992            String perm = pkg.requestedPermissions.get(i);
8993            BasePermission bp = mSettings.mPermissions.get(perm);
8994            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8995                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8996                if (appOpPkgs != null) {
8997                    appOpPkgs.remove(pkg.packageName);
8998                    if (appOpPkgs.isEmpty()) {
8999                        mAppOpPermissionPackages.remove(perm);
9000                    }
9001                }
9002            }
9003        }
9004        if (r != null) {
9005            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9006        }
9007
9008        N = pkg.instrumentation.size();
9009        r = null;
9010        for (i=0; i<N; i++) {
9011            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9012            mInstrumentation.remove(a.getComponentName());
9013            if (DEBUG_REMOVE && chatty) {
9014                if (r == null) {
9015                    r = new StringBuilder(256);
9016                } else {
9017                    r.append(' ');
9018                }
9019                r.append(a.info.name);
9020            }
9021        }
9022        if (r != null) {
9023            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9024        }
9025
9026        r = null;
9027        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9028            // Only system apps can hold shared libraries.
9029            if (pkg.libraryNames != null) {
9030                for (i=0; i<pkg.libraryNames.size(); i++) {
9031                    String name = pkg.libraryNames.get(i);
9032                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9033                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9034                        mSharedLibraries.remove(name);
9035                        if (DEBUG_REMOVE && chatty) {
9036                            if (r == null) {
9037                                r = new StringBuilder(256);
9038                            } else {
9039                                r.append(' ');
9040                            }
9041                            r.append(name);
9042                        }
9043                    }
9044                }
9045            }
9046        }
9047        if (r != null) {
9048            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9049        }
9050    }
9051
9052    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9053        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9054            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9055                return true;
9056            }
9057        }
9058        return false;
9059    }
9060
9061    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9062    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9063    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9064
9065    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9066        // Update the parent permissions
9067        updatePermissionsLPw(pkg.packageName, pkg, flags);
9068        // Update the child permissions
9069        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9070        for (int i = 0; i < childCount; i++) {
9071            PackageParser.Package childPkg = pkg.childPackages.get(i);
9072            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9073        }
9074    }
9075
9076    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9077            int flags) {
9078        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9079        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9080    }
9081
9082    private void updatePermissionsLPw(String changingPkg,
9083            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9084        // Make sure there are no dangling permission trees.
9085        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9086        while (it.hasNext()) {
9087            final BasePermission bp = it.next();
9088            if (bp.packageSetting == null) {
9089                // We may not yet have parsed the package, so just see if
9090                // we still know about its settings.
9091                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9092            }
9093            if (bp.packageSetting == null) {
9094                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9095                        + " from package " + bp.sourcePackage);
9096                it.remove();
9097            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9098                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9099                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9100                            + " from package " + bp.sourcePackage);
9101                    flags |= UPDATE_PERMISSIONS_ALL;
9102                    it.remove();
9103                }
9104            }
9105        }
9106
9107        // Make sure all dynamic permissions have been assigned to a package,
9108        // and make sure there are no dangling permissions.
9109        it = mSettings.mPermissions.values().iterator();
9110        while (it.hasNext()) {
9111            final BasePermission bp = it.next();
9112            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9113                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9114                        + bp.name + " pkg=" + bp.sourcePackage
9115                        + " info=" + bp.pendingInfo);
9116                if (bp.packageSetting == null && bp.pendingInfo != null) {
9117                    final BasePermission tree = findPermissionTreeLP(bp.name);
9118                    if (tree != null && tree.perm != null) {
9119                        bp.packageSetting = tree.packageSetting;
9120                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9121                                new PermissionInfo(bp.pendingInfo));
9122                        bp.perm.info.packageName = tree.perm.info.packageName;
9123                        bp.perm.info.name = bp.name;
9124                        bp.uid = tree.uid;
9125                    }
9126                }
9127            }
9128            if (bp.packageSetting == null) {
9129                // We may not yet have parsed the package, so just see if
9130                // we still know about its settings.
9131                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9132            }
9133            if (bp.packageSetting == null) {
9134                Slog.w(TAG, "Removing dangling permission: " + bp.name
9135                        + " from package " + bp.sourcePackage);
9136                it.remove();
9137            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9138                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9139                    Slog.i(TAG, "Removing old permission: " + bp.name
9140                            + " from package " + bp.sourcePackage);
9141                    flags |= UPDATE_PERMISSIONS_ALL;
9142                    it.remove();
9143                }
9144            }
9145        }
9146
9147        // Now update the permissions for all packages, in particular
9148        // replace the granted permissions of the system packages.
9149        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9150            for (PackageParser.Package pkg : mPackages.values()) {
9151                if (pkg != pkgInfo) {
9152                    // Only replace for packages on requested volume
9153                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9154                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9155                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9156                    grantPermissionsLPw(pkg, replace, changingPkg);
9157                }
9158            }
9159        }
9160
9161        if (pkgInfo != null) {
9162            // Only replace for packages on requested volume
9163            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9164            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9165                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9166            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9167        }
9168    }
9169
9170    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9171            String packageOfInterest) {
9172        // IMPORTANT: There are two types of permissions: install and runtime.
9173        // Install time permissions are granted when the app is installed to
9174        // all device users and users added in the future. Runtime permissions
9175        // are granted at runtime explicitly to specific users. Normal and signature
9176        // protected permissions are install time permissions. Dangerous permissions
9177        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9178        // otherwise they are runtime permissions. This function does not manage
9179        // runtime permissions except for the case an app targeting Lollipop MR1
9180        // being upgraded to target a newer SDK, in which case dangerous permissions
9181        // are transformed from install time to runtime ones.
9182
9183        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9184        if (ps == null) {
9185            return;
9186        }
9187
9188        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9189
9190        PermissionsState permissionsState = ps.getPermissionsState();
9191        PermissionsState origPermissions = permissionsState;
9192
9193        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9194
9195        boolean runtimePermissionsRevoked = false;
9196        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9197
9198        boolean changedInstallPermission = false;
9199
9200        if (replace) {
9201            ps.installPermissionsFixed = false;
9202            if (!ps.isSharedUser()) {
9203                origPermissions = new PermissionsState(permissionsState);
9204                permissionsState.reset();
9205            } else {
9206                // We need to know only about runtime permission changes since the
9207                // calling code always writes the install permissions state but
9208                // the runtime ones are written only if changed. The only cases of
9209                // changed runtime permissions here are promotion of an install to
9210                // runtime and revocation of a runtime from a shared user.
9211                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9212                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9213                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9214                    runtimePermissionsRevoked = true;
9215                }
9216            }
9217        }
9218
9219        permissionsState.setGlobalGids(mGlobalGids);
9220
9221        final int N = pkg.requestedPermissions.size();
9222        for (int i=0; i<N; i++) {
9223            final String name = pkg.requestedPermissions.get(i);
9224            final BasePermission bp = mSettings.mPermissions.get(name);
9225
9226            if (DEBUG_INSTALL) {
9227                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9228            }
9229
9230            if (bp == null || bp.packageSetting == null) {
9231                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9232                    Slog.w(TAG, "Unknown permission " + name
9233                            + " in package " + pkg.packageName);
9234                }
9235                continue;
9236            }
9237
9238            final String perm = bp.name;
9239            boolean allowedSig = false;
9240            int grant = GRANT_DENIED;
9241
9242            // Keep track of app op permissions.
9243            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9244                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9245                if (pkgs == null) {
9246                    pkgs = new ArraySet<>();
9247                    mAppOpPermissionPackages.put(bp.name, pkgs);
9248                }
9249                pkgs.add(pkg.packageName);
9250            }
9251
9252            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9253            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9254                    >= Build.VERSION_CODES.M;
9255            switch (level) {
9256                case PermissionInfo.PROTECTION_NORMAL: {
9257                    // For all apps normal permissions are install time ones.
9258                    grant = GRANT_INSTALL;
9259                } break;
9260
9261                case PermissionInfo.PROTECTION_DANGEROUS: {
9262                    // If a permission review is required for legacy apps we represent
9263                    // their permissions as always granted runtime ones since we need
9264                    // to keep the review required permission flag per user while an
9265                    // install permission's state is shared across all users.
9266                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9267                        // For legacy apps dangerous permissions are install time ones.
9268                        grant = GRANT_INSTALL;
9269                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9270                        // For legacy apps that became modern, install becomes runtime.
9271                        grant = GRANT_UPGRADE;
9272                    } else if (mPromoteSystemApps
9273                            && isSystemApp(ps)
9274                            && mExistingSystemPackages.contains(ps.name)) {
9275                        // For legacy system apps, install becomes runtime.
9276                        // We cannot check hasInstallPermission() for system apps since those
9277                        // permissions were granted implicitly and not persisted pre-M.
9278                        grant = GRANT_UPGRADE;
9279                    } else {
9280                        // For modern apps keep runtime permissions unchanged.
9281                        grant = GRANT_RUNTIME;
9282                    }
9283                } break;
9284
9285                case PermissionInfo.PROTECTION_SIGNATURE: {
9286                    // For all apps signature permissions are install time ones.
9287                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9288                    if (allowedSig) {
9289                        grant = GRANT_INSTALL;
9290                    }
9291                } break;
9292            }
9293
9294            if (DEBUG_INSTALL) {
9295                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9296            }
9297
9298            if (grant != GRANT_DENIED) {
9299                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9300                    // If this is an existing, non-system package, then
9301                    // we can't add any new permissions to it.
9302                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9303                        // Except...  if this is a permission that was added
9304                        // to the platform (note: need to only do this when
9305                        // updating the platform).
9306                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9307                            grant = GRANT_DENIED;
9308                        }
9309                    }
9310                }
9311
9312                switch (grant) {
9313                    case GRANT_INSTALL: {
9314                        // Revoke this as runtime permission to handle the case of
9315                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9316                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9317                            if (origPermissions.getRuntimePermissionState(
9318                                    bp.name, userId) != null) {
9319                                // Revoke the runtime permission and clear the flags.
9320                                origPermissions.revokeRuntimePermission(bp, userId);
9321                                origPermissions.updatePermissionFlags(bp, userId,
9322                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9323                                // If we revoked a permission permission, we have to write.
9324                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9325                                        changedRuntimePermissionUserIds, userId);
9326                            }
9327                        }
9328                        // Grant an install permission.
9329                        if (permissionsState.grantInstallPermission(bp) !=
9330                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9331                            changedInstallPermission = true;
9332                        }
9333                    } break;
9334
9335                    case GRANT_RUNTIME: {
9336                        // Grant previously granted runtime permissions.
9337                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9338                            PermissionState permissionState = origPermissions
9339                                    .getRuntimePermissionState(bp.name, userId);
9340                            int flags = permissionState != null
9341                                    ? permissionState.getFlags() : 0;
9342                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9343                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9344                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9345                                    // If we cannot put the permission as it was, we have to write.
9346                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9347                                            changedRuntimePermissionUserIds, userId);
9348                                }
9349                                // If the app supports runtime permissions no need for a review.
9350                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9351                                        && appSupportsRuntimePermissions
9352                                        && (flags & PackageManager
9353                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9354                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9355                                    // Since we changed the flags, we have to write.
9356                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9357                                            changedRuntimePermissionUserIds, userId);
9358                                }
9359                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9360                                    && !appSupportsRuntimePermissions) {
9361                                // For legacy apps that need a permission review, every new
9362                                // runtime permission is granted but it is pending a review.
9363                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9364                                    permissionsState.grantRuntimePermission(bp, userId);
9365                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9366                                    // We changed the permission and flags, hence have to write.
9367                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9368                                            changedRuntimePermissionUserIds, userId);
9369                                }
9370                            }
9371                            // Propagate the permission flags.
9372                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9373                        }
9374                    } break;
9375
9376                    case GRANT_UPGRADE: {
9377                        // Grant runtime permissions for a previously held install permission.
9378                        PermissionState permissionState = origPermissions
9379                                .getInstallPermissionState(bp.name);
9380                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9381
9382                        if (origPermissions.revokeInstallPermission(bp)
9383                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9384                            // We will be transferring the permission flags, so clear them.
9385                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9386                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9387                            changedInstallPermission = true;
9388                        }
9389
9390                        // If the permission is not to be promoted to runtime we ignore it and
9391                        // also its other flags as they are not applicable to install permissions.
9392                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9393                            for (int userId : currentUserIds) {
9394                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9395                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9396                                    // Transfer the permission flags.
9397                                    permissionsState.updatePermissionFlags(bp, userId,
9398                                            flags, flags);
9399                                    // If we granted the permission, we have to write.
9400                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9401                                            changedRuntimePermissionUserIds, userId);
9402                                }
9403                            }
9404                        }
9405                    } break;
9406
9407                    default: {
9408                        if (packageOfInterest == null
9409                                || packageOfInterest.equals(pkg.packageName)) {
9410                            Slog.w(TAG, "Not granting permission " + perm
9411                                    + " to package " + pkg.packageName
9412                                    + " because it was previously installed without");
9413                        }
9414                    } break;
9415                }
9416            } else {
9417                if (permissionsState.revokeInstallPermission(bp) !=
9418                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9419                    // Also drop the permission flags.
9420                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9421                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9422                    changedInstallPermission = true;
9423                    Slog.i(TAG, "Un-granting permission " + perm
9424                            + " from package " + pkg.packageName
9425                            + " (protectionLevel=" + bp.protectionLevel
9426                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9427                            + ")");
9428                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9429                    // Don't print warning for app op permissions, since it is fine for them
9430                    // not to be granted, there is a UI for the user to decide.
9431                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9432                        Slog.w(TAG, "Not granting permission " + perm
9433                                + " to package " + pkg.packageName
9434                                + " (protectionLevel=" + bp.protectionLevel
9435                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9436                                + ")");
9437                    }
9438                }
9439            }
9440        }
9441
9442        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9443                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9444            // This is the first that we have heard about this package, so the
9445            // permissions we have now selected are fixed until explicitly
9446            // changed.
9447            ps.installPermissionsFixed = true;
9448        }
9449
9450        // Persist the runtime permissions state for users with changes. If permissions
9451        // were revoked because no app in the shared user declares them we have to
9452        // write synchronously to avoid losing runtime permissions state.
9453        for (int userId : changedRuntimePermissionUserIds) {
9454            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9455        }
9456
9457        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9458    }
9459
9460    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9461        boolean allowed = false;
9462        final int NP = PackageParser.NEW_PERMISSIONS.length;
9463        for (int ip=0; ip<NP; ip++) {
9464            final PackageParser.NewPermissionInfo npi
9465                    = PackageParser.NEW_PERMISSIONS[ip];
9466            if (npi.name.equals(perm)
9467                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9468                allowed = true;
9469                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9470                        + pkg.packageName);
9471                break;
9472            }
9473        }
9474        return allowed;
9475    }
9476
9477    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9478            BasePermission bp, PermissionsState origPermissions) {
9479        boolean allowed;
9480        allowed = (compareSignatures(
9481                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9482                        == PackageManager.SIGNATURE_MATCH)
9483                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9484                        == PackageManager.SIGNATURE_MATCH);
9485        if (!allowed && (bp.protectionLevel
9486                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9487            if (isSystemApp(pkg)) {
9488                // For updated system applications, a system permission
9489                // is granted only if it had been defined by the original application.
9490                if (pkg.isUpdatedSystemApp()) {
9491                    final PackageSetting sysPs = mSettings
9492                            .getDisabledSystemPkgLPr(pkg.packageName);
9493                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9494                        // If the original was granted this permission, we take
9495                        // that grant decision as read and propagate it to the
9496                        // update.
9497                        if (sysPs.isPrivileged()) {
9498                            allowed = true;
9499                        }
9500                    } else {
9501                        // The system apk may have been updated with an older
9502                        // version of the one on the data partition, but which
9503                        // granted a new system permission that it didn't have
9504                        // before.  In this case we do want to allow the app to
9505                        // now get the new permission if the ancestral apk is
9506                        // privileged to get it.
9507                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9508                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9509                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9510                                    allowed = true;
9511                                    break;
9512                                }
9513                            }
9514                        }
9515                        // Also if a privileged parent package on the system image or any of
9516                        // its children requested a privileged permission, the updated child
9517                        // packages can also get the permission.
9518                        if (pkg.parentPackage != null) {
9519                            final PackageSetting disabledSysParentPs = mSettings
9520                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9521                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9522                                    && disabledSysParentPs.isPrivileged()) {
9523                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9524                                    allowed = true;
9525                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9526                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9527                                    for (int i = 0; i < count; i++) {
9528                                        PackageParser.Package disabledSysChildPkg =
9529                                                disabledSysParentPs.pkg.childPackages.get(i);
9530                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9531                                                perm)) {
9532                                            allowed = true;
9533                                            break;
9534                                        }
9535                                    }
9536                                }
9537                            }
9538                        }
9539                    }
9540                } else {
9541                    allowed = isPrivilegedApp(pkg);
9542                }
9543            }
9544        }
9545        if (!allowed) {
9546            if (!allowed && (bp.protectionLevel
9547                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9548                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9549                // If this was a previously normal/dangerous permission that got moved
9550                // to a system permission as part of the runtime permission redesign, then
9551                // we still want to blindly grant it to old apps.
9552                allowed = true;
9553            }
9554            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9555                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9556                // If this permission is to be granted to the system installer and
9557                // this app is an installer, then it gets the permission.
9558                allowed = true;
9559            }
9560            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9561                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9562                // If this permission is to be granted to the system verifier and
9563                // this app is a verifier, then it gets the permission.
9564                allowed = true;
9565            }
9566            if (!allowed && (bp.protectionLevel
9567                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9568                    && isSystemApp(pkg)) {
9569                // Any pre-installed system app is allowed to get this permission.
9570                allowed = true;
9571            }
9572            if (!allowed && (bp.protectionLevel
9573                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9574                // For development permissions, a development permission
9575                // is granted only if it was already granted.
9576                allowed = origPermissions.hasInstallPermission(perm);
9577            }
9578        }
9579        return allowed;
9580    }
9581
9582    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9583        final int permCount = pkg.requestedPermissions.size();
9584        for (int j = 0; j < permCount; j++) {
9585            String requestedPermission = pkg.requestedPermissions.get(j);
9586            if (permission.equals(requestedPermission)) {
9587                return true;
9588            }
9589        }
9590        return false;
9591    }
9592
9593    final class ActivityIntentResolver
9594            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9595        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9596                boolean defaultOnly, int userId) {
9597            if (!sUserManager.exists(userId)) return null;
9598            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9599            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9600        }
9601
9602        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9603                int userId) {
9604            if (!sUserManager.exists(userId)) return null;
9605            mFlags = flags;
9606            return super.queryIntent(intent, resolvedType,
9607                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9608        }
9609
9610        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9611                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9612            if (!sUserManager.exists(userId)) return null;
9613            if (packageActivities == null) {
9614                return null;
9615            }
9616            mFlags = flags;
9617            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9618            final int N = packageActivities.size();
9619            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9620                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9621
9622            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9623            for (int i = 0; i < N; ++i) {
9624                intentFilters = packageActivities.get(i).intents;
9625                if (intentFilters != null && intentFilters.size() > 0) {
9626                    PackageParser.ActivityIntentInfo[] array =
9627                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9628                    intentFilters.toArray(array);
9629                    listCut.add(array);
9630                }
9631            }
9632            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9633        }
9634
9635        public final void addActivity(PackageParser.Activity a, String type) {
9636            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9637            mActivities.put(a.getComponentName(), a);
9638            if (DEBUG_SHOW_INFO)
9639                Log.v(
9640                TAG, "  " + type + " " +
9641                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9642            if (DEBUG_SHOW_INFO)
9643                Log.v(TAG, "    Class=" + a.info.name);
9644            final int NI = a.intents.size();
9645            for (int j=0; j<NI; j++) {
9646                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9647                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9648                    intent.setPriority(0);
9649                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9650                            + a.className + " with priority > 0, forcing to 0");
9651                }
9652                if (DEBUG_SHOW_INFO) {
9653                    Log.v(TAG, "    IntentFilter:");
9654                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9655                }
9656                if (!intent.debugCheck()) {
9657                    Log.w(TAG, "==> For Activity " + a.info.name);
9658                }
9659                addFilter(intent);
9660            }
9661        }
9662
9663        public final void removeActivity(PackageParser.Activity a, String type) {
9664            mActivities.remove(a.getComponentName());
9665            if (DEBUG_SHOW_INFO) {
9666                Log.v(TAG, "  " + type + " "
9667                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9668                                : a.info.name) + ":");
9669                Log.v(TAG, "    Class=" + a.info.name);
9670            }
9671            final int NI = a.intents.size();
9672            for (int j=0; j<NI; j++) {
9673                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9674                if (DEBUG_SHOW_INFO) {
9675                    Log.v(TAG, "    IntentFilter:");
9676                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9677                }
9678                removeFilter(intent);
9679            }
9680        }
9681
9682        @Override
9683        protected boolean allowFilterResult(
9684                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9685            ActivityInfo filterAi = filter.activity.info;
9686            for (int i=dest.size()-1; i>=0; i--) {
9687                ActivityInfo destAi = dest.get(i).activityInfo;
9688                if (destAi.name == filterAi.name
9689                        && destAi.packageName == filterAi.packageName) {
9690                    return false;
9691                }
9692            }
9693            return true;
9694        }
9695
9696        @Override
9697        protected ActivityIntentInfo[] newArray(int size) {
9698            return new ActivityIntentInfo[size];
9699        }
9700
9701        @Override
9702        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9703            if (!sUserManager.exists(userId)) return true;
9704            PackageParser.Package p = filter.activity.owner;
9705            if (p != null) {
9706                PackageSetting ps = (PackageSetting)p.mExtras;
9707                if (ps != null) {
9708                    // System apps are never considered stopped for purposes of
9709                    // filtering, because there may be no way for the user to
9710                    // actually re-launch them.
9711                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9712                            && ps.getStopped(userId);
9713                }
9714            }
9715            return false;
9716        }
9717
9718        @Override
9719        protected boolean isPackageForFilter(String packageName,
9720                PackageParser.ActivityIntentInfo info) {
9721            return packageName.equals(info.activity.owner.packageName);
9722        }
9723
9724        @Override
9725        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9726                int match, int userId) {
9727            if (!sUserManager.exists(userId)) return null;
9728            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9729                return null;
9730            }
9731            final PackageParser.Activity activity = info.activity;
9732            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9733            if (ps == null) {
9734                return null;
9735            }
9736            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9737                    ps.readUserState(userId), userId);
9738            if (ai == null) {
9739                return null;
9740            }
9741            final ResolveInfo res = new ResolveInfo();
9742            res.activityInfo = ai;
9743            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9744                res.filter = info;
9745            }
9746            if (info != null) {
9747                res.handleAllWebDataURI = info.handleAllWebDataURI();
9748            }
9749            res.priority = info.getPriority();
9750            res.preferredOrder = activity.owner.mPreferredOrder;
9751            //System.out.println("Result: " + res.activityInfo.className +
9752            //                   " = " + res.priority);
9753            res.match = match;
9754            res.isDefault = info.hasDefault;
9755            res.labelRes = info.labelRes;
9756            res.nonLocalizedLabel = info.nonLocalizedLabel;
9757            if (userNeedsBadging(userId)) {
9758                res.noResourceId = true;
9759            } else {
9760                res.icon = info.icon;
9761            }
9762            res.iconResourceId = info.icon;
9763            res.system = res.activityInfo.applicationInfo.isSystemApp();
9764            return res;
9765        }
9766
9767        @Override
9768        protected void sortResults(List<ResolveInfo> results) {
9769            Collections.sort(results, mResolvePrioritySorter);
9770        }
9771
9772        @Override
9773        protected void dumpFilter(PrintWriter out, String prefix,
9774                PackageParser.ActivityIntentInfo filter) {
9775            out.print(prefix); out.print(
9776                    Integer.toHexString(System.identityHashCode(filter.activity)));
9777                    out.print(' ');
9778                    filter.activity.printComponentShortName(out);
9779                    out.print(" filter ");
9780                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9781        }
9782
9783        @Override
9784        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9785            return filter.activity;
9786        }
9787
9788        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9789            PackageParser.Activity activity = (PackageParser.Activity)label;
9790            out.print(prefix); out.print(
9791                    Integer.toHexString(System.identityHashCode(activity)));
9792                    out.print(' ');
9793                    activity.printComponentShortName(out);
9794            if (count > 1) {
9795                out.print(" ("); out.print(count); out.print(" filters)");
9796            }
9797            out.println();
9798        }
9799
9800//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9801//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9802//            final List<ResolveInfo> retList = Lists.newArrayList();
9803//            while (i.hasNext()) {
9804//                final ResolveInfo resolveInfo = i.next();
9805//                if (isEnabledLP(resolveInfo.activityInfo)) {
9806//                    retList.add(resolveInfo);
9807//                }
9808//            }
9809//            return retList;
9810//        }
9811
9812        // Keys are String (activity class name), values are Activity.
9813        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9814                = new ArrayMap<ComponentName, PackageParser.Activity>();
9815        private int mFlags;
9816    }
9817
9818    private final class ServiceIntentResolver
9819            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9820        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9821                boolean defaultOnly, int userId) {
9822            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9823            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9824        }
9825
9826        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9827                int userId) {
9828            if (!sUserManager.exists(userId)) return null;
9829            mFlags = flags;
9830            return super.queryIntent(intent, resolvedType,
9831                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9832        }
9833
9834        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9835                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9836            if (!sUserManager.exists(userId)) return null;
9837            if (packageServices == null) {
9838                return null;
9839            }
9840            mFlags = flags;
9841            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9842            final int N = packageServices.size();
9843            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9844                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9845
9846            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9847            for (int i = 0; i < N; ++i) {
9848                intentFilters = packageServices.get(i).intents;
9849                if (intentFilters != null && intentFilters.size() > 0) {
9850                    PackageParser.ServiceIntentInfo[] array =
9851                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9852                    intentFilters.toArray(array);
9853                    listCut.add(array);
9854                }
9855            }
9856            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9857        }
9858
9859        public final void addService(PackageParser.Service s) {
9860            mServices.put(s.getComponentName(), s);
9861            if (DEBUG_SHOW_INFO) {
9862                Log.v(TAG, "  "
9863                        + (s.info.nonLocalizedLabel != null
9864                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9865                Log.v(TAG, "    Class=" + s.info.name);
9866            }
9867            final int NI = s.intents.size();
9868            int j;
9869            for (j=0; j<NI; j++) {
9870                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9871                if (DEBUG_SHOW_INFO) {
9872                    Log.v(TAG, "    IntentFilter:");
9873                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9874                }
9875                if (!intent.debugCheck()) {
9876                    Log.w(TAG, "==> For Service " + s.info.name);
9877                }
9878                addFilter(intent);
9879            }
9880        }
9881
9882        public final void removeService(PackageParser.Service s) {
9883            mServices.remove(s.getComponentName());
9884            if (DEBUG_SHOW_INFO) {
9885                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9886                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9887                Log.v(TAG, "    Class=" + s.info.name);
9888            }
9889            final int NI = s.intents.size();
9890            int j;
9891            for (j=0; j<NI; j++) {
9892                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9893                if (DEBUG_SHOW_INFO) {
9894                    Log.v(TAG, "    IntentFilter:");
9895                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9896                }
9897                removeFilter(intent);
9898            }
9899        }
9900
9901        @Override
9902        protected boolean allowFilterResult(
9903                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9904            ServiceInfo filterSi = filter.service.info;
9905            for (int i=dest.size()-1; i>=0; i--) {
9906                ServiceInfo destAi = dest.get(i).serviceInfo;
9907                if (destAi.name == filterSi.name
9908                        && destAi.packageName == filterSi.packageName) {
9909                    return false;
9910                }
9911            }
9912            return true;
9913        }
9914
9915        @Override
9916        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9917            return new PackageParser.ServiceIntentInfo[size];
9918        }
9919
9920        @Override
9921        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9922            if (!sUserManager.exists(userId)) return true;
9923            PackageParser.Package p = filter.service.owner;
9924            if (p != null) {
9925                PackageSetting ps = (PackageSetting)p.mExtras;
9926                if (ps != null) {
9927                    // System apps are never considered stopped for purposes of
9928                    // filtering, because there may be no way for the user to
9929                    // actually re-launch them.
9930                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9931                            && ps.getStopped(userId);
9932                }
9933            }
9934            return false;
9935        }
9936
9937        @Override
9938        protected boolean isPackageForFilter(String packageName,
9939                PackageParser.ServiceIntentInfo info) {
9940            return packageName.equals(info.service.owner.packageName);
9941        }
9942
9943        @Override
9944        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9945                int match, int userId) {
9946            if (!sUserManager.exists(userId)) return null;
9947            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9948            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9949                return null;
9950            }
9951            final PackageParser.Service service = info.service;
9952            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9953            if (ps == null) {
9954                return null;
9955            }
9956            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9957                    ps.readUserState(userId), userId);
9958            if (si == null) {
9959                return null;
9960            }
9961            final ResolveInfo res = new ResolveInfo();
9962            res.serviceInfo = si;
9963            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9964                res.filter = filter;
9965            }
9966            res.priority = info.getPriority();
9967            res.preferredOrder = service.owner.mPreferredOrder;
9968            res.match = match;
9969            res.isDefault = info.hasDefault;
9970            res.labelRes = info.labelRes;
9971            res.nonLocalizedLabel = info.nonLocalizedLabel;
9972            res.icon = info.icon;
9973            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9974            return res;
9975        }
9976
9977        @Override
9978        protected void sortResults(List<ResolveInfo> results) {
9979            Collections.sort(results, mResolvePrioritySorter);
9980        }
9981
9982        @Override
9983        protected void dumpFilter(PrintWriter out, String prefix,
9984                PackageParser.ServiceIntentInfo filter) {
9985            out.print(prefix); out.print(
9986                    Integer.toHexString(System.identityHashCode(filter.service)));
9987                    out.print(' ');
9988                    filter.service.printComponentShortName(out);
9989                    out.print(" filter ");
9990                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9991        }
9992
9993        @Override
9994        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9995            return filter.service;
9996        }
9997
9998        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9999            PackageParser.Service service = (PackageParser.Service)label;
10000            out.print(prefix); out.print(
10001                    Integer.toHexString(System.identityHashCode(service)));
10002                    out.print(' ');
10003                    service.printComponentShortName(out);
10004            if (count > 1) {
10005                out.print(" ("); out.print(count); out.print(" filters)");
10006            }
10007            out.println();
10008        }
10009
10010//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10011//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10012//            final List<ResolveInfo> retList = Lists.newArrayList();
10013//            while (i.hasNext()) {
10014//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10015//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10016//                    retList.add(resolveInfo);
10017//                }
10018//            }
10019//            return retList;
10020//        }
10021
10022        // Keys are String (activity class name), values are Activity.
10023        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10024                = new ArrayMap<ComponentName, PackageParser.Service>();
10025        private int mFlags;
10026    };
10027
10028    private final class ProviderIntentResolver
10029            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10030        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10031                boolean defaultOnly, int userId) {
10032            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10033            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10034        }
10035
10036        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10037                int userId) {
10038            if (!sUserManager.exists(userId))
10039                return null;
10040            mFlags = flags;
10041            return super.queryIntent(intent, resolvedType,
10042                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10043        }
10044
10045        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10046                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10047            if (!sUserManager.exists(userId))
10048                return null;
10049            if (packageProviders == null) {
10050                return null;
10051            }
10052            mFlags = flags;
10053            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10054            final int N = packageProviders.size();
10055            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10056                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10057
10058            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10059            for (int i = 0; i < N; ++i) {
10060                intentFilters = packageProviders.get(i).intents;
10061                if (intentFilters != null && intentFilters.size() > 0) {
10062                    PackageParser.ProviderIntentInfo[] array =
10063                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10064                    intentFilters.toArray(array);
10065                    listCut.add(array);
10066                }
10067            }
10068            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10069        }
10070
10071        public final void addProvider(PackageParser.Provider p) {
10072            if (mProviders.containsKey(p.getComponentName())) {
10073                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10074                return;
10075            }
10076
10077            mProviders.put(p.getComponentName(), p);
10078            if (DEBUG_SHOW_INFO) {
10079                Log.v(TAG, "  "
10080                        + (p.info.nonLocalizedLabel != null
10081                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10082                Log.v(TAG, "    Class=" + p.info.name);
10083            }
10084            final int NI = p.intents.size();
10085            int j;
10086            for (j = 0; j < NI; j++) {
10087                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10088                if (DEBUG_SHOW_INFO) {
10089                    Log.v(TAG, "    IntentFilter:");
10090                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10091                }
10092                if (!intent.debugCheck()) {
10093                    Log.w(TAG, "==> For Provider " + p.info.name);
10094                }
10095                addFilter(intent);
10096            }
10097        }
10098
10099        public final void removeProvider(PackageParser.Provider p) {
10100            mProviders.remove(p.getComponentName());
10101            if (DEBUG_SHOW_INFO) {
10102                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10103                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10104                Log.v(TAG, "    Class=" + p.info.name);
10105            }
10106            final int NI = p.intents.size();
10107            int j;
10108            for (j = 0; j < NI; j++) {
10109                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10110                if (DEBUG_SHOW_INFO) {
10111                    Log.v(TAG, "    IntentFilter:");
10112                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10113                }
10114                removeFilter(intent);
10115            }
10116        }
10117
10118        @Override
10119        protected boolean allowFilterResult(
10120                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10121            ProviderInfo filterPi = filter.provider.info;
10122            for (int i = dest.size() - 1; i >= 0; i--) {
10123                ProviderInfo destPi = dest.get(i).providerInfo;
10124                if (destPi.name == filterPi.name
10125                        && destPi.packageName == filterPi.packageName) {
10126                    return false;
10127                }
10128            }
10129            return true;
10130        }
10131
10132        @Override
10133        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10134            return new PackageParser.ProviderIntentInfo[size];
10135        }
10136
10137        @Override
10138        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10139            if (!sUserManager.exists(userId))
10140                return true;
10141            PackageParser.Package p = filter.provider.owner;
10142            if (p != null) {
10143                PackageSetting ps = (PackageSetting) p.mExtras;
10144                if (ps != null) {
10145                    // System apps are never considered stopped for purposes of
10146                    // filtering, because there may be no way for the user to
10147                    // actually re-launch them.
10148                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10149                            && ps.getStopped(userId);
10150                }
10151            }
10152            return false;
10153        }
10154
10155        @Override
10156        protected boolean isPackageForFilter(String packageName,
10157                PackageParser.ProviderIntentInfo info) {
10158            return packageName.equals(info.provider.owner.packageName);
10159        }
10160
10161        @Override
10162        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10163                int match, int userId) {
10164            if (!sUserManager.exists(userId))
10165                return null;
10166            final PackageParser.ProviderIntentInfo info = filter;
10167            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10168                return null;
10169            }
10170            final PackageParser.Provider provider = info.provider;
10171            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10172            if (ps == null) {
10173                return null;
10174            }
10175            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10176                    ps.readUserState(userId), userId);
10177            if (pi == null) {
10178                return null;
10179            }
10180            final ResolveInfo res = new ResolveInfo();
10181            res.providerInfo = pi;
10182            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10183                res.filter = filter;
10184            }
10185            res.priority = info.getPriority();
10186            res.preferredOrder = provider.owner.mPreferredOrder;
10187            res.match = match;
10188            res.isDefault = info.hasDefault;
10189            res.labelRes = info.labelRes;
10190            res.nonLocalizedLabel = info.nonLocalizedLabel;
10191            res.icon = info.icon;
10192            res.system = res.providerInfo.applicationInfo.isSystemApp();
10193            return res;
10194        }
10195
10196        @Override
10197        protected void sortResults(List<ResolveInfo> results) {
10198            Collections.sort(results, mResolvePrioritySorter);
10199        }
10200
10201        @Override
10202        protected void dumpFilter(PrintWriter out, String prefix,
10203                PackageParser.ProviderIntentInfo filter) {
10204            out.print(prefix);
10205            out.print(
10206                    Integer.toHexString(System.identityHashCode(filter.provider)));
10207            out.print(' ');
10208            filter.provider.printComponentShortName(out);
10209            out.print(" filter ");
10210            out.println(Integer.toHexString(System.identityHashCode(filter)));
10211        }
10212
10213        @Override
10214        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10215            return filter.provider;
10216        }
10217
10218        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10219            PackageParser.Provider provider = (PackageParser.Provider)label;
10220            out.print(prefix); out.print(
10221                    Integer.toHexString(System.identityHashCode(provider)));
10222                    out.print(' ');
10223                    provider.printComponentShortName(out);
10224            if (count > 1) {
10225                out.print(" ("); out.print(count); out.print(" filters)");
10226            }
10227            out.println();
10228        }
10229
10230        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10231                = new ArrayMap<ComponentName, PackageParser.Provider>();
10232        private int mFlags;
10233    }
10234
10235    private static final class EphemeralIntentResolver
10236            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10237        @Override
10238        protected EphemeralResolveIntentInfo[] newArray(int size) {
10239            return new EphemeralResolveIntentInfo[size];
10240        }
10241
10242        @Override
10243        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10244            return true;
10245        }
10246
10247        @Override
10248        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10249                int userId) {
10250            if (!sUserManager.exists(userId)) {
10251                return null;
10252            }
10253            return info.getEphemeralResolveInfo();
10254        }
10255    }
10256
10257    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10258            new Comparator<ResolveInfo>() {
10259        public int compare(ResolveInfo r1, ResolveInfo r2) {
10260            int v1 = r1.priority;
10261            int v2 = r2.priority;
10262            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10263            if (v1 != v2) {
10264                return (v1 > v2) ? -1 : 1;
10265            }
10266            v1 = r1.preferredOrder;
10267            v2 = r2.preferredOrder;
10268            if (v1 != v2) {
10269                return (v1 > v2) ? -1 : 1;
10270            }
10271            if (r1.isDefault != r2.isDefault) {
10272                return r1.isDefault ? -1 : 1;
10273            }
10274            v1 = r1.match;
10275            v2 = r2.match;
10276            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10277            if (v1 != v2) {
10278                return (v1 > v2) ? -1 : 1;
10279            }
10280            if (r1.system != r2.system) {
10281                return r1.system ? -1 : 1;
10282            }
10283            if (r1.activityInfo != null) {
10284                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10285            }
10286            if (r1.serviceInfo != null) {
10287                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10288            }
10289            if (r1.providerInfo != null) {
10290                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10291            }
10292            return 0;
10293        }
10294    };
10295
10296    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10297            new Comparator<ProviderInfo>() {
10298        public int compare(ProviderInfo p1, ProviderInfo p2) {
10299            final int v1 = p1.initOrder;
10300            final int v2 = p2.initOrder;
10301            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10302        }
10303    };
10304
10305    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10306            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10307            final int[] userIds) {
10308        mHandler.post(new Runnable() {
10309            @Override
10310            public void run() {
10311                try {
10312                    final IActivityManager am = ActivityManagerNative.getDefault();
10313                    if (am == null) return;
10314                    final int[] resolvedUserIds;
10315                    if (userIds == null) {
10316                        resolvedUserIds = am.getRunningUserIds();
10317                    } else {
10318                        resolvedUserIds = userIds;
10319                    }
10320                    for (int id : resolvedUserIds) {
10321                        final Intent intent = new Intent(action,
10322                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10323                        if (extras != null) {
10324                            intent.putExtras(extras);
10325                        }
10326                        if (targetPkg != null) {
10327                            intent.setPackage(targetPkg);
10328                        }
10329                        // Modify the UID when posting to other users
10330                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10331                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10332                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10333                            intent.putExtra(Intent.EXTRA_UID, uid);
10334                        }
10335                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10336                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10337                        if (DEBUG_BROADCASTS) {
10338                            RuntimeException here = new RuntimeException("here");
10339                            here.fillInStackTrace();
10340                            Slog.d(TAG, "Sending to user " + id + ": "
10341                                    + intent.toShortString(false, true, false, false)
10342                                    + " " + intent.getExtras(), here);
10343                        }
10344                        am.broadcastIntent(null, intent, null, finishedReceiver,
10345                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10346                                null, finishedReceiver != null, false, id);
10347                    }
10348                } catch (RemoteException ex) {
10349                }
10350            }
10351        });
10352    }
10353
10354    /**
10355     * Check if the external storage media is available. This is true if there
10356     * is a mounted external storage medium or if the external storage is
10357     * emulated.
10358     */
10359    private boolean isExternalMediaAvailable() {
10360        return mMediaMounted || Environment.isExternalStorageEmulated();
10361    }
10362
10363    @Override
10364    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10365        // writer
10366        synchronized (mPackages) {
10367            if (!isExternalMediaAvailable()) {
10368                // If the external storage is no longer mounted at this point,
10369                // the caller may not have been able to delete all of this
10370                // packages files and can not delete any more.  Bail.
10371                return null;
10372            }
10373            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10374            if (lastPackage != null) {
10375                pkgs.remove(lastPackage);
10376            }
10377            if (pkgs.size() > 0) {
10378                return pkgs.get(0);
10379            }
10380        }
10381        return null;
10382    }
10383
10384    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10385        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10386                userId, andCode ? 1 : 0, packageName);
10387        if (mSystemReady) {
10388            msg.sendToTarget();
10389        } else {
10390            if (mPostSystemReadyMessages == null) {
10391                mPostSystemReadyMessages = new ArrayList<>();
10392            }
10393            mPostSystemReadyMessages.add(msg);
10394        }
10395    }
10396
10397    void startCleaningPackages() {
10398        // reader
10399        synchronized (mPackages) {
10400            if (!isExternalMediaAvailable()) {
10401                return;
10402            }
10403            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10404                return;
10405            }
10406        }
10407        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10408        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10409        IActivityManager am = ActivityManagerNative.getDefault();
10410        if (am != null) {
10411            try {
10412                am.startService(null, intent, null, mContext.getOpPackageName(),
10413                        UserHandle.USER_SYSTEM);
10414            } catch (RemoteException e) {
10415            }
10416        }
10417    }
10418
10419    @Override
10420    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10421            int installFlags, String installerPackageName, int userId) {
10422        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10423
10424        final int callingUid = Binder.getCallingUid();
10425        enforceCrossUserPermission(callingUid, userId,
10426                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10427
10428        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10429            try {
10430                if (observer != null) {
10431                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10432                }
10433            } catch (RemoteException re) {
10434            }
10435            return;
10436        }
10437
10438        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10439            installFlags |= PackageManager.INSTALL_FROM_ADB;
10440
10441        } else {
10442            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10443            // about installerPackageName.
10444
10445            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10446            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10447        }
10448
10449        UserHandle user;
10450        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10451            user = UserHandle.ALL;
10452        } else {
10453            user = new UserHandle(userId);
10454        }
10455
10456        // Only system components can circumvent runtime permissions when installing.
10457        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10458                && mContext.checkCallingOrSelfPermission(Manifest.permission
10459                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10460            throw new SecurityException("You need the "
10461                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10462                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10463        }
10464
10465        final File originFile = new File(originPath);
10466        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10467
10468        final Message msg = mHandler.obtainMessage(INIT_COPY);
10469        final VerificationInfo verificationInfo = new VerificationInfo(
10470                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10471        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10472                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10473                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10474        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10475        msg.obj = params;
10476
10477        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10478                System.identityHashCode(msg.obj));
10479        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10480                System.identityHashCode(msg.obj));
10481
10482        mHandler.sendMessage(msg);
10483    }
10484
10485    void installStage(String packageName, File stagedDir, String stagedCid,
10486            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10487            String installerPackageName, int installerUid, UserHandle user) {
10488        if (DEBUG_EPHEMERAL) {
10489            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10490                Slog.d(TAG, "Ephemeral install of " + packageName);
10491            }
10492        }
10493        final VerificationInfo verificationInfo = new VerificationInfo(
10494                sessionParams.originatingUri, sessionParams.referrerUri,
10495                sessionParams.originatingUid, installerUid);
10496
10497        final OriginInfo origin;
10498        if (stagedDir != null) {
10499            origin = OriginInfo.fromStagedFile(stagedDir);
10500        } else {
10501            origin = OriginInfo.fromStagedContainer(stagedCid);
10502        }
10503
10504        final Message msg = mHandler.obtainMessage(INIT_COPY);
10505        final InstallParams params = new InstallParams(origin, null, observer,
10506                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10507                verificationInfo, user, sessionParams.abiOverride,
10508                sessionParams.grantedRuntimePermissions);
10509        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10510        msg.obj = params;
10511
10512        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10513                System.identityHashCode(msg.obj));
10514        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10515                System.identityHashCode(msg.obj));
10516
10517        mHandler.sendMessage(msg);
10518    }
10519
10520    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10521            int userId) {
10522        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10523        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10524    }
10525
10526    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10527            int appId, int userId) {
10528        Bundle extras = new Bundle(1);
10529        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10530
10531        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10532                packageName, extras, 0, null, null, new int[] {userId});
10533        try {
10534            IActivityManager am = ActivityManagerNative.getDefault();
10535            if (isSystem && am.isUserRunning(userId, 0)) {
10536                // The just-installed/enabled app is bundled on the system, so presumed
10537                // to be able to run automatically without needing an explicit launch.
10538                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10539                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10540                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10541                        .setPackage(packageName);
10542                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10543                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10544            }
10545        } catch (RemoteException e) {
10546            // shouldn't happen
10547            Slog.w(TAG, "Unable to bootstrap installed package", e);
10548        }
10549    }
10550
10551    @Override
10552    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10553            int userId) {
10554        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10555        PackageSetting pkgSetting;
10556        final int uid = Binder.getCallingUid();
10557        enforceCrossUserPermission(uid, userId,
10558                true /* requireFullPermission */, true /* checkShell */,
10559                "setApplicationHiddenSetting for user " + userId);
10560
10561        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10562            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10563            return false;
10564        }
10565
10566        long callingId = Binder.clearCallingIdentity();
10567        try {
10568            boolean sendAdded = false;
10569            boolean sendRemoved = false;
10570            // writer
10571            synchronized (mPackages) {
10572                pkgSetting = mSettings.mPackages.get(packageName);
10573                if (pkgSetting == null) {
10574                    return false;
10575                }
10576                if (pkgSetting.getHidden(userId) != hidden) {
10577                    pkgSetting.setHidden(hidden, userId);
10578                    mSettings.writePackageRestrictionsLPr(userId);
10579                    if (hidden) {
10580                        sendRemoved = true;
10581                    } else {
10582                        sendAdded = true;
10583                    }
10584                }
10585            }
10586            if (sendAdded) {
10587                sendPackageAddedForUser(packageName, pkgSetting, userId);
10588                return true;
10589            }
10590            if (sendRemoved) {
10591                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10592                        "hiding pkg");
10593                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10594                return true;
10595            }
10596        } finally {
10597            Binder.restoreCallingIdentity(callingId);
10598        }
10599        return false;
10600    }
10601
10602    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10603            int userId) {
10604        final PackageRemovedInfo info = new PackageRemovedInfo();
10605        info.removedPackage = packageName;
10606        info.removedUsers = new int[] {userId};
10607        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10608        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10609    }
10610
10611    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10612        if (pkgList.length > 0) {
10613            Bundle extras = new Bundle(1);
10614            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10615
10616            sendPackageBroadcast(
10617                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10618                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10619                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10620                    new int[] {userId});
10621        }
10622    }
10623
10624    /**
10625     * Returns true if application is not found or there was an error. Otherwise it returns
10626     * the hidden state of the package for the given user.
10627     */
10628    @Override
10629    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10630        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10631        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10632                true /* requireFullPermission */, false /* checkShell */,
10633                "getApplicationHidden for user " + userId);
10634        PackageSetting pkgSetting;
10635        long callingId = Binder.clearCallingIdentity();
10636        try {
10637            // writer
10638            synchronized (mPackages) {
10639                pkgSetting = mSettings.mPackages.get(packageName);
10640                if (pkgSetting == null) {
10641                    return true;
10642                }
10643                return pkgSetting.getHidden(userId);
10644            }
10645        } finally {
10646            Binder.restoreCallingIdentity(callingId);
10647        }
10648    }
10649
10650    /**
10651     * @hide
10652     */
10653    @Override
10654    public int installExistingPackageAsUser(String packageName, int userId) {
10655        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10656                null);
10657        PackageSetting pkgSetting;
10658        final int uid = Binder.getCallingUid();
10659        enforceCrossUserPermission(uid, userId,
10660                true /* requireFullPermission */, true /* checkShell */,
10661                "installExistingPackage for user " + userId);
10662        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10663            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10664        }
10665
10666        long callingId = Binder.clearCallingIdentity();
10667        try {
10668            boolean installed = false;
10669
10670            // writer
10671            synchronized (mPackages) {
10672                pkgSetting = mSettings.mPackages.get(packageName);
10673                if (pkgSetting == null) {
10674                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10675                }
10676                if (!pkgSetting.getInstalled(userId)) {
10677                    pkgSetting.setInstalled(true, userId);
10678                    pkgSetting.setHidden(false, userId);
10679                    mSettings.writePackageRestrictionsLPr(userId);
10680                    installed = true;
10681                }
10682            }
10683
10684            if (installed) {
10685                if (pkgSetting.pkg != null) {
10686                    prepareAppDataAfterInstall(pkgSetting.pkg);
10687                }
10688                sendPackageAddedForUser(packageName, pkgSetting, userId);
10689            }
10690        } finally {
10691            Binder.restoreCallingIdentity(callingId);
10692        }
10693
10694        return PackageManager.INSTALL_SUCCEEDED;
10695    }
10696
10697    boolean isUserRestricted(int userId, String restrictionKey) {
10698        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10699        if (restrictions.getBoolean(restrictionKey, false)) {
10700            Log.w(TAG, "User is restricted: " + restrictionKey);
10701            return true;
10702        }
10703        return false;
10704    }
10705
10706    @Override
10707    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10708            int userId) {
10709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10710        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10711                true /* requireFullPermission */, true /* checkShell */,
10712                "setPackagesSuspended for user " + userId);
10713
10714        if (ArrayUtils.isEmpty(packageNames)) {
10715            return packageNames;
10716        }
10717
10718        // List of package names for whom the suspended state has changed.
10719        List<String> changedPackages = new ArrayList<>(packageNames.length);
10720        // List of package names for whom the suspended state is not set as requested in this
10721        // method.
10722        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10723        for (int i = 0; i < packageNames.length; i++) {
10724            String packageName = packageNames[i];
10725            long callingId = Binder.clearCallingIdentity();
10726            try {
10727                boolean changed = false;
10728                final int appId;
10729                synchronized (mPackages) {
10730                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10731                    if (pkgSetting == null) {
10732                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10733                                + "\". Skipping suspending/un-suspending.");
10734                        unactionedPackages.add(packageName);
10735                        continue;
10736                    }
10737                    appId = pkgSetting.appId;
10738                    if (pkgSetting.getSuspended(userId) != suspended) {
10739                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10740                            unactionedPackages.add(packageName);
10741                            continue;
10742                        }
10743                        pkgSetting.setSuspended(suspended, userId);
10744                        mSettings.writePackageRestrictionsLPr(userId);
10745                        changed = true;
10746                        changedPackages.add(packageName);
10747                    }
10748                }
10749
10750                if (changed && suspended) {
10751                    killApplication(packageName, UserHandle.getUid(userId, appId),
10752                            "suspending package");
10753                }
10754            } finally {
10755                Binder.restoreCallingIdentity(callingId);
10756            }
10757        }
10758
10759        if (!changedPackages.isEmpty()) {
10760            sendPackagesSuspendedForUser(changedPackages.toArray(
10761                    new String[changedPackages.size()]), userId, suspended);
10762        }
10763
10764        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10765    }
10766
10767    @Override
10768    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10769        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10770                true /* requireFullPermission */, false /* checkShell */,
10771                "isPackageSuspendedForUser for user " + userId);
10772        synchronized (mPackages) {
10773            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10774            return pkgSetting != null && pkgSetting.getSuspended(userId);
10775        }
10776    }
10777
10778    // TODO: investigate and add more restrictions for suspending crucial packages.
10779    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10780        if (isPackageDeviceAdmin(packageName, userId)) {
10781            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10782                    + "\": has active device admin");
10783            return false;
10784        }
10785
10786        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10787        if (packageName.equals(activeLauncherPackageName)) {
10788            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10789                    + "\" because it is set as the active launcher");
10790            return false;
10791        }
10792
10793        final PackageParser.Package pkg = mPackages.get(packageName);
10794        if (pkg != null && isPrivilegedApp(pkg)) {
10795            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10796                    + "\" because it is a privileged app");
10797            return false;
10798        }
10799
10800        return true;
10801    }
10802
10803    private String getActiveLauncherPackageName(int userId) {
10804        Intent intent = new Intent(Intent.ACTION_MAIN);
10805        intent.addCategory(Intent.CATEGORY_HOME);
10806        ResolveInfo resolveInfo = resolveIntent(
10807                intent,
10808                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10809                PackageManager.MATCH_DEFAULT_ONLY,
10810                userId);
10811
10812        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10813    }
10814
10815    @Override
10816    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10817        mContext.enforceCallingOrSelfPermission(
10818                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10819                "Only package verification agents can verify applications");
10820
10821        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10822        final PackageVerificationResponse response = new PackageVerificationResponse(
10823                verificationCode, Binder.getCallingUid());
10824        msg.arg1 = id;
10825        msg.obj = response;
10826        mHandler.sendMessage(msg);
10827    }
10828
10829    @Override
10830    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10831            long millisecondsToDelay) {
10832        mContext.enforceCallingOrSelfPermission(
10833                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10834                "Only package verification agents can extend verification timeouts");
10835
10836        final PackageVerificationState state = mPendingVerification.get(id);
10837        final PackageVerificationResponse response = new PackageVerificationResponse(
10838                verificationCodeAtTimeout, Binder.getCallingUid());
10839
10840        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10841            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10842        }
10843        if (millisecondsToDelay < 0) {
10844            millisecondsToDelay = 0;
10845        }
10846        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10847                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10848            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10849        }
10850
10851        if ((state != null) && !state.timeoutExtended()) {
10852            state.extendTimeout();
10853
10854            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10855            msg.arg1 = id;
10856            msg.obj = response;
10857            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10858        }
10859    }
10860
10861    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10862            int verificationCode, UserHandle user) {
10863        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10864        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10865        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10866        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10867        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10868
10869        mContext.sendBroadcastAsUser(intent, user,
10870                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10871    }
10872
10873    private ComponentName matchComponentForVerifier(String packageName,
10874            List<ResolveInfo> receivers) {
10875        ActivityInfo targetReceiver = null;
10876
10877        final int NR = receivers.size();
10878        for (int i = 0; i < NR; i++) {
10879            final ResolveInfo info = receivers.get(i);
10880            if (info.activityInfo == null) {
10881                continue;
10882            }
10883
10884            if (packageName.equals(info.activityInfo.packageName)) {
10885                targetReceiver = info.activityInfo;
10886                break;
10887            }
10888        }
10889
10890        if (targetReceiver == null) {
10891            return null;
10892        }
10893
10894        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10895    }
10896
10897    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10898            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10899        if (pkgInfo.verifiers.length == 0) {
10900            return null;
10901        }
10902
10903        final int N = pkgInfo.verifiers.length;
10904        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10905        for (int i = 0; i < N; i++) {
10906            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10907
10908            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10909                    receivers);
10910            if (comp == null) {
10911                continue;
10912            }
10913
10914            final int verifierUid = getUidForVerifier(verifierInfo);
10915            if (verifierUid == -1) {
10916                continue;
10917            }
10918
10919            if (DEBUG_VERIFY) {
10920                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10921                        + " with the correct signature");
10922            }
10923            sufficientVerifiers.add(comp);
10924            verificationState.addSufficientVerifier(verifierUid);
10925        }
10926
10927        return sufficientVerifiers;
10928    }
10929
10930    private int getUidForVerifier(VerifierInfo verifierInfo) {
10931        synchronized (mPackages) {
10932            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10933            if (pkg == null) {
10934                return -1;
10935            } else if (pkg.mSignatures.length != 1) {
10936                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10937                        + " has more than one signature; ignoring");
10938                return -1;
10939            }
10940
10941            /*
10942             * If the public key of the package's signature does not match
10943             * our expected public key, then this is a different package and
10944             * we should skip.
10945             */
10946
10947            final byte[] expectedPublicKey;
10948            try {
10949                final Signature verifierSig = pkg.mSignatures[0];
10950                final PublicKey publicKey = verifierSig.getPublicKey();
10951                expectedPublicKey = publicKey.getEncoded();
10952            } catch (CertificateException e) {
10953                return -1;
10954            }
10955
10956            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10957
10958            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10959                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10960                        + " does not have the expected public key; ignoring");
10961                return -1;
10962            }
10963
10964            return pkg.applicationInfo.uid;
10965        }
10966    }
10967
10968    @Override
10969    public void finishPackageInstall(int token) {
10970        enforceSystemOrRoot("Only the system is allowed to finish installs");
10971
10972        if (DEBUG_INSTALL) {
10973            Slog.v(TAG, "BM finishing package install for " + token);
10974        }
10975        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10976
10977        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10978        mHandler.sendMessage(msg);
10979    }
10980
10981    /**
10982     * Get the verification agent timeout.
10983     *
10984     * @return verification timeout in milliseconds
10985     */
10986    private long getVerificationTimeout() {
10987        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10988                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10989                DEFAULT_VERIFICATION_TIMEOUT);
10990    }
10991
10992    /**
10993     * Get the default verification agent response code.
10994     *
10995     * @return default verification response code
10996     */
10997    private int getDefaultVerificationResponse() {
10998        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10999                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11000                DEFAULT_VERIFICATION_RESPONSE);
11001    }
11002
11003    /**
11004     * Check whether or not package verification has been enabled.
11005     *
11006     * @return true if verification should be performed
11007     */
11008    private boolean isVerificationEnabled(int userId, int installFlags) {
11009        if (!DEFAULT_VERIFY_ENABLE) {
11010            return false;
11011        }
11012        // Ephemeral apps don't get the full verification treatment
11013        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11014            if (DEBUG_EPHEMERAL) {
11015                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11016            }
11017            return false;
11018        }
11019
11020        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11021
11022        // Check if installing from ADB
11023        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11024            // Do not run verification in a test harness environment
11025            if (ActivityManager.isRunningInTestHarness()) {
11026                return false;
11027            }
11028            if (ensureVerifyAppsEnabled) {
11029                return true;
11030            }
11031            // Check if the developer does not want package verification for ADB installs
11032            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11033                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11034                return false;
11035            }
11036        }
11037
11038        if (ensureVerifyAppsEnabled) {
11039            return true;
11040        }
11041
11042        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11043                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11044    }
11045
11046    @Override
11047    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11048            throws RemoteException {
11049        mContext.enforceCallingOrSelfPermission(
11050                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11051                "Only intentfilter verification agents can verify applications");
11052
11053        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11054        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11055                Binder.getCallingUid(), verificationCode, failedDomains);
11056        msg.arg1 = id;
11057        msg.obj = response;
11058        mHandler.sendMessage(msg);
11059    }
11060
11061    @Override
11062    public int getIntentVerificationStatus(String packageName, int userId) {
11063        synchronized (mPackages) {
11064            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11065        }
11066    }
11067
11068    @Override
11069    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11070        mContext.enforceCallingOrSelfPermission(
11071                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11072
11073        boolean result = false;
11074        synchronized (mPackages) {
11075            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11076        }
11077        if (result) {
11078            scheduleWritePackageRestrictionsLocked(userId);
11079        }
11080        return result;
11081    }
11082
11083    @Override
11084    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11085        synchronized (mPackages) {
11086            return mSettings.getIntentFilterVerificationsLPr(packageName);
11087        }
11088    }
11089
11090    @Override
11091    public List<IntentFilter> getAllIntentFilters(String packageName) {
11092        if (TextUtils.isEmpty(packageName)) {
11093            return Collections.<IntentFilter>emptyList();
11094        }
11095        synchronized (mPackages) {
11096            PackageParser.Package pkg = mPackages.get(packageName);
11097            if (pkg == null || pkg.activities == null) {
11098                return Collections.<IntentFilter>emptyList();
11099            }
11100            final int count = pkg.activities.size();
11101            ArrayList<IntentFilter> result = new ArrayList<>();
11102            for (int n=0; n<count; n++) {
11103                PackageParser.Activity activity = pkg.activities.get(n);
11104                if (activity.intents != null && activity.intents.size() > 0) {
11105                    result.addAll(activity.intents);
11106                }
11107            }
11108            return result;
11109        }
11110    }
11111
11112    @Override
11113    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11114        mContext.enforceCallingOrSelfPermission(
11115                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11116
11117        synchronized (mPackages) {
11118            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11119            if (packageName != null) {
11120                result |= updateIntentVerificationStatus(packageName,
11121                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11122                        userId);
11123                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11124                        packageName, userId);
11125            }
11126            return result;
11127        }
11128    }
11129
11130    @Override
11131    public String getDefaultBrowserPackageName(int userId) {
11132        synchronized (mPackages) {
11133            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11134        }
11135    }
11136
11137    /**
11138     * Get the "allow unknown sources" setting.
11139     *
11140     * @return the current "allow unknown sources" setting
11141     */
11142    private int getUnknownSourcesSettings() {
11143        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11144                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11145                -1);
11146    }
11147
11148    @Override
11149    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11150        final int uid = Binder.getCallingUid();
11151        // writer
11152        synchronized (mPackages) {
11153            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11154            if (targetPackageSetting == null) {
11155                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11156            }
11157
11158            PackageSetting installerPackageSetting;
11159            if (installerPackageName != null) {
11160                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11161                if (installerPackageSetting == null) {
11162                    throw new IllegalArgumentException("Unknown installer package: "
11163                            + installerPackageName);
11164                }
11165            } else {
11166                installerPackageSetting = null;
11167            }
11168
11169            Signature[] callerSignature;
11170            Object obj = mSettings.getUserIdLPr(uid);
11171            if (obj != null) {
11172                if (obj instanceof SharedUserSetting) {
11173                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11174                } else if (obj instanceof PackageSetting) {
11175                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11176                } else {
11177                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11178                }
11179            } else {
11180                throw new SecurityException("Unknown calling UID: " + uid);
11181            }
11182
11183            // Verify: can't set installerPackageName to a package that is
11184            // not signed with the same cert as the caller.
11185            if (installerPackageSetting != null) {
11186                if (compareSignatures(callerSignature,
11187                        installerPackageSetting.signatures.mSignatures)
11188                        != PackageManager.SIGNATURE_MATCH) {
11189                    throw new SecurityException(
11190                            "Caller does not have same cert as new installer package "
11191                            + installerPackageName);
11192                }
11193            }
11194
11195            // Verify: if target already has an installer package, it must
11196            // be signed with the same cert as the caller.
11197            if (targetPackageSetting.installerPackageName != null) {
11198                PackageSetting setting = mSettings.mPackages.get(
11199                        targetPackageSetting.installerPackageName);
11200                // If the currently set package isn't valid, then it's always
11201                // okay to change it.
11202                if (setting != null) {
11203                    if (compareSignatures(callerSignature,
11204                            setting.signatures.mSignatures)
11205                            != PackageManager.SIGNATURE_MATCH) {
11206                        throw new SecurityException(
11207                                "Caller does not have same cert as old installer package "
11208                                + targetPackageSetting.installerPackageName);
11209                    }
11210                }
11211            }
11212
11213            // Okay!
11214            targetPackageSetting.installerPackageName = installerPackageName;
11215            scheduleWriteSettingsLocked();
11216        }
11217    }
11218
11219    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11220        // Queue up an async operation since the package installation may take a little while.
11221        mHandler.post(new Runnable() {
11222            public void run() {
11223                mHandler.removeCallbacks(this);
11224                 // Result object to be returned
11225                PackageInstalledInfo res = new PackageInstalledInfo();
11226                res.setReturnCode(currentStatus);
11227                res.uid = -1;
11228                res.pkg = null;
11229                res.removedInfo = null;
11230                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11231                    args.doPreInstall(res.returnCode);
11232                    synchronized (mInstallLock) {
11233                        installPackageTracedLI(args, res);
11234                    }
11235                    args.doPostInstall(res.returnCode, res.uid);
11236                }
11237
11238                // A restore should be performed at this point if (a) the install
11239                // succeeded, (b) the operation is not an update, and (c) the new
11240                // package has not opted out of backup participation.
11241                final boolean update = res.removedInfo != null
11242                        && res.removedInfo.removedPackage != null;
11243                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11244                boolean doRestore = !update
11245                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11246
11247                // Set up the post-install work request bookkeeping.  This will be used
11248                // and cleaned up by the post-install event handling regardless of whether
11249                // there's a restore pass performed.  Token values are >= 1.
11250                int token;
11251                if (mNextInstallToken < 0) mNextInstallToken = 1;
11252                token = mNextInstallToken++;
11253
11254                PostInstallData data = new PostInstallData(args, res);
11255                mRunningInstalls.put(token, data);
11256                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11257
11258                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11259                    // Pass responsibility to the Backup Manager.  It will perform a
11260                    // restore if appropriate, then pass responsibility back to the
11261                    // Package Manager to run the post-install observer callbacks
11262                    // and broadcasts.
11263                    IBackupManager bm = IBackupManager.Stub.asInterface(
11264                            ServiceManager.getService(Context.BACKUP_SERVICE));
11265                    if (bm != null) {
11266                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11267                                + " to BM for possible restore");
11268                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11269                        try {
11270                            // TODO: http://b/22388012
11271                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11272                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11273                            } else {
11274                                doRestore = false;
11275                            }
11276                        } catch (RemoteException e) {
11277                            // can't happen; the backup manager is local
11278                        } catch (Exception e) {
11279                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11280                            doRestore = false;
11281                        }
11282                    } else {
11283                        Slog.e(TAG, "Backup Manager not found!");
11284                        doRestore = false;
11285                    }
11286                }
11287
11288                if (!doRestore) {
11289                    // No restore possible, or the Backup Manager was mysteriously not
11290                    // available -- just fire the post-install work request directly.
11291                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11292
11293                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11294
11295                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11296                    mHandler.sendMessage(msg);
11297                }
11298            }
11299        });
11300    }
11301
11302    private abstract class HandlerParams {
11303        private static final int MAX_RETRIES = 4;
11304
11305        /**
11306         * Number of times startCopy() has been attempted and had a non-fatal
11307         * error.
11308         */
11309        private int mRetries = 0;
11310
11311        /** User handle for the user requesting the information or installation. */
11312        private final UserHandle mUser;
11313        String traceMethod;
11314        int traceCookie;
11315
11316        HandlerParams(UserHandle user) {
11317            mUser = user;
11318        }
11319
11320        UserHandle getUser() {
11321            return mUser;
11322        }
11323
11324        HandlerParams setTraceMethod(String traceMethod) {
11325            this.traceMethod = traceMethod;
11326            return this;
11327        }
11328
11329        HandlerParams setTraceCookie(int traceCookie) {
11330            this.traceCookie = traceCookie;
11331            return this;
11332        }
11333
11334        final boolean startCopy() {
11335            boolean res;
11336            try {
11337                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11338
11339                if (++mRetries > MAX_RETRIES) {
11340                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11341                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11342                    handleServiceError();
11343                    return false;
11344                } else {
11345                    handleStartCopy();
11346                    res = true;
11347                }
11348            } catch (RemoteException e) {
11349                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11350                mHandler.sendEmptyMessage(MCS_RECONNECT);
11351                res = false;
11352            }
11353            handleReturnCode();
11354            return res;
11355        }
11356
11357        final void serviceError() {
11358            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11359            handleServiceError();
11360            handleReturnCode();
11361        }
11362
11363        abstract void handleStartCopy() throws RemoteException;
11364        abstract void handleServiceError();
11365        abstract void handleReturnCode();
11366    }
11367
11368    class MeasureParams extends HandlerParams {
11369        private final PackageStats mStats;
11370        private boolean mSuccess;
11371
11372        private final IPackageStatsObserver mObserver;
11373
11374        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11375            super(new UserHandle(stats.userHandle));
11376            mObserver = observer;
11377            mStats = stats;
11378        }
11379
11380        @Override
11381        public String toString() {
11382            return "MeasureParams{"
11383                + Integer.toHexString(System.identityHashCode(this))
11384                + " " + mStats.packageName + "}";
11385        }
11386
11387        @Override
11388        void handleStartCopy() throws RemoteException {
11389            synchronized (mInstallLock) {
11390                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11391            }
11392
11393            if (mSuccess) {
11394                final boolean mounted;
11395                if (Environment.isExternalStorageEmulated()) {
11396                    mounted = true;
11397                } else {
11398                    final String status = Environment.getExternalStorageState();
11399                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11400                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11401                }
11402
11403                if (mounted) {
11404                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11405
11406                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11407                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11408
11409                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11410                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11411
11412                    // Always subtract cache size, since it's a subdirectory
11413                    mStats.externalDataSize -= mStats.externalCacheSize;
11414
11415                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11416                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11417
11418                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11419                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11420                }
11421            }
11422        }
11423
11424        @Override
11425        void handleReturnCode() {
11426            if (mObserver != null) {
11427                try {
11428                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11429                } catch (RemoteException e) {
11430                    Slog.i(TAG, "Observer no longer exists.");
11431                }
11432            }
11433        }
11434
11435        @Override
11436        void handleServiceError() {
11437            Slog.e(TAG, "Could not measure application " + mStats.packageName
11438                            + " external storage");
11439        }
11440    }
11441
11442    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11443            throws RemoteException {
11444        long result = 0;
11445        for (File path : paths) {
11446            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11447        }
11448        return result;
11449    }
11450
11451    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11452        for (File path : paths) {
11453            try {
11454                mcs.clearDirectory(path.getAbsolutePath());
11455            } catch (RemoteException e) {
11456            }
11457        }
11458    }
11459
11460    static class OriginInfo {
11461        /**
11462         * Location where install is coming from, before it has been
11463         * copied/renamed into place. This could be a single monolithic APK
11464         * file, or a cluster directory. This location may be untrusted.
11465         */
11466        final File file;
11467        final String cid;
11468
11469        /**
11470         * Flag indicating that {@link #file} or {@link #cid} has already been
11471         * staged, meaning downstream users don't need to defensively copy the
11472         * contents.
11473         */
11474        final boolean staged;
11475
11476        /**
11477         * Flag indicating that {@link #file} or {@link #cid} is an already
11478         * installed app that is being moved.
11479         */
11480        final boolean existing;
11481
11482        final String resolvedPath;
11483        final File resolvedFile;
11484
11485        static OriginInfo fromNothing() {
11486            return new OriginInfo(null, null, false, false);
11487        }
11488
11489        static OriginInfo fromUntrustedFile(File file) {
11490            return new OriginInfo(file, null, false, false);
11491        }
11492
11493        static OriginInfo fromExistingFile(File file) {
11494            return new OriginInfo(file, null, false, true);
11495        }
11496
11497        static OriginInfo fromStagedFile(File file) {
11498            return new OriginInfo(file, null, true, false);
11499        }
11500
11501        static OriginInfo fromStagedContainer(String cid) {
11502            return new OriginInfo(null, cid, true, false);
11503        }
11504
11505        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11506            this.file = file;
11507            this.cid = cid;
11508            this.staged = staged;
11509            this.existing = existing;
11510
11511            if (cid != null) {
11512                resolvedPath = PackageHelper.getSdDir(cid);
11513                resolvedFile = new File(resolvedPath);
11514            } else if (file != null) {
11515                resolvedPath = file.getAbsolutePath();
11516                resolvedFile = file;
11517            } else {
11518                resolvedPath = null;
11519                resolvedFile = null;
11520            }
11521        }
11522    }
11523
11524    static class MoveInfo {
11525        final int moveId;
11526        final String fromUuid;
11527        final String toUuid;
11528        final String packageName;
11529        final String dataAppName;
11530        final int appId;
11531        final String seinfo;
11532        final int targetSdkVersion;
11533
11534        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11535                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11536            this.moveId = moveId;
11537            this.fromUuid = fromUuid;
11538            this.toUuid = toUuid;
11539            this.packageName = packageName;
11540            this.dataAppName = dataAppName;
11541            this.appId = appId;
11542            this.seinfo = seinfo;
11543            this.targetSdkVersion = targetSdkVersion;
11544        }
11545    }
11546
11547    static class VerificationInfo {
11548        /** A constant used to indicate that a uid value is not present. */
11549        public static final int NO_UID = -1;
11550
11551        /** URI referencing where the package was downloaded from. */
11552        final Uri originatingUri;
11553
11554        /** HTTP referrer URI associated with the originatingURI. */
11555        final Uri referrer;
11556
11557        /** UID of the application that the install request originated from. */
11558        final int originatingUid;
11559
11560        /** UID of application requesting the install */
11561        final int installerUid;
11562
11563        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11564            this.originatingUri = originatingUri;
11565            this.referrer = referrer;
11566            this.originatingUid = originatingUid;
11567            this.installerUid = installerUid;
11568        }
11569    }
11570
11571    class InstallParams extends HandlerParams {
11572        final OriginInfo origin;
11573        final MoveInfo move;
11574        final IPackageInstallObserver2 observer;
11575        int installFlags;
11576        final String installerPackageName;
11577        final String volumeUuid;
11578        private InstallArgs mArgs;
11579        private int mRet;
11580        final String packageAbiOverride;
11581        final String[] grantedRuntimePermissions;
11582        final VerificationInfo verificationInfo;
11583
11584        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11585                int installFlags, String installerPackageName, String volumeUuid,
11586                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11587                String[] grantedPermissions) {
11588            super(user);
11589            this.origin = origin;
11590            this.move = move;
11591            this.observer = observer;
11592            this.installFlags = installFlags;
11593            this.installerPackageName = installerPackageName;
11594            this.volumeUuid = volumeUuid;
11595            this.verificationInfo = verificationInfo;
11596            this.packageAbiOverride = packageAbiOverride;
11597            this.grantedRuntimePermissions = grantedPermissions;
11598        }
11599
11600        @Override
11601        public String toString() {
11602            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11603                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11604        }
11605
11606        private int installLocationPolicy(PackageInfoLite pkgLite) {
11607            String packageName = pkgLite.packageName;
11608            int installLocation = pkgLite.installLocation;
11609            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11610            // reader
11611            synchronized (mPackages) {
11612                // Currently installed package which the new package is attempting to replace or
11613                // null if no such package is installed.
11614                PackageParser.Package installedPkg = mPackages.get(packageName);
11615                // Package which currently owns the data which the new package will own if installed.
11616                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11617                // will be null whereas dataOwnerPkg will contain information about the package
11618                // which was uninstalled while keeping its data.
11619                PackageParser.Package dataOwnerPkg = installedPkg;
11620                if (dataOwnerPkg  == null) {
11621                    PackageSetting ps = mSettings.mPackages.get(packageName);
11622                    if (ps != null) {
11623                        dataOwnerPkg = ps.pkg;
11624                    }
11625                }
11626
11627                if (dataOwnerPkg != null) {
11628                    // If installed, the package will get access to data left on the device by its
11629                    // predecessor. As a security measure, this is permited only if this is not a
11630                    // version downgrade or if the predecessor package is marked as debuggable and
11631                    // a downgrade is explicitly requested.
11632                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11633                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11634                        try {
11635                            checkDowngrade(dataOwnerPkg, pkgLite);
11636                        } catch (PackageManagerException e) {
11637                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11638                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11639                        }
11640                    }
11641                }
11642
11643                if (installedPkg != null) {
11644                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11645                        // Check for updated system application.
11646                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11647                            if (onSd) {
11648                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11649                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11650                            }
11651                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11652                        } else {
11653                            if (onSd) {
11654                                // Install flag overrides everything.
11655                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11656                            }
11657                            // If current upgrade specifies particular preference
11658                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11659                                // Application explicitly specified internal.
11660                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11661                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11662                                // App explictly prefers external. Let policy decide
11663                            } else {
11664                                // Prefer previous location
11665                                if (isExternal(installedPkg)) {
11666                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11667                                }
11668                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11669                            }
11670                        }
11671                    } else {
11672                        // Invalid install. Return error code
11673                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11674                    }
11675                }
11676            }
11677            // All the special cases have been taken care of.
11678            // Return result based on recommended install location.
11679            if (onSd) {
11680                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11681            }
11682            return pkgLite.recommendedInstallLocation;
11683        }
11684
11685        /*
11686         * Invoke remote method to get package information and install
11687         * location values. Override install location based on default
11688         * policy if needed and then create install arguments based
11689         * on the install location.
11690         */
11691        public void handleStartCopy() throws RemoteException {
11692            int ret = PackageManager.INSTALL_SUCCEEDED;
11693
11694            // If we're already staged, we've firmly committed to an install location
11695            if (origin.staged) {
11696                if (origin.file != null) {
11697                    installFlags |= PackageManager.INSTALL_INTERNAL;
11698                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11699                } else if (origin.cid != null) {
11700                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11701                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11702                } else {
11703                    throw new IllegalStateException("Invalid stage location");
11704                }
11705            }
11706
11707            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11708            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11709            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11710            PackageInfoLite pkgLite = null;
11711
11712            if (onInt && onSd) {
11713                // Check if both bits are set.
11714                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11715                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11716            } else if (onSd && ephemeral) {
11717                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11718                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11719            } else {
11720                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11721                        packageAbiOverride);
11722
11723                if (DEBUG_EPHEMERAL && ephemeral) {
11724                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11725                }
11726
11727                /*
11728                 * If we have too little free space, try to free cache
11729                 * before giving up.
11730                 */
11731                if (!origin.staged && pkgLite.recommendedInstallLocation
11732                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11733                    // TODO: focus freeing disk space on the target device
11734                    final StorageManager storage = StorageManager.from(mContext);
11735                    final long lowThreshold = storage.getStorageLowBytes(
11736                            Environment.getDataDirectory());
11737
11738                    final long sizeBytes = mContainerService.calculateInstalledSize(
11739                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11740
11741                    try {
11742                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11743                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11744                                installFlags, packageAbiOverride);
11745                    } catch (InstallerException e) {
11746                        Slog.w(TAG, "Failed to free cache", e);
11747                    }
11748
11749                    /*
11750                     * The cache free must have deleted the file we
11751                     * downloaded to install.
11752                     *
11753                     * TODO: fix the "freeCache" call to not delete
11754                     *       the file we care about.
11755                     */
11756                    if (pkgLite.recommendedInstallLocation
11757                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11758                        pkgLite.recommendedInstallLocation
11759                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11760                    }
11761                }
11762            }
11763
11764            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11765                int loc = pkgLite.recommendedInstallLocation;
11766                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11767                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11768                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11769                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11770                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11771                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11772                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11773                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11774                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11775                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11776                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11777                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11778                } else {
11779                    // Override with defaults if needed.
11780                    loc = installLocationPolicy(pkgLite);
11781                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11782                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11783                    } else if (!onSd && !onInt) {
11784                        // Override install location with flags
11785                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11786                            // Set the flag to install on external media.
11787                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11788                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11789                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11790                            if (DEBUG_EPHEMERAL) {
11791                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11792                            }
11793                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11794                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11795                                    |PackageManager.INSTALL_INTERNAL);
11796                        } else {
11797                            // Make sure the flag for installing on external
11798                            // media is unset
11799                            installFlags |= PackageManager.INSTALL_INTERNAL;
11800                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11801                        }
11802                    }
11803                }
11804            }
11805
11806            final InstallArgs args = createInstallArgs(this);
11807            mArgs = args;
11808
11809            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11810                // TODO: http://b/22976637
11811                // Apps installed for "all" users use the device owner to verify the app
11812                UserHandle verifierUser = getUser();
11813                if (verifierUser == UserHandle.ALL) {
11814                    verifierUser = UserHandle.SYSTEM;
11815                }
11816
11817                /*
11818                 * Determine if we have any installed package verifiers. If we
11819                 * do, then we'll defer to them to verify the packages.
11820                 */
11821                final int requiredUid = mRequiredVerifierPackage == null ? -1
11822                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11823                                verifierUser.getIdentifier());
11824                if (!origin.existing && requiredUid != -1
11825                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11826                    final Intent verification = new Intent(
11827                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11828                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11829                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11830                            PACKAGE_MIME_TYPE);
11831                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11832
11833                    // Query all live verifiers based on current user state
11834                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11835                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11836
11837                    if (DEBUG_VERIFY) {
11838                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11839                                + verification.toString() + " with " + pkgLite.verifiers.length
11840                                + " optional verifiers");
11841                    }
11842
11843                    final int verificationId = mPendingVerificationToken++;
11844
11845                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11846
11847                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11848                            installerPackageName);
11849
11850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11851                            installFlags);
11852
11853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11854                            pkgLite.packageName);
11855
11856                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11857                            pkgLite.versionCode);
11858
11859                    if (verificationInfo != null) {
11860                        if (verificationInfo.originatingUri != null) {
11861                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11862                                    verificationInfo.originatingUri);
11863                        }
11864                        if (verificationInfo.referrer != null) {
11865                            verification.putExtra(Intent.EXTRA_REFERRER,
11866                                    verificationInfo.referrer);
11867                        }
11868                        if (verificationInfo.originatingUid >= 0) {
11869                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11870                                    verificationInfo.originatingUid);
11871                        }
11872                        if (verificationInfo.installerUid >= 0) {
11873                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11874                                    verificationInfo.installerUid);
11875                        }
11876                    }
11877
11878                    final PackageVerificationState verificationState = new PackageVerificationState(
11879                            requiredUid, args);
11880
11881                    mPendingVerification.append(verificationId, verificationState);
11882
11883                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11884                            receivers, verificationState);
11885
11886                    /*
11887                     * If any sufficient verifiers were listed in the package
11888                     * manifest, attempt to ask them.
11889                     */
11890                    if (sufficientVerifiers != null) {
11891                        final int N = sufficientVerifiers.size();
11892                        if (N == 0) {
11893                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11894                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11895                        } else {
11896                            for (int i = 0; i < N; i++) {
11897                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11898
11899                                final Intent sufficientIntent = new Intent(verification);
11900                                sufficientIntent.setComponent(verifierComponent);
11901                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11902                            }
11903                        }
11904                    }
11905
11906                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11907                            mRequiredVerifierPackage, receivers);
11908                    if (ret == PackageManager.INSTALL_SUCCEEDED
11909                            && mRequiredVerifierPackage != null) {
11910                        Trace.asyncTraceBegin(
11911                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11912                        /*
11913                         * Send the intent to the required verification agent,
11914                         * but only start the verification timeout after the
11915                         * target BroadcastReceivers have run.
11916                         */
11917                        verification.setComponent(requiredVerifierComponent);
11918                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11919                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11920                                new BroadcastReceiver() {
11921                                    @Override
11922                                    public void onReceive(Context context, Intent intent) {
11923                                        final Message msg = mHandler
11924                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11925                                        msg.arg1 = verificationId;
11926                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11927                                    }
11928                                }, null, 0, null, null);
11929
11930                        /*
11931                         * We don't want the copy to proceed until verification
11932                         * succeeds, so null out this field.
11933                         */
11934                        mArgs = null;
11935                    }
11936                } else {
11937                    /*
11938                     * No package verification is enabled, so immediately start
11939                     * the remote call to initiate copy using temporary file.
11940                     */
11941                    ret = args.copyApk(mContainerService, true);
11942                }
11943            }
11944
11945            mRet = ret;
11946        }
11947
11948        @Override
11949        void handleReturnCode() {
11950            // If mArgs is null, then MCS couldn't be reached. When it
11951            // reconnects, it will try again to install. At that point, this
11952            // will succeed.
11953            if (mArgs != null) {
11954                processPendingInstall(mArgs, mRet);
11955            }
11956        }
11957
11958        @Override
11959        void handleServiceError() {
11960            mArgs = createInstallArgs(this);
11961            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11962        }
11963
11964        public boolean isForwardLocked() {
11965            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11966        }
11967    }
11968
11969    /**
11970     * Used during creation of InstallArgs
11971     *
11972     * @param installFlags package installation flags
11973     * @return true if should be installed on external storage
11974     */
11975    private static boolean installOnExternalAsec(int installFlags) {
11976        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11977            return false;
11978        }
11979        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11980            return true;
11981        }
11982        return false;
11983    }
11984
11985    /**
11986     * Used during creation of InstallArgs
11987     *
11988     * @param installFlags package installation flags
11989     * @return true if should be installed as forward locked
11990     */
11991    private static boolean installForwardLocked(int installFlags) {
11992        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11993    }
11994
11995    private InstallArgs createInstallArgs(InstallParams params) {
11996        if (params.move != null) {
11997            return new MoveInstallArgs(params);
11998        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11999            return new AsecInstallArgs(params);
12000        } else {
12001            return new FileInstallArgs(params);
12002        }
12003    }
12004
12005    /**
12006     * Create args that describe an existing installed package. Typically used
12007     * when cleaning up old installs, or used as a move source.
12008     */
12009    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12010            String resourcePath, String[] instructionSets) {
12011        final boolean isInAsec;
12012        if (installOnExternalAsec(installFlags)) {
12013            /* Apps on SD card are always in ASEC containers. */
12014            isInAsec = true;
12015        } else if (installForwardLocked(installFlags)
12016                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12017            /*
12018             * Forward-locked apps are only in ASEC containers if they're the
12019             * new style
12020             */
12021            isInAsec = true;
12022        } else {
12023            isInAsec = false;
12024        }
12025
12026        if (isInAsec) {
12027            return new AsecInstallArgs(codePath, instructionSets,
12028                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12029        } else {
12030            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12031        }
12032    }
12033
12034    static abstract class InstallArgs {
12035        /** @see InstallParams#origin */
12036        final OriginInfo origin;
12037        /** @see InstallParams#move */
12038        final MoveInfo move;
12039
12040        final IPackageInstallObserver2 observer;
12041        // Always refers to PackageManager flags only
12042        final int installFlags;
12043        final String installerPackageName;
12044        final String volumeUuid;
12045        final UserHandle user;
12046        final String abiOverride;
12047        final String[] installGrantPermissions;
12048        /** If non-null, drop an async trace when the install completes */
12049        final String traceMethod;
12050        final int traceCookie;
12051
12052        // The list of instruction sets supported by this app. This is currently
12053        // only used during the rmdex() phase to clean up resources. We can get rid of this
12054        // if we move dex files under the common app path.
12055        /* nullable */ String[] instructionSets;
12056
12057        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12058                int installFlags, String installerPackageName, String volumeUuid,
12059                UserHandle user, String[] instructionSets,
12060                String abiOverride, String[] installGrantPermissions,
12061                String traceMethod, int traceCookie) {
12062            this.origin = origin;
12063            this.move = move;
12064            this.installFlags = installFlags;
12065            this.observer = observer;
12066            this.installerPackageName = installerPackageName;
12067            this.volumeUuid = volumeUuid;
12068            this.user = user;
12069            this.instructionSets = instructionSets;
12070            this.abiOverride = abiOverride;
12071            this.installGrantPermissions = installGrantPermissions;
12072            this.traceMethod = traceMethod;
12073            this.traceCookie = traceCookie;
12074        }
12075
12076        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12077        abstract int doPreInstall(int status);
12078
12079        /**
12080         * Rename package into final resting place. All paths on the given
12081         * scanned package should be updated to reflect the rename.
12082         */
12083        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12084        abstract int doPostInstall(int status, int uid);
12085
12086        /** @see PackageSettingBase#codePathString */
12087        abstract String getCodePath();
12088        /** @see PackageSettingBase#resourcePathString */
12089        abstract String getResourcePath();
12090
12091        // Need installer lock especially for dex file removal.
12092        abstract void cleanUpResourcesLI();
12093        abstract boolean doPostDeleteLI(boolean delete);
12094
12095        /**
12096         * Called before the source arguments are copied. This is used mostly
12097         * for MoveParams when it needs to read the source file to put it in the
12098         * destination.
12099         */
12100        int doPreCopy() {
12101            return PackageManager.INSTALL_SUCCEEDED;
12102        }
12103
12104        /**
12105         * Called after the source arguments are copied. This is used mostly for
12106         * MoveParams when it needs to read the source file to put it in the
12107         * destination.
12108         *
12109         * @return
12110         */
12111        int doPostCopy(int uid) {
12112            return PackageManager.INSTALL_SUCCEEDED;
12113        }
12114
12115        protected boolean isFwdLocked() {
12116            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12117        }
12118
12119        protected boolean isExternalAsec() {
12120            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12121        }
12122
12123        protected boolean isEphemeral() {
12124            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12125        }
12126
12127        UserHandle getUser() {
12128            return user;
12129        }
12130    }
12131
12132    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12133        if (!allCodePaths.isEmpty()) {
12134            if (instructionSets == null) {
12135                throw new IllegalStateException("instructionSet == null");
12136            }
12137            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12138            for (String codePath : allCodePaths) {
12139                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12140                    try {
12141                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12142                    } catch (InstallerException ignored) {
12143                    }
12144                }
12145            }
12146        }
12147    }
12148
12149    /**
12150     * Logic to handle installation of non-ASEC applications, including copying
12151     * and renaming logic.
12152     */
12153    class FileInstallArgs extends InstallArgs {
12154        private File codeFile;
12155        private File resourceFile;
12156
12157        // Example topology:
12158        // /data/app/com.example/base.apk
12159        // /data/app/com.example/split_foo.apk
12160        // /data/app/com.example/lib/arm/libfoo.so
12161        // /data/app/com.example/lib/arm64/libfoo.so
12162        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12163
12164        /** New install */
12165        FileInstallArgs(InstallParams params) {
12166            super(params.origin, params.move, params.observer, params.installFlags,
12167                    params.installerPackageName, params.volumeUuid,
12168                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12169                    params.grantedRuntimePermissions,
12170                    params.traceMethod, params.traceCookie);
12171            if (isFwdLocked()) {
12172                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12173            }
12174        }
12175
12176        /** Existing install */
12177        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12178            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12179                    null, null, null, 0);
12180            this.codeFile = (codePath != null) ? new File(codePath) : null;
12181            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12182        }
12183
12184        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12185            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12186            try {
12187                return doCopyApk(imcs, temp);
12188            } finally {
12189                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12190            }
12191        }
12192
12193        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12194            if (origin.staged) {
12195                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12196                codeFile = origin.file;
12197                resourceFile = origin.file;
12198                return PackageManager.INSTALL_SUCCEEDED;
12199            }
12200
12201            try {
12202                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12203                final File tempDir =
12204                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12205                codeFile = tempDir;
12206                resourceFile = tempDir;
12207            } catch (IOException e) {
12208                Slog.w(TAG, "Failed to create copy file: " + e);
12209                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12210            }
12211
12212            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12213                @Override
12214                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12215                    if (!FileUtils.isValidExtFilename(name)) {
12216                        throw new IllegalArgumentException("Invalid filename: " + name);
12217                    }
12218                    try {
12219                        final File file = new File(codeFile, name);
12220                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12221                                O_RDWR | O_CREAT, 0644);
12222                        Os.chmod(file.getAbsolutePath(), 0644);
12223                        return new ParcelFileDescriptor(fd);
12224                    } catch (ErrnoException e) {
12225                        throw new RemoteException("Failed to open: " + e.getMessage());
12226                    }
12227                }
12228            };
12229
12230            int ret = PackageManager.INSTALL_SUCCEEDED;
12231            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12232            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12233                Slog.e(TAG, "Failed to copy package");
12234                return ret;
12235            }
12236
12237            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12238            NativeLibraryHelper.Handle handle = null;
12239            try {
12240                handle = NativeLibraryHelper.Handle.create(codeFile);
12241                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12242                        abiOverride);
12243            } catch (IOException e) {
12244                Slog.e(TAG, "Copying native libraries failed", e);
12245                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12246            } finally {
12247                IoUtils.closeQuietly(handle);
12248            }
12249
12250            return ret;
12251        }
12252
12253        int doPreInstall(int status) {
12254            if (status != PackageManager.INSTALL_SUCCEEDED) {
12255                cleanUp();
12256            }
12257            return status;
12258        }
12259
12260        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12261            if (status != PackageManager.INSTALL_SUCCEEDED) {
12262                cleanUp();
12263                return false;
12264            }
12265
12266            final File targetDir = codeFile.getParentFile();
12267            final File beforeCodeFile = codeFile;
12268            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12269
12270            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12271            try {
12272                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12273            } catch (ErrnoException e) {
12274                Slog.w(TAG, "Failed to rename", e);
12275                return false;
12276            }
12277
12278            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12279                Slog.w(TAG, "Failed to restorecon");
12280                return false;
12281            }
12282
12283            // Reflect the rename internally
12284            codeFile = afterCodeFile;
12285            resourceFile = afterCodeFile;
12286
12287            // Reflect the rename in scanned details
12288            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12289            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12290                    afterCodeFile, pkg.baseCodePath));
12291            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12292                    afterCodeFile, pkg.splitCodePaths));
12293
12294            // Reflect the rename in app info
12295            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12296            pkg.setApplicationInfoCodePath(pkg.codePath);
12297            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12298            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12299            pkg.setApplicationInfoResourcePath(pkg.codePath);
12300            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12301            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12302
12303            return true;
12304        }
12305
12306        int doPostInstall(int status, int uid) {
12307            if (status != PackageManager.INSTALL_SUCCEEDED) {
12308                cleanUp();
12309            }
12310            return status;
12311        }
12312
12313        @Override
12314        String getCodePath() {
12315            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12316        }
12317
12318        @Override
12319        String getResourcePath() {
12320            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12321        }
12322
12323        private boolean cleanUp() {
12324            if (codeFile == null || !codeFile.exists()) {
12325                return false;
12326            }
12327
12328            removeCodePathLI(codeFile);
12329
12330            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12331                resourceFile.delete();
12332            }
12333
12334            return true;
12335        }
12336
12337        void cleanUpResourcesLI() {
12338            // Try enumerating all code paths before deleting
12339            List<String> allCodePaths = Collections.EMPTY_LIST;
12340            if (codeFile != null && codeFile.exists()) {
12341                try {
12342                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12343                    allCodePaths = pkg.getAllCodePaths();
12344                } catch (PackageParserException e) {
12345                    // Ignored; we tried our best
12346                }
12347            }
12348
12349            cleanUp();
12350            removeDexFiles(allCodePaths, instructionSets);
12351        }
12352
12353        boolean doPostDeleteLI(boolean delete) {
12354            // XXX err, shouldn't we respect the delete flag?
12355            cleanUpResourcesLI();
12356            return true;
12357        }
12358    }
12359
12360    private boolean isAsecExternal(String cid) {
12361        final String asecPath = PackageHelper.getSdFilesystem(cid);
12362        return !asecPath.startsWith(mAsecInternalPath);
12363    }
12364
12365    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12366            PackageManagerException {
12367        if (copyRet < 0) {
12368            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12369                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12370                throw new PackageManagerException(copyRet, message);
12371            }
12372        }
12373    }
12374
12375    /**
12376     * Extract the MountService "container ID" from the full code path of an
12377     * .apk.
12378     */
12379    static String cidFromCodePath(String fullCodePath) {
12380        int eidx = fullCodePath.lastIndexOf("/");
12381        String subStr1 = fullCodePath.substring(0, eidx);
12382        int sidx = subStr1.lastIndexOf("/");
12383        return subStr1.substring(sidx+1, eidx);
12384    }
12385
12386    /**
12387     * Logic to handle installation of ASEC applications, including copying and
12388     * renaming logic.
12389     */
12390    class AsecInstallArgs extends InstallArgs {
12391        static final String RES_FILE_NAME = "pkg.apk";
12392        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12393
12394        String cid;
12395        String packagePath;
12396        String resourcePath;
12397
12398        /** New install */
12399        AsecInstallArgs(InstallParams params) {
12400            super(params.origin, params.move, params.observer, params.installFlags,
12401                    params.installerPackageName, params.volumeUuid,
12402                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12403                    params.grantedRuntimePermissions,
12404                    params.traceMethod, params.traceCookie);
12405        }
12406
12407        /** Existing install */
12408        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12409                        boolean isExternal, boolean isForwardLocked) {
12410            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12411                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12412                    instructionSets, null, null, null, 0);
12413            // Hackily pretend we're still looking at a full code path
12414            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12415                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12416            }
12417
12418            // Extract cid from fullCodePath
12419            int eidx = fullCodePath.lastIndexOf("/");
12420            String subStr1 = fullCodePath.substring(0, eidx);
12421            int sidx = subStr1.lastIndexOf("/");
12422            cid = subStr1.substring(sidx+1, eidx);
12423            setMountPath(subStr1);
12424        }
12425
12426        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12427            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12428                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12429                    instructionSets, null, null, null, 0);
12430            this.cid = cid;
12431            setMountPath(PackageHelper.getSdDir(cid));
12432        }
12433
12434        void createCopyFile() {
12435            cid = mInstallerService.allocateExternalStageCidLegacy();
12436        }
12437
12438        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12439            if (origin.staged && origin.cid != null) {
12440                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12441                cid = origin.cid;
12442                setMountPath(PackageHelper.getSdDir(cid));
12443                return PackageManager.INSTALL_SUCCEEDED;
12444            }
12445
12446            if (temp) {
12447                createCopyFile();
12448            } else {
12449                /*
12450                 * Pre-emptively destroy the container since it's destroyed if
12451                 * copying fails due to it existing anyway.
12452                 */
12453                PackageHelper.destroySdDir(cid);
12454            }
12455
12456            final String newMountPath = imcs.copyPackageToContainer(
12457                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12458                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12459
12460            if (newMountPath != null) {
12461                setMountPath(newMountPath);
12462                return PackageManager.INSTALL_SUCCEEDED;
12463            } else {
12464                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12465            }
12466        }
12467
12468        @Override
12469        String getCodePath() {
12470            return packagePath;
12471        }
12472
12473        @Override
12474        String getResourcePath() {
12475            return resourcePath;
12476        }
12477
12478        int doPreInstall(int status) {
12479            if (status != PackageManager.INSTALL_SUCCEEDED) {
12480                // Destroy container
12481                PackageHelper.destroySdDir(cid);
12482            } else {
12483                boolean mounted = PackageHelper.isContainerMounted(cid);
12484                if (!mounted) {
12485                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12486                            Process.SYSTEM_UID);
12487                    if (newMountPath != null) {
12488                        setMountPath(newMountPath);
12489                    } else {
12490                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12491                    }
12492                }
12493            }
12494            return status;
12495        }
12496
12497        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12498            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12499            String newMountPath = null;
12500            if (PackageHelper.isContainerMounted(cid)) {
12501                // Unmount the container
12502                if (!PackageHelper.unMountSdDir(cid)) {
12503                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12504                    return false;
12505                }
12506            }
12507            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12508                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12509                        " which might be stale. Will try to clean up.");
12510                // Clean up the stale container and proceed to recreate.
12511                if (!PackageHelper.destroySdDir(newCacheId)) {
12512                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12513                    return false;
12514                }
12515                // Successfully cleaned up stale container. Try to rename again.
12516                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12517                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12518                            + " inspite of cleaning it up.");
12519                    return false;
12520                }
12521            }
12522            if (!PackageHelper.isContainerMounted(newCacheId)) {
12523                Slog.w(TAG, "Mounting container " + newCacheId);
12524                newMountPath = PackageHelper.mountSdDir(newCacheId,
12525                        getEncryptKey(), Process.SYSTEM_UID);
12526            } else {
12527                newMountPath = PackageHelper.getSdDir(newCacheId);
12528            }
12529            if (newMountPath == null) {
12530                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12531                return false;
12532            }
12533            Log.i(TAG, "Succesfully renamed " + cid +
12534                    " to " + newCacheId +
12535                    " at new path: " + newMountPath);
12536            cid = newCacheId;
12537
12538            final File beforeCodeFile = new File(packagePath);
12539            setMountPath(newMountPath);
12540            final File afterCodeFile = new File(packagePath);
12541
12542            // Reflect the rename in scanned details
12543            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12544            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12545                    afterCodeFile, pkg.baseCodePath));
12546            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12547                    afterCodeFile, pkg.splitCodePaths));
12548
12549            // Reflect the rename in app info
12550            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12551            pkg.setApplicationInfoCodePath(pkg.codePath);
12552            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12553            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12554            pkg.setApplicationInfoResourcePath(pkg.codePath);
12555            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12556            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12557
12558            return true;
12559        }
12560
12561        private void setMountPath(String mountPath) {
12562            final File mountFile = new File(mountPath);
12563
12564            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12565            if (monolithicFile.exists()) {
12566                packagePath = monolithicFile.getAbsolutePath();
12567                if (isFwdLocked()) {
12568                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12569                } else {
12570                    resourcePath = packagePath;
12571                }
12572            } else {
12573                packagePath = mountFile.getAbsolutePath();
12574                resourcePath = packagePath;
12575            }
12576        }
12577
12578        int doPostInstall(int status, int uid) {
12579            if (status != PackageManager.INSTALL_SUCCEEDED) {
12580                cleanUp();
12581            } else {
12582                final int groupOwner;
12583                final String protectedFile;
12584                if (isFwdLocked()) {
12585                    groupOwner = UserHandle.getSharedAppGid(uid);
12586                    protectedFile = RES_FILE_NAME;
12587                } else {
12588                    groupOwner = -1;
12589                    protectedFile = null;
12590                }
12591
12592                if (uid < Process.FIRST_APPLICATION_UID
12593                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12594                    Slog.e(TAG, "Failed to finalize " + cid);
12595                    PackageHelper.destroySdDir(cid);
12596                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12597                }
12598
12599                boolean mounted = PackageHelper.isContainerMounted(cid);
12600                if (!mounted) {
12601                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12602                }
12603            }
12604            return status;
12605        }
12606
12607        private void cleanUp() {
12608            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12609
12610            // Destroy secure container
12611            PackageHelper.destroySdDir(cid);
12612        }
12613
12614        private List<String> getAllCodePaths() {
12615            final File codeFile = new File(getCodePath());
12616            if (codeFile != null && codeFile.exists()) {
12617                try {
12618                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12619                    return pkg.getAllCodePaths();
12620                } catch (PackageParserException e) {
12621                    // Ignored; we tried our best
12622                }
12623            }
12624            return Collections.EMPTY_LIST;
12625        }
12626
12627        void cleanUpResourcesLI() {
12628            // Enumerate all code paths before deleting
12629            cleanUpResourcesLI(getAllCodePaths());
12630        }
12631
12632        private void cleanUpResourcesLI(List<String> allCodePaths) {
12633            cleanUp();
12634            removeDexFiles(allCodePaths, instructionSets);
12635        }
12636
12637        String getPackageName() {
12638            return getAsecPackageName(cid);
12639        }
12640
12641        boolean doPostDeleteLI(boolean delete) {
12642            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12643            final List<String> allCodePaths = getAllCodePaths();
12644            boolean mounted = PackageHelper.isContainerMounted(cid);
12645            if (mounted) {
12646                // Unmount first
12647                if (PackageHelper.unMountSdDir(cid)) {
12648                    mounted = false;
12649                }
12650            }
12651            if (!mounted && delete) {
12652                cleanUpResourcesLI(allCodePaths);
12653            }
12654            return !mounted;
12655        }
12656
12657        @Override
12658        int doPreCopy() {
12659            if (isFwdLocked()) {
12660                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12661                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12662                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12663                }
12664            }
12665
12666            return PackageManager.INSTALL_SUCCEEDED;
12667        }
12668
12669        @Override
12670        int doPostCopy(int uid) {
12671            if (isFwdLocked()) {
12672                if (uid < Process.FIRST_APPLICATION_UID
12673                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12674                                RES_FILE_NAME)) {
12675                    Slog.e(TAG, "Failed to finalize " + cid);
12676                    PackageHelper.destroySdDir(cid);
12677                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12678                }
12679            }
12680
12681            return PackageManager.INSTALL_SUCCEEDED;
12682        }
12683    }
12684
12685    /**
12686     * Logic to handle movement of existing installed applications.
12687     */
12688    class MoveInstallArgs extends InstallArgs {
12689        private File codeFile;
12690        private File resourceFile;
12691
12692        /** New install */
12693        MoveInstallArgs(InstallParams params) {
12694            super(params.origin, params.move, params.observer, params.installFlags,
12695                    params.installerPackageName, params.volumeUuid,
12696                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12697                    params.grantedRuntimePermissions,
12698                    params.traceMethod, params.traceCookie);
12699        }
12700
12701        int copyApk(IMediaContainerService imcs, boolean temp) {
12702            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12703                    + move.fromUuid + " to " + move.toUuid);
12704            synchronized (mInstaller) {
12705                try {
12706                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12707                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12708                } catch (InstallerException e) {
12709                    Slog.w(TAG, "Failed to move app", e);
12710                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12711                }
12712            }
12713
12714            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12715            resourceFile = codeFile;
12716            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12717
12718            return PackageManager.INSTALL_SUCCEEDED;
12719        }
12720
12721        int doPreInstall(int status) {
12722            if (status != PackageManager.INSTALL_SUCCEEDED) {
12723                cleanUp(move.toUuid);
12724            }
12725            return status;
12726        }
12727
12728        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12729            if (status != PackageManager.INSTALL_SUCCEEDED) {
12730                cleanUp(move.toUuid);
12731                return false;
12732            }
12733
12734            // Reflect the move in app info
12735            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12736            pkg.setApplicationInfoCodePath(pkg.codePath);
12737            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12738            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12739            pkg.setApplicationInfoResourcePath(pkg.codePath);
12740            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12741            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12742
12743            return true;
12744        }
12745
12746        int doPostInstall(int status, int uid) {
12747            if (status == PackageManager.INSTALL_SUCCEEDED) {
12748                cleanUp(move.fromUuid);
12749            } else {
12750                cleanUp(move.toUuid);
12751            }
12752            return status;
12753        }
12754
12755        @Override
12756        String getCodePath() {
12757            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12758        }
12759
12760        @Override
12761        String getResourcePath() {
12762            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12763        }
12764
12765        private boolean cleanUp(String volumeUuid) {
12766            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12767                    move.dataAppName);
12768            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12769            synchronized (mInstallLock) {
12770                // Clean up both app data and code
12771                removeDataDirsLI(volumeUuid, move.packageName);
12772                removeCodePathLI(codeFile);
12773            }
12774            return true;
12775        }
12776
12777        void cleanUpResourcesLI() {
12778            throw new UnsupportedOperationException();
12779        }
12780
12781        boolean doPostDeleteLI(boolean delete) {
12782            throw new UnsupportedOperationException();
12783        }
12784    }
12785
12786    static String getAsecPackageName(String packageCid) {
12787        int idx = packageCid.lastIndexOf("-");
12788        if (idx == -1) {
12789            return packageCid;
12790        }
12791        return packageCid.substring(0, idx);
12792    }
12793
12794    // Utility method used to create code paths based on package name and available index.
12795    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12796        String idxStr = "";
12797        int idx = 1;
12798        // Fall back to default value of idx=1 if prefix is not
12799        // part of oldCodePath
12800        if (oldCodePath != null) {
12801            String subStr = oldCodePath;
12802            // Drop the suffix right away
12803            if (suffix != null && subStr.endsWith(suffix)) {
12804                subStr = subStr.substring(0, subStr.length() - suffix.length());
12805            }
12806            // If oldCodePath already contains prefix find out the
12807            // ending index to either increment or decrement.
12808            int sidx = subStr.lastIndexOf(prefix);
12809            if (sidx != -1) {
12810                subStr = subStr.substring(sidx + prefix.length());
12811                if (subStr != null) {
12812                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12813                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12814                    }
12815                    try {
12816                        idx = Integer.parseInt(subStr);
12817                        if (idx <= 1) {
12818                            idx++;
12819                        } else {
12820                            idx--;
12821                        }
12822                    } catch(NumberFormatException e) {
12823                    }
12824                }
12825            }
12826        }
12827        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12828        return prefix + idxStr;
12829    }
12830
12831    private File getNextCodePath(File targetDir, String packageName) {
12832        int suffix = 1;
12833        File result;
12834        do {
12835            result = new File(targetDir, packageName + "-" + suffix);
12836            suffix++;
12837        } while (result.exists());
12838        return result;
12839    }
12840
12841    // Utility method that returns the relative package path with respect
12842    // to the installation directory. Like say for /data/data/com.test-1.apk
12843    // string com.test-1 is returned.
12844    static String deriveCodePathName(String codePath) {
12845        if (codePath == null) {
12846            return null;
12847        }
12848        final File codeFile = new File(codePath);
12849        final String name = codeFile.getName();
12850        if (codeFile.isDirectory()) {
12851            return name;
12852        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12853            final int lastDot = name.lastIndexOf('.');
12854            return name.substring(0, lastDot);
12855        } else {
12856            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12857            return null;
12858        }
12859    }
12860
12861    static class PackageInstalledInfo {
12862        String name;
12863        int uid;
12864        // The set of users that originally had this package installed.
12865        int[] origUsers;
12866        // The set of users that now have this package installed.
12867        int[] newUsers;
12868        PackageParser.Package pkg;
12869        int returnCode;
12870        String returnMsg;
12871        PackageRemovedInfo removedInfo;
12872        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12873
12874        public void setError(int code, String msg) {
12875            setReturnCode(code);
12876            setReturnMessage(msg);
12877            Slog.w(TAG, msg);
12878        }
12879
12880        public void setError(String msg, PackageParserException e) {
12881            setReturnCode(e.error);
12882            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12883            Slog.w(TAG, msg, e);
12884        }
12885
12886        public void setError(String msg, PackageManagerException e) {
12887            returnCode = e.error;
12888            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12889            Slog.w(TAG, msg, e);
12890        }
12891
12892        public void setReturnCode(int returnCode) {
12893            this.returnCode = returnCode;
12894            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12895            for (int i = 0; i < childCount; i++) {
12896                addedChildPackages.valueAt(i).returnCode = returnCode;
12897            }
12898        }
12899
12900        private void setReturnMessage(String returnMsg) {
12901            this.returnMsg = returnMsg;
12902            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12903            for (int i = 0; i < childCount; i++) {
12904                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12905            }
12906        }
12907
12908        // In some error cases we want to convey more info back to the observer
12909        String origPackage;
12910        String origPermission;
12911    }
12912
12913    /*
12914     * Install a non-existing package.
12915     */
12916    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12917            UserHandle user, String installerPackageName, String volumeUuid,
12918            PackageInstalledInfo res) {
12919        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12920
12921        // Remember this for later, in case we need to rollback this install
12922        String pkgName = pkg.packageName;
12923
12924        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12925
12926        synchronized(mPackages) {
12927            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12928                // A package with the same name is already installed, though
12929                // it has been renamed to an older name.  The package we
12930                // are trying to install should be installed as an update to
12931                // the existing one, but that has not been requested, so bail.
12932                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12933                        + " without first uninstalling package running as "
12934                        + mSettings.mRenamedPackages.get(pkgName));
12935                return;
12936            }
12937            if (mPackages.containsKey(pkgName)) {
12938                // Don't allow installation over an existing package with the same name.
12939                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12940                        + " without first uninstalling.");
12941                return;
12942            }
12943        }
12944
12945        try {
12946            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12947                    System.currentTimeMillis(), user);
12948
12949            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12950
12951            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12952                prepareAppDataAfterInstall(newPackage);
12953
12954            } else {
12955                // Remove package from internal structures, but keep around any
12956                // data that might have already existed
12957                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12958                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12959            }
12960        } catch (PackageManagerException e) {
12961            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12962        }
12963
12964        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12965    }
12966
12967    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12968        // Can't rotate keys during boot or if sharedUser.
12969        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12970                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12971            return false;
12972        }
12973        // app is using upgradeKeySets; make sure all are valid
12974        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12975        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12976        for (int i = 0; i < upgradeKeySets.length; i++) {
12977            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12978                Slog.wtf(TAG, "Package "
12979                         + (oldPs.name != null ? oldPs.name : "<null>")
12980                         + " contains upgrade-key-set reference to unknown key-set: "
12981                         + upgradeKeySets[i]
12982                         + " reverting to signatures check.");
12983                return false;
12984            }
12985        }
12986        return true;
12987    }
12988
12989    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12990        // Upgrade keysets are being used.  Determine if new package has a superset of the
12991        // required keys.
12992        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12993        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12994        for (int i = 0; i < upgradeKeySets.length; i++) {
12995            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12996            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12997                return true;
12998            }
12999        }
13000        return false;
13001    }
13002
13003    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13004            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13005        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13006
13007        final PackageParser.Package oldPackage;
13008        final String pkgName = pkg.packageName;
13009        final int[] allUsers;
13010
13011        // First find the old package info and check signatures
13012        synchronized(mPackages) {
13013            oldPackage = mPackages.get(pkgName);
13014            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13015            if (isEphemeral && !oldIsEphemeral) {
13016                // can't downgrade from full to ephemeral
13017                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13018                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13019                return;
13020            }
13021            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13022            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13023            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13024                if (!checkUpgradeKeySetLP(ps, pkg)) {
13025                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13026                            "New package not signed by keys specified by upgrade-keysets: "
13027                                    + pkgName);
13028                    return;
13029                }
13030            } else {
13031                // default to original signature matching
13032                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13033                        != PackageManager.SIGNATURE_MATCH) {
13034                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13035                            "New package has a different signature: " + pkgName);
13036                    return;
13037                }
13038            }
13039
13040            // In case of rollback, remember per-user/profile install state
13041            allUsers = sUserManager.getUserIds();
13042        }
13043
13044        // Update what is removed
13045        res.removedInfo = new PackageRemovedInfo();
13046        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13047        res.removedInfo.removedPackage = oldPackage.packageName;
13048        res.removedInfo.isUpdate = true;
13049        final int childCount = (oldPackage.childPackages != null)
13050                ? oldPackage.childPackages.size() : 0;
13051        for (int i = 0; i < childCount; i++) {
13052            boolean childPackageUpdated = false;
13053            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13054            if (res.addedChildPackages != null) {
13055                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13056                if (childRes != null) {
13057                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13058                    childRes.removedInfo.removedPackage = childPkg.packageName;
13059                    childRes.removedInfo.isUpdate = true;
13060                    childPackageUpdated = true;
13061                }
13062            }
13063            if (!childPackageUpdated) {
13064                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13065                childRemovedRes.removedPackage = childPkg.packageName;
13066                childRemovedRes.isUpdate = false;
13067                childRemovedRes.dataRemoved = true;
13068                synchronized (mPackages) {
13069                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13070                    if (childPs != null) {
13071                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13072                    }
13073                }
13074                if (res.removedInfo.removedChildPackages == null) {
13075                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13076                }
13077                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13078            }
13079        }
13080
13081        boolean sysPkg = (isSystemApp(oldPackage));
13082        if (sysPkg) {
13083            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13084                    user, allUsers, installerPackageName, res);
13085        } else {
13086            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13087                    user, allUsers, installerPackageName, res);
13088        }
13089    }
13090
13091    public List<String> getPreviousCodePaths(String packageName) {
13092        final PackageSetting ps = mSettings.mPackages.get(packageName);
13093        final List<String> result = new ArrayList<String>();
13094        if (ps != null && ps.oldCodePaths != null) {
13095            result.addAll(ps.oldCodePaths);
13096        }
13097        return result;
13098    }
13099
13100    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13101            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13102            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13103        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13104                + deletedPackage);
13105
13106        String pkgName = deletedPackage.packageName;
13107        boolean deletedPkg = true;
13108        boolean addedPkg = false;
13109        boolean updatedSettings = false;
13110        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13111        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13112                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13113
13114        final long origUpdateTime = (pkg.mExtras != null)
13115                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13116
13117        // First delete the existing package while retaining the data directory
13118        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13119                res.removedInfo, true, pkg)) {
13120            // If the existing package wasn't successfully deleted
13121            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13122            deletedPkg = false;
13123        } else {
13124            // Successfully deleted the old package; proceed with replace.
13125
13126            // If deleted package lived in a container, give users a chance to
13127            // relinquish resources before killing.
13128            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13129                if (DEBUG_INSTALL) {
13130                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13131                }
13132                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13133                final ArrayList<String> pkgList = new ArrayList<String>(1);
13134                pkgList.add(deletedPackage.applicationInfo.packageName);
13135                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13136            }
13137
13138            deleteCodeCacheDirsLI(pkg);
13139
13140            try {
13141                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13142                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13143                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13144
13145                // Update the in-memory copy of the previous code paths.
13146                PackageSetting ps = mSettings.mPackages.get(pkgName);
13147                if (!killApp) {
13148                    if (ps.oldCodePaths == null) {
13149                        ps.oldCodePaths = new ArraySet<>();
13150                    }
13151                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13152                    if (deletedPackage.splitCodePaths != null) {
13153                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13154                    }
13155                } else {
13156                    ps.oldCodePaths = null;
13157                }
13158                if (ps.childPackageNames != null) {
13159                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13160                        final String childPkgName = ps.childPackageNames.get(i);
13161                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13162                        childPs.oldCodePaths = ps.oldCodePaths;
13163                    }
13164                }
13165                prepareAppDataAfterInstall(newPackage);
13166                addedPkg = true;
13167            } catch (PackageManagerException e) {
13168                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13169            }
13170        }
13171
13172        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13173            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13174
13175            // Revert all internal state mutations and added folders for the failed install
13176            if (addedPkg) {
13177                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13178                        res.removedInfo, true, null);
13179            }
13180
13181            // Restore the old package
13182            if (deletedPkg) {
13183                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13184                File restoreFile = new File(deletedPackage.codePath);
13185                // Parse old package
13186                boolean oldExternal = isExternal(deletedPackage);
13187                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13188                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13189                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13190                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13191                try {
13192                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13193                            null);
13194                } catch (PackageManagerException e) {
13195                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13196                            + e.getMessage());
13197                    return;
13198                }
13199
13200                synchronized (mPackages) {
13201                    // Ensure the installer package name up to date
13202                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13203
13204                    // Update permissions for restored package
13205                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13206
13207                    mSettings.writeLPr();
13208                }
13209
13210                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13211            }
13212        } else {
13213            synchronized (mPackages) {
13214                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13215                if (ps != null) {
13216                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13217                    if (res.removedInfo.removedChildPackages != null) {
13218                        final int childCount = res.removedInfo.removedChildPackages.size();
13219                        // Iterate in reverse as we may modify the collection
13220                        for (int i = childCount - 1; i >= 0; i--) {
13221                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13222                            if (res.addedChildPackages.containsKey(childPackageName)) {
13223                                res.removedInfo.removedChildPackages.removeAt(i);
13224                            } else {
13225                                PackageRemovedInfo childInfo = res.removedInfo
13226                                        .removedChildPackages.valueAt(i);
13227                                childInfo.removedForAllUsers = mPackages.get(
13228                                        childInfo.removedPackage) == null;
13229                            }
13230                        }
13231                    }
13232                }
13233            }
13234        }
13235    }
13236
13237    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13238            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13239            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13240        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13241                + ", old=" + deletedPackage);
13242
13243        final boolean disabledSystem;
13244
13245        // Set the system/privileged flags as needed
13246        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13247        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13248                != 0) {
13249            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13250        }
13251
13252        // Kill package processes including services, providers, etc.
13253        killPackage(deletedPackage, "replace sys pkg");
13254
13255        // Remove existing system package
13256        removePackageLI(deletedPackage, true);
13257
13258        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13259        if (!disabledSystem) {
13260            // We didn't need to disable the .apk as a current system package,
13261            // which means we are replacing another update that is already
13262            // installed.  We need to make sure to delete the older one's .apk.
13263            res.removedInfo.args = createInstallArgsForExisting(0,
13264                    deletedPackage.applicationInfo.getCodePath(),
13265                    deletedPackage.applicationInfo.getResourcePath(),
13266                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13267        } else {
13268            res.removedInfo.args = null;
13269        }
13270
13271        // Successfully disabled the old package. Now proceed with re-installation
13272        deleteCodeCacheDirsLI(pkg);
13273
13274        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13275        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13276                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13277
13278        PackageParser.Package newPackage = null;
13279        try {
13280            // Add the package to the internal data structures
13281            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13282
13283            // Set the update and install times
13284            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13285            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13286                    System.currentTimeMillis());
13287
13288            // Check for shared user id changes
13289            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13290                    deletedPackage, newPackage);
13291            if (invalidPackageName != null) {
13292                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13293                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13294                                + " to " + invalidPackageName);
13295            }
13296
13297            // Update the package dynamic state if succeeded
13298            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13299                // Now that the install succeeded make sure we remove data
13300                // directories for any child package the update removed.
13301                final int deletedChildCount = (deletedPackage.childPackages != null)
13302                        ? deletedPackage.childPackages.size() : 0;
13303                final int newChildCount = (newPackage.childPackages != null)
13304                        ? newPackage.childPackages.size() : 0;
13305                for (int i = 0; i < deletedChildCount; i++) {
13306                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13307                    boolean childPackageDeleted = true;
13308                    for (int j = 0; j < newChildCount; j++) {
13309                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13310                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13311                            childPackageDeleted = false;
13312                            break;
13313                        }
13314                    }
13315                    if (childPackageDeleted) {
13316                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13317                                deletedChildPkg.packageName);
13318                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13319                            PackageRemovedInfo removedChildRes = res.removedInfo
13320                                    .removedChildPackages.get(deletedChildPkg.packageName);
13321                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13322                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13323                        }
13324                    }
13325                }
13326
13327                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13328                prepareAppDataAfterInstall(newPackage);
13329            }
13330        } catch (PackageManagerException e) {
13331            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13332            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13333        }
13334
13335        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13336            // Re installation failed. Restore old information
13337            // Remove new pkg information
13338            if (newPackage != null) {
13339                removeInstalledPackageLI(newPackage, true);
13340            }
13341            // Add back the old system package
13342            try {
13343                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13344            } catch (PackageManagerException e) {
13345                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13346            }
13347
13348            synchronized (mPackages) {
13349                if (disabledSystem) {
13350                    enableSystemPackageLPw(deletedPackage);
13351                }
13352
13353                // Ensure the installer package name up to date
13354                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13355
13356                // Update permissions for restored package
13357                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13358
13359                mSettings.writeLPr();
13360            }
13361
13362            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13363                    + " after failed upgrade");
13364        }
13365    }
13366
13367    /**
13368     * Checks whether the parent or any of the child packages have a change shared
13369     * user. For a package to be a valid update the shred users of the parent and
13370     * the children should match. We may later support changing child shared users.
13371     * @param oldPkg The updated package.
13372     * @param newPkg The update package.
13373     * @return The shared user that change between the versions.
13374     */
13375    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13376            PackageParser.Package newPkg) {
13377        // Check parent shared user
13378        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13379            return newPkg.packageName;
13380        }
13381        // Check child shared users
13382        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13383        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13384        for (int i = 0; i < newChildCount; i++) {
13385            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13386            // If this child was present, did it have the same shared user?
13387            for (int j = 0; j < oldChildCount; j++) {
13388                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13389                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13390                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13391                    return newChildPkg.packageName;
13392                }
13393            }
13394        }
13395        return null;
13396    }
13397
13398    private void removeNativeBinariesLI(PackageSetting ps) {
13399        // Remove the lib path for the parent package
13400        if (ps != null) {
13401            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13402            // Remove the lib path for the child packages
13403            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13404            for (int i = 0; i < childCount; i++) {
13405                PackageSetting childPs = null;
13406                synchronized (mPackages) {
13407                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13408                }
13409                if (childPs != null) {
13410                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13411                            .legacyNativeLibraryPathString);
13412                }
13413            }
13414        }
13415    }
13416
13417    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13418        // Enable the parent package
13419        mSettings.enableSystemPackageLPw(pkg.packageName);
13420        // Enable the child packages
13421        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13422        for (int i = 0; i < childCount; i++) {
13423            PackageParser.Package childPkg = pkg.childPackages.get(i);
13424            mSettings.enableSystemPackageLPw(childPkg.packageName);
13425        }
13426    }
13427
13428    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13429            PackageParser.Package newPkg) {
13430        // Disable the parent package (parent always replaced)
13431        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13432        // Disable the child packages
13433        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13434        for (int i = 0; i < childCount; i++) {
13435            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13436            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13437            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13438        }
13439        return disabled;
13440    }
13441
13442    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13443            String installerPackageName) {
13444        // Enable the parent package
13445        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13446        // Enable the child packages
13447        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13448        for (int i = 0; i < childCount; i++) {
13449            PackageParser.Package childPkg = pkg.childPackages.get(i);
13450            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13451        }
13452    }
13453
13454    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13455        // Collect all used permissions in the UID
13456        ArraySet<String> usedPermissions = new ArraySet<>();
13457        final int packageCount = su.packages.size();
13458        for (int i = 0; i < packageCount; i++) {
13459            PackageSetting ps = su.packages.valueAt(i);
13460            if (ps.pkg == null) {
13461                continue;
13462            }
13463            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13464            for (int j = 0; j < requestedPermCount; j++) {
13465                String permission = ps.pkg.requestedPermissions.get(j);
13466                BasePermission bp = mSettings.mPermissions.get(permission);
13467                if (bp != null) {
13468                    usedPermissions.add(permission);
13469                }
13470            }
13471        }
13472
13473        PermissionsState permissionsState = su.getPermissionsState();
13474        // Prune install permissions
13475        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13476        final int installPermCount = installPermStates.size();
13477        for (int i = installPermCount - 1; i >= 0;  i--) {
13478            PermissionState permissionState = installPermStates.get(i);
13479            if (!usedPermissions.contains(permissionState.getName())) {
13480                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13481                if (bp != null) {
13482                    permissionsState.revokeInstallPermission(bp);
13483                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13484                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13485                }
13486            }
13487        }
13488
13489        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13490
13491        // Prune runtime permissions
13492        for (int userId : allUserIds) {
13493            List<PermissionState> runtimePermStates = permissionsState
13494                    .getRuntimePermissionStates(userId);
13495            final int runtimePermCount = runtimePermStates.size();
13496            for (int i = runtimePermCount - 1; i >= 0; i--) {
13497                PermissionState permissionState = runtimePermStates.get(i);
13498                if (!usedPermissions.contains(permissionState.getName())) {
13499                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13500                    if (bp != null) {
13501                        permissionsState.revokeRuntimePermission(bp, userId);
13502                        permissionsState.updatePermissionFlags(bp, userId,
13503                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13504                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13505                                runtimePermissionChangedUserIds, userId);
13506                    }
13507                }
13508            }
13509        }
13510
13511        return runtimePermissionChangedUserIds;
13512    }
13513
13514    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13515            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13516        // Update the parent package setting
13517        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13518                res, user);
13519        // Update the child packages setting
13520        final int childCount = (newPackage.childPackages != null)
13521                ? newPackage.childPackages.size() : 0;
13522        for (int i = 0; i < childCount; i++) {
13523            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13524            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13525            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13526                    childRes.origUsers, childRes, user);
13527        }
13528    }
13529
13530    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13531            String installerPackageName, int[] allUsers, int[] installedForUsers,
13532            PackageInstalledInfo res, UserHandle user) {
13533        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13534
13535        String pkgName = newPackage.packageName;
13536        synchronized (mPackages) {
13537            //write settings. the installStatus will be incomplete at this stage.
13538            //note that the new package setting would have already been
13539            //added to mPackages. It hasn't been persisted yet.
13540            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13541            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13542            mSettings.writeLPr();
13543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13544        }
13545
13546        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13547        synchronized (mPackages) {
13548            updatePermissionsLPw(newPackage.packageName, newPackage,
13549                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13550                            ? UPDATE_PERMISSIONS_ALL : 0));
13551            // For system-bundled packages, we assume that installing an upgraded version
13552            // of the package implies that the user actually wants to run that new code,
13553            // so we enable the package.
13554            PackageSetting ps = mSettings.mPackages.get(pkgName);
13555            final int userId = user.getIdentifier();
13556            if (ps != null) {
13557                if (isSystemApp(newPackage)) {
13558                    if (DEBUG_INSTALL) {
13559                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13560                    }
13561                    // Enable system package for requested users
13562                    if (res.origUsers != null) {
13563                        for (int origUserId : res.origUsers) {
13564                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13565                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13566                                        origUserId, installerPackageName);
13567                            }
13568                        }
13569                    }
13570                    // Also convey the prior install/uninstall state
13571                    if (allUsers != null && installedForUsers != null) {
13572                        for (int currentUserId : allUsers) {
13573                            final boolean installed = ArrayUtils.contains(
13574                                    installedForUsers, currentUserId);
13575                            if (DEBUG_INSTALL) {
13576                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13577                            }
13578                            ps.setInstalled(installed, currentUserId);
13579                        }
13580                        // these install state changes will be persisted in the
13581                        // upcoming call to mSettings.writeLPr().
13582                    }
13583                }
13584                // It's implied that when a user requests installation, they want the app to be
13585                // installed and enabled.
13586                if (userId != UserHandle.USER_ALL) {
13587                    ps.setInstalled(true, userId);
13588                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13589                }
13590            }
13591            res.name = pkgName;
13592            res.uid = newPackage.applicationInfo.uid;
13593            res.pkg = newPackage;
13594            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13595            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13596            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13597            //to update install status
13598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13599            mSettings.writeLPr();
13600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13601        }
13602
13603        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13604    }
13605
13606    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13607        try {
13608            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13609            installPackageLI(args, res);
13610        } finally {
13611            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13612        }
13613    }
13614
13615    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13616        final int installFlags = args.installFlags;
13617        final String installerPackageName = args.installerPackageName;
13618        final String volumeUuid = args.volumeUuid;
13619        final File tmpPackageFile = new File(args.getCodePath());
13620        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13621        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13622                || (args.volumeUuid != null));
13623        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13624        boolean replace = false;
13625        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13626        if (args.move != null) {
13627            // moving a complete application; perform an initial scan on the new install location
13628            scanFlags |= SCAN_INITIAL;
13629        }
13630        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13631            scanFlags |= SCAN_DONT_KILL_APP;
13632        }
13633
13634        // Result object to be returned
13635        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13636
13637        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13638
13639        // Sanity check
13640        if (ephemeral && (forwardLocked || onExternal)) {
13641            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13642                    + " external=" + onExternal);
13643            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13644            return;
13645        }
13646
13647        // Retrieve PackageSettings and parse package
13648        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13649                | PackageParser.PARSE_ENFORCE_CODE
13650                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13651                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13652                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13653        PackageParser pp = new PackageParser();
13654        pp.setSeparateProcesses(mSeparateProcesses);
13655        pp.setDisplayMetrics(mMetrics);
13656
13657        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13658        final PackageParser.Package pkg;
13659        try {
13660            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13661        } catch (PackageParserException e) {
13662            res.setError("Failed parse during installPackageLI", e);
13663            return;
13664        } finally {
13665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13666        }
13667
13668        // If we are installing a clustered package add results for the children
13669        if (pkg.childPackages != null) {
13670            synchronized (mPackages) {
13671                final int childCount = pkg.childPackages.size();
13672                for (int i = 0; i < childCount; i++) {
13673                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13674                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13675                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13676                    childRes.pkg = childPkg;
13677                    childRes.name = childPkg.packageName;
13678                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13679                    if (childPs != null) {
13680                        childRes.origUsers = childPs.queryInstalledUsers(
13681                                sUserManager.getUserIds(), true);
13682                    }
13683                    if ((mPackages.containsKey(childPkg.packageName))) {
13684                        childRes.removedInfo = new PackageRemovedInfo();
13685                        childRes.removedInfo.removedPackage = childPkg.packageName;
13686                    }
13687                    if (res.addedChildPackages == null) {
13688                        res.addedChildPackages = new ArrayMap<>();
13689                    }
13690                    res.addedChildPackages.put(childPkg.packageName, childRes);
13691                }
13692            }
13693        }
13694
13695        // If package doesn't declare API override, mark that we have an install
13696        // time CPU ABI override.
13697        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13698            pkg.cpuAbiOverride = args.abiOverride;
13699        }
13700
13701        String pkgName = res.name = pkg.packageName;
13702        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13703            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13704                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13705                return;
13706            }
13707        }
13708
13709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13710        try {
13711            PackageParser.collectCertificates(pkg, parseFlags);
13712        } catch (PackageParserException e) {
13713            res.setError("Failed collect during installPackageLI", e);
13714            return;
13715        } finally {
13716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13717        }
13718
13719        // Get rid of all references to package scan path via parser.
13720        pp = null;
13721        String oldCodePath = null;
13722        boolean systemApp = false;
13723        synchronized (mPackages) {
13724            // Check if installing already existing package
13725            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13726                String oldName = mSettings.mRenamedPackages.get(pkgName);
13727                if (pkg.mOriginalPackages != null
13728                        && pkg.mOriginalPackages.contains(oldName)
13729                        && mPackages.containsKey(oldName)) {
13730                    // This package is derived from an original package,
13731                    // and this device has been updating from that original
13732                    // name.  We must continue using the original name, so
13733                    // rename the new package here.
13734                    pkg.setPackageName(oldName);
13735                    pkgName = pkg.packageName;
13736                    replace = true;
13737                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13738                            + oldName + " pkgName=" + pkgName);
13739                } else if (mPackages.containsKey(pkgName)) {
13740                    // This package, under its official name, already exists
13741                    // on the device; we should replace it.
13742                    replace = true;
13743                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13744                }
13745
13746                // Child packages are installed through the parent package
13747                if (pkg.parentPackage != null) {
13748                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13749                            "Package " + pkg.packageName + " is child of package "
13750                                    + pkg.parentPackage.parentPackage + ". Child packages "
13751                                    + "can be updated only through the parent package.");
13752                    return;
13753                }
13754
13755                if (replace) {
13756                    // Prevent apps opting out from runtime permissions
13757                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13758                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13759                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13760                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13761                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13762                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13763                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13764                                        + " doesn't support runtime permissions but the old"
13765                                        + " target SDK " + oldTargetSdk + " does.");
13766                        return;
13767                    }
13768
13769                    // Prevent installing of child packages
13770                    if (oldPackage.parentPackage != null) {
13771                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13772                                "Package " + pkg.packageName + " is child of package "
13773                                        + oldPackage.parentPackage + ". Child packages "
13774                                        + "can be updated only through the parent package.");
13775                        return;
13776                    }
13777                }
13778            }
13779
13780            PackageSetting ps = mSettings.mPackages.get(pkgName);
13781            if (ps != null) {
13782                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13783
13784                // Quick sanity check that we're signed correctly if updating;
13785                // we'll check this again later when scanning, but we want to
13786                // bail early here before tripping over redefined permissions.
13787                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13788                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13789                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13790                                + pkg.packageName + " upgrade keys do not match the "
13791                                + "previously installed version");
13792                        return;
13793                    }
13794                } else {
13795                    try {
13796                        verifySignaturesLP(ps, pkg);
13797                    } catch (PackageManagerException e) {
13798                        res.setError(e.error, e.getMessage());
13799                        return;
13800                    }
13801                }
13802
13803                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13804                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13805                    systemApp = (ps.pkg.applicationInfo.flags &
13806                            ApplicationInfo.FLAG_SYSTEM) != 0;
13807                }
13808                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13809            }
13810
13811            // Check whether the newly-scanned package wants to define an already-defined perm
13812            int N = pkg.permissions.size();
13813            for (int i = N-1; i >= 0; i--) {
13814                PackageParser.Permission perm = pkg.permissions.get(i);
13815                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13816                if (bp != null) {
13817                    // If the defining package is signed with our cert, it's okay.  This
13818                    // also includes the "updating the same package" case, of course.
13819                    // "updating same package" could also involve key-rotation.
13820                    final boolean sigsOk;
13821                    if (bp.sourcePackage.equals(pkg.packageName)
13822                            && (bp.packageSetting instanceof PackageSetting)
13823                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13824                                    scanFlags))) {
13825                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13826                    } else {
13827                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13828                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13829                    }
13830                    if (!sigsOk) {
13831                        // If the owning package is the system itself, we log but allow
13832                        // install to proceed; we fail the install on all other permission
13833                        // redefinitions.
13834                        if (!bp.sourcePackage.equals("android")) {
13835                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13836                                    + pkg.packageName + " attempting to redeclare permission "
13837                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13838                            res.origPermission = perm.info.name;
13839                            res.origPackage = bp.sourcePackage;
13840                            return;
13841                        } else {
13842                            Slog.w(TAG, "Package " + pkg.packageName
13843                                    + " attempting to redeclare system permission "
13844                                    + perm.info.name + "; ignoring new declaration");
13845                            pkg.permissions.remove(i);
13846                        }
13847                    }
13848                }
13849            }
13850        }
13851
13852        if (systemApp) {
13853            if (onExternal) {
13854                // Abort update; system app can't be replaced with app on sdcard
13855                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13856                        "Cannot install updates to system apps on sdcard");
13857                return;
13858            } else if (ephemeral) {
13859                // Abort update; system app can't be replaced with an ephemeral app
13860                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13861                        "Cannot update a system app with an ephemeral app");
13862                return;
13863            }
13864        }
13865
13866        if (args.move != null) {
13867            // We did an in-place move, so dex is ready to roll
13868            scanFlags |= SCAN_NO_DEX;
13869            scanFlags |= SCAN_MOVE;
13870
13871            synchronized (mPackages) {
13872                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13873                if (ps == null) {
13874                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13875                            "Missing settings for moved package " + pkgName);
13876                }
13877
13878                // We moved the entire application as-is, so bring over the
13879                // previously derived ABI information.
13880                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13881                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13882            }
13883
13884        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13885            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13886            scanFlags |= SCAN_NO_DEX;
13887
13888            try {
13889                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13890                    args.abiOverride : pkg.cpuAbiOverride);
13891                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13892                        true /* extract libs */);
13893            } catch (PackageManagerException pme) {
13894                Slog.e(TAG, "Error deriving application ABI", pme);
13895                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13896                return;
13897            }
13898
13899
13900            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13901            // Do not run PackageDexOptimizer through the local performDexOpt
13902            // method because `pkg` is not in `mPackages` yet.
13903            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13904                    false /* useProfiles */, true /* extractOnly */);
13905            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13906            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13907                String msg = "Extracking package failed for " + pkgName;
13908                res.setError(INSTALL_FAILED_DEXOPT, msg);
13909                return;
13910            }
13911        }
13912
13913        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13914            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13915            return;
13916        }
13917
13918        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13919
13920        if (replace) {
13921            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13922                    installerPackageName, res);
13923        } else {
13924            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13925                    args.user, installerPackageName, volumeUuid, res);
13926        }
13927        synchronized (mPackages) {
13928            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13929            if (ps != null) {
13930                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13931            }
13932
13933            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13934            for (int i = 0; i < childCount; i++) {
13935                PackageParser.Package childPkg = pkg.childPackages.get(i);
13936                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13937                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13938                if (childPs != null) {
13939                    childRes.newUsers = childPs.queryInstalledUsers(
13940                            sUserManager.getUserIds(), true);
13941                }
13942            }
13943        }
13944    }
13945
13946    private void startIntentFilterVerifications(int userId, boolean replacing,
13947            PackageParser.Package pkg) {
13948        if (mIntentFilterVerifierComponent == null) {
13949            Slog.w(TAG, "No IntentFilter verification will not be done as "
13950                    + "there is no IntentFilterVerifier available!");
13951            return;
13952        }
13953
13954        final int verifierUid = getPackageUid(
13955                mIntentFilterVerifierComponent.getPackageName(),
13956                MATCH_DEBUG_TRIAGED_MISSING,
13957                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13958
13959        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13960        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13961        mHandler.sendMessage(msg);
13962
13963        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13964        for (int i = 0; i < childCount; i++) {
13965            PackageParser.Package childPkg = pkg.childPackages.get(i);
13966            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13967            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13968            mHandler.sendMessage(msg);
13969        }
13970    }
13971
13972    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13973            PackageParser.Package pkg) {
13974        int size = pkg.activities.size();
13975        if (size == 0) {
13976            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13977                    "No activity, so no need to verify any IntentFilter!");
13978            return;
13979        }
13980
13981        final boolean hasDomainURLs = hasDomainURLs(pkg);
13982        if (!hasDomainURLs) {
13983            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13984                    "No domain URLs, so no need to verify any IntentFilter!");
13985            return;
13986        }
13987
13988        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13989                + " if any IntentFilter from the " + size
13990                + " Activities needs verification ...");
13991
13992        int count = 0;
13993        final String packageName = pkg.packageName;
13994
13995        synchronized (mPackages) {
13996            // If this is a new install and we see that we've already run verification for this
13997            // package, we have nothing to do: it means the state was restored from backup.
13998            if (!replacing) {
13999                IntentFilterVerificationInfo ivi =
14000                        mSettings.getIntentFilterVerificationLPr(packageName);
14001                if (ivi != null) {
14002                    if (DEBUG_DOMAIN_VERIFICATION) {
14003                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14004                                + ivi.getStatusString());
14005                    }
14006                    return;
14007                }
14008            }
14009
14010            // If any filters need to be verified, then all need to be.
14011            boolean needToVerify = false;
14012            for (PackageParser.Activity a : pkg.activities) {
14013                for (ActivityIntentInfo filter : a.intents) {
14014                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14015                        if (DEBUG_DOMAIN_VERIFICATION) {
14016                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14017                        }
14018                        needToVerify = true;
14019                        break;
14020                    }
14021                }
14022            }
14023
14024            if (needToVerify) {
14025                final int verificationId = mIntentFilterVerificationToken++;
14026                for (PackageParser.Activity a : pkg.activities) {
14027                    for (ActivityIntentInfo filter : a.intents) {
14028                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14029                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14030                                    "Verification needed for IntentFilter:" + filter.toString());
14031                            mIntentFilterVerifier.addOneIntentFilterVerification(
14032                                    verifierUid, userId, verificationId, filter, packageName);
14033                            count++;
14034                        }
14035                    }
14036                }
14037            }
14038        }
14039
14040        if (count > 0) {
14041            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14042                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14043                    +  " for userId:" + userId);
14044            mIntentFilterVerifier.startVerifications(userId);
14045        } else {
14046            if (DEBUG_DOMAIN_VERIFICATION) {
14047                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14048            }
14049        }
14050    }
14051
14052    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14053        final ComponentName cn  = filter.activity.getComponentName();
14054        final String packageName = cn.getPackageName();
14055
14056        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14057                packageName);
14058        if (ivi == null) {
14059            return true;
14060        }
14061        int status = ivi.getStatus();
14062        switch (status) {
14063            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14064            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14065                return true;
14066
14067            default:
14068                // Nothing to do
14069                return false;
14070        }
14071    }
14072
14073    private static boolean isMultiArch(ApplicationInfo info) {
14074        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14075    }
14076
14077    private static boolean isExternal(PackageParser.Package pkg) {
14078        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14079    }
14080
14081    private static boolean isExternal(PackageSetting ps) {
14082        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14083    }
14084
14085    private static boolean isEphemeral(PackageParser.Package pkg) {
14086        return pkg.applicationInfo.isEphemeralApp();
14087    }
14088
14089    private static boolean isEphemeral(PackageSetting ps) {
14090        return ps.pkg != null && isEphemeral(ps.pkg);
14091    }
14092
14093    private static boolean isSystemApp(PackageParser.Package pkg) {
14094        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14095    }
14096
14097    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14098        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14099    }
14100
14101    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14102        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14103    }
14104
14105    private static boolean isSystemApp(PackageSetting ps) {
14106        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14107    }
14108
14109    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14110        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14111    }
14112
14113    private int packageFlagsToInstallFlags(PackageSetting ps) {
14114        int installFlags = 0;
14115        if (isEphemeral(ps)) {
14116            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14117        }
14118        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14119            // This existing package was an external ASEC install when we have
14120            // the external flag without a UUID
14121            installFlags |= PackageManager.INSTALL_EXTERNAL;
14122        }
14123        if (ps.isForwardLocked()) {
14124            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14125        }
14126        return installFlags;
14127    }
14128
14129    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14130        if (isExternal(pkg)) {
14131            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14132                return StorageManager.UUID_PRIMARY_PHYSICAL;
14133            } else {
14134                return pkg.volumeUuid;
14135            }
14136        } else {
14137            return StorageManager.UUID_PRIVATE_INTERNAL;
14138        }
14139    }
14140
14141    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14142        if (isExternal(pkg)) {
14143            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14144                return mSettings.getExternalVersion();
14145            } else {
14146                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14147            }
14148        } else {
14149            return mSettings.getInternalVersion();
14150        }
14151    }
14152
14153    private void deleteTempPackageFiles() {
14154        final FilenameFilter filter = new FilenameFilter() {
14155            public boolean accept(File dir, String name) {
14156                return name.startsWith("vmdl") && name.endsWith(".tmp");
14157            }
14158        };
14159        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14160            file.delete();
14161        }
14162    }
14163
14164    @Override
14165    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14166            int flags) {
14167        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14168                flags);
14169    }
14170
14171    @Override
14172    public void deletePackage(final String packageName,
14173            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14174        mContext.enforceCallingOrSelfPermission(
14175                android.Manifest.permission.DELETE_PACKAGES, null);
14176        Preconditions.checkNotNull(packageName);
14177        Preconditions.checkNotNull(observer);
14178        final int uid = Binder.getCallingUid();
14179        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14180        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14181        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14182            mContext.enforceCallingOrSelfPermission(
14183                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14184                    "deletePackage for user " + userId);
14185        }
14186
14187        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14188            try {
14189                observer.onPackageDeleted(packageName,
14190                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14191            } catch (RemoteException re) {
14192            }
14193            return;
14194        }
14195
14196        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14197            try {
14198                observer.onPackageDeleted(packageName,
14199                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14200            } catch (RemoteException re) {
14201            }
14202            return;
14203        }
14204
14205        if (DEBUG_REMOVE) {
14206            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14207                    + " deleteAllUsers: " + deleteAllUsers );
14208        }
14209        // Queue up an async operation since the package deletion may take a little while.
14210        mHandler.post(new Runnable() {
14211            public void run() {
14212                mHandler.removeCallbacks(this);
14213                int returnCode;
14214                if (!deleteAllUsers) {
14215                    returnCode = deletePackageX(packageName, userId, flags);
14216                } else {
14217                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14218                    // If nobody is blocking uninstall, proceed with delete for all users
14219                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14220                        returnCode = deletePackageX(packageName, userId, flags);
14221                    } else {
14222                        // Otherwise uninstall individually for users with blockUninstalls=false
14223                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14224                        for (int userId : users) {
14225                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14226                                returnCode = deletePackageX(packageName, userId, userFlags);
14227                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14228                                    Slog.w(TAG, "Package delete failed for user " + userId
14229                                            + ", returnCode " + returnCode);
14230                                }
14231                            }
14232                        }
14233                        // The app has only been marked uninstalled for certain users.
14234                        // We still need to report that delete was blocked
14235                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14236                    }
14237                }
14238                try {
14239                    observer.onPackageDeleted(packageName, returnCode, null);
14240                } catch (RemoteException e) {
14241                    Log.i(TAG, "Observer no longer exists.");
14242                } //end catch
14243            } //end run
14244        });
14245    }
14246
14247    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14248        int[] result = EMPTY_INT_ARRAY;
14249        for (int userId : userIds) {
14250            if (getBlockUninstallForUser(packageName, userId)) {
14251                result = ArrayUtils.appendInt(result, userId);
14252            }
14253        }
14254        return result;
14255    }
14256
14257    @Override
14258    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14259        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14260    }
14261
14262    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14263        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14264                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14265        try {
14266            if (dpm != null) {
14267                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14268                        /* callingUserOnly =*/ false);
14269                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14270                        : deviceOwnerComponentName.getPackageName();
14271                // Does the package contains the device owner?
14272                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14273                // this check is probably not needed, since DO should be registered as a device
14274                // admin on some user too. (Original bug for this: b/17657954)
14275                if (packageName.equals(deviceOwnerPackageName)) {
14276                    return true;
14277                }
14278                // Does it contain a device admin for any user?
14279                int[] users;
14280                if (userId == UserHandle.USER_ALL) {
14281                    users = sUserManager.getUserIds();
14282                } else {
14283                    users = new int[]{userId};
14284                }
14285                for (int i = 0; i < users.length; ++i) {
14286                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14287                        return true;
14288                    }
14289                }
14290            }
14291        } catch (RemoteException e) {
14292        }
14293        return false;
14294    }
14295
14296    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14297        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14298    }
14299
14300    /**
14301     *  This method is an internal method that could be get invoked either
14302     *  to delete an installed package or to clean up a failed installation.
14303     *  After deleting an installed package, a broadcast is sent to notify any
14304     *  listeners that the package has been installed. For cleaning up a failed
14305     *  installation, the broadcast is not necessary since the package's
14306     *  installation wouldn't have sent the initial broadcast either
14307     *  The key steps in deleting a package are
14308     *  deleting the package information in internal structures like mPackages,
14309     *  deleting the packages base directories through installd
14310     *  updating mSettings to reflect current status
14311     *  persisting settings for later use
14312     *  sending a broadcast if necessary
14313     */
14314    private int deletePackageX(String packageName, int userId, int flags) {
14315        final PackageRemovedInfo info = new PackageRemovedInfo();
14316        final boolean res;
14317
14318        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14319                ? UserHandle.ALL : new UserHandle(userId);
14320
14321        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14322            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14323            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14324        }
14325
14326        PackageSetting uninstalledPs = null;
14327
14328        // for the uninstall-updates case and restricted profiles, remember the per-
14329        // user handle installed state
14330        int[] allUsers;
14331        synchronized (mPackages) {
14332            uninstalledPs = mSettings.mPackages.get(packageName);
14333            if (uninstalledPs == null) {
14334                Slog.w(TAG, "Not removing non-existent package " + packageName);
14335                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14336            }
14337            allUsers = sUserManager.getUserIds();
14338            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14339        }
14340
14341        synchronized (mInstallLock) {
14342            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14343            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14344                    flags | REMOVE_CHATTY, info, true, null);
14345            synchronized (mPackages) {
14346                if (res) {
14347                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14348                }
14349            }
14350        }
14351
14352        if (res) {
14353            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14354            info.sendPackageRemovedBroadcasts(killApp);
14355            info.sendSystemPackageUpdatedBroadcasts();
14356            info.sendSystemPackageAppearedBroadcasts();
14357        }
14358        // Force a gc here.
14359        Runtime.getRuntime().gc();
14360        // Delete the resources here after sending the broadcast to let
14361        // other processes clean up before deleting resources.
14362        if (info.args != null) {
14363            synchronized (mInstallLock) {
14364                info.args.doPostDeleteLI(true);
14365            }
14366        }
14367
14368        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14369    }
14370
14371    class PackageRemovedInfo {
14372        String removedPackage;
14373        int uid = -1;
14374        int removedAppId = -1;
14375        int[] origUsers;
14376        int[] removedUsers = null;
14377        boolean isRemovedPackageSystemUpdate = false;
14378        boolean isUpdate;
14379        boolean dataRemoved;
14380        boolean removedForAllUsers;
14381        // Clean up resources deleted packages.
14382        InstallArgs args = null;
14383        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14384        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14385
14386        void sendPackageRemovedBroadcasts(boolean killApp) {
14387            sendPackageRemovedBroadcastInternal(killApp);
14388            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14389            for (int i = 0; i < childCount; i++) {
14390                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14391                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14392            }
14393        }
14394
14395        void sendSystemPackageUpdatedBroadcasts() {
14396            if (isRemovedPackageSystemUpdate) {
14397                sendSystemPackageUpdatedBroadcastsInternal();
14398                final int childCount = (removedChildPackages != null)
14399                        ? removedChildPackages.size() : 0;
14400                for (int i = 0; i < childCount; i++) {
14401                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14402                    if (childInfo.isRemovedPackageSystemUpdate) {
14403                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14404                    }
14405                }
14406            }
14407        }
14408
14409        void sendSystemPackageAppearedBroadcasts() {
14410            final int packageCount = (appearedChildPackages != null)
14411                    ? appearedChildPackages.size() : 0;
14412            for (int i = 0; i < packageCount; i++) {
14413                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14414                for (int userId : installedInfo.newUsers) {
14415                    sendPackageAddedForUser(installedInfo.name, true,
14416                            UserHandle.getAppId(installedInfo.uid), userId);
14417                }
14418            }
14419        }
14420
14421        private void sendSystemPackageUpdatedBroadcastsInternal() {
14422            Bundle extras = new Bundle(2);
14423            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14424            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14425            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14426                    extras, 0, null, null, null);
14427            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14428                    extras, 0, null, null, null);
14429            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14430                    null, 0, removedPackage, null, null);
14431        }
14432
14433        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14434            Bundle extras = new Bundle(2);
14435            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14436            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14437            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14438            if (isUpdate || isRemovedPackageSystemUpdate) {
14439                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14440            }
14441            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14442            if (removedPackage != null) {
14443                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14444                        extras, 0, null, null, removedUsers);
14445                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14446                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14447                            removedPackage, extras, 0, null, null, removedUsers);
14448                }
14449            }
14450            if (removedAppId >= 0) {
14451                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14452                        removedUsers);
14453            }
14454        }
14455    }
14456
14457    /*
14458     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14459     * flag is not set, the data directory is removed as well.
14460     * make sure this flag is set for partially installed apps. If not its meaningless to
14461     * delete a partially installed application.
14462     */
14463    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14464            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14465        String packageName = ps.name;
14466        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14467        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14468        // Retrieve object to delete permissions for shared user later on
14469        final PackageSetting deletedPs;
14470        // reader
14471        synchronized (mPackages) {
14472            deletedPs = mSettings.mPackages.get(packageName);
14473            if (outInfo != null) {
14474                outInfo.removedPackage = packageName;
14475                outInfo.removedUsers = deletedPs != null
14476                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14477                        : null;
14478            }
14479        }
14480        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14481            removeDataDirsLI(ps.volumeUuid, packageName);
14482            if (outInfo != null) {
14483                outInfo.dataRemoved = true;
14484            }
14485            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14486        }
14487        // writer
14488        synchronized (mPackages) {
14489            if (deletedPs != null) {
14490                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14491                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14492                    clearDefaultBrowserIfNeeded(packageName);
14493                    if (outInfo != null) {
14494                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14495                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14496                    }
14497                    updatePermissionsLPw(deletedPs.name, null, 0);
14498                    if (deletedPs.sharedUser != null) {
14499                        // Remove permissions associated with package. Since runtime
14500                        // permissions are per user we have to kill the removed package
14501                        // or packages running under the shared user of the removed
14502                        // package if revoking the permissions requested only by the removed
14503                        // package is successful and this causes a change in gids.
14504                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14505                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14506                                    userId);
14507                            if (userIdToKill == UserHandle.USER_ALL
14508                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14509                                // If gids changed for this user, kill all affected packages.
14510                                mHandler.post(new Runnable() {
14511                                    @Override
14512                                    public void run() {
14513                                        // This has to happen with no lock held.
14514                                        killApplication(deletedPs.name, deletedPs.appId,
14515                                                KILL_APP_REASON_GIDS_CHANGED);
14516                                    }
14517                                });
14518                                break;
14519                            }
14520                        }
14521                    }
14522                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14523                }
14524                // make sure to preserve per-user disabled state if this removal was just
14525                // a downgrade of a system app to the factory package
14526                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14527                    if (DEBUG_REMOVE) {
14528                        Slog.d(TAG, "Propagating install state across downgrade");
14529                    }
14530                    for (int userId : allUserHandles) {
14531                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14532                        if (DEBUG_REMOVE) {
14533                            Slog.d(TAG, "    user " + userId + " => " + installed);
14534                        }
14535                        ps.setInstalled(installed, userId);
14536                    }
14537                }
14538            }
14539            // can downgrade to reader
14540            if (writeSettings) {
14541                // Save settings now
14542                mSettings.writeLPr();
14543            }
14544        }
14545        if (outInfo != null) {
14546            // A user ID was deleted here. Go through all users and remove it
14547            // from KeyStore.
14548            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14549        }
14550    }
14551
14552    static boolean locationIsPrivileged(File path) {
14553        try {
14554            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14555                    .getCanonicalPath();
14556            return path.getCanonicalPath().startsWith(privilegedAppDir);
14557        } catch (IOException e) {
14558            Slog.e(TAG, "Unable to access code path " + path);
14559        }
14560        return false;
14561    }
14562
14563    /*
14564     * Tries to delete system package.
14565     */
14566    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14567            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14568            boolean writeSettings) {
14569        if (deletedPs.parentPackageName != null) {
14570            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14571            return false;
14572        }
14573
14574        final boolean applyUserRestrictions
14575                = (allUserHandles != null) && (outInfo.origUsers != null);
14576        final PackageSetting disabledPs;
14577        // Confirm if the system package has been updated
14578        // An updated system app can be deleted. This will also have to restore
14579        // the system pkg from system partition
14580        // reader
14581        synchronized (mPackages) {
14582            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14583        }
14584
14585        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14586                + " disabledPs=" + disabledPs);
14587
14588        if (disabledPs == null) {
14589            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14590            return false;
14591        } else if (DEBUG_REMOVE) {
14592            Slog.d(TAG, "Deleting system pkg from data partition");
14593        }
14594
14595        if (DEBUG_REMOVE) {
14596            if (applyUserRestrictions) {
14597                Slog.d(TAG, "Remembering install states:");
14598                for (int userId : allUserHandles) {
14599                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14600                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14601                }
14602            }
14603        }
14604
14605        // Delete the updated package
14606        outInfo.isRemovedPackageSystemUpdate = true;
14607        if (outInfo.removedChildPackages != null) {
14608            final int childCount = (deletedPs.childPackageNames != null)
14609                    ? deletedPs.childPackageNames.size() : 0;
14610            for (int i = 0; i < childCount; i++) {
14611                String childPackageName = deletedPs.childPackageNames.get(i);
14612                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14613                        .contains(childPackageName)) {
14614                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14615                            childPackageName);
14616                    if (childInfo != null) {
14617                        childInfo.isRemovedPackageSystemUpdate = true;
14618                    }
14619                }
14620            }
14621        }
14622
14623        if (disabledPs.versionCode < deletedPs.versionCode) {
14624            // Delete data for downgrades
14625            flags &= ~PackageManager.DELETE_KEEP_DATA;
14626        } else {
14627            // Preserve data by setting flag
14628            flags |= PackageManager.DELETE_KEEP_DATA;
14629        }
14630
14631        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14632                outInfo, writeSettings, disabledPs.pkg);
14633        if (!ret) {
14634            return false;
14635        }
14636
14637        // writer
14638        synchronized (mPackages) {
14639            // Reinstate the old system package
14640            enableSystemPackageLPw(disabledPs.pkg);
14641            // Remove any native libraries from the upgraded package.
14642            removeNativeBinariesLI(deletedPs);
14643        }
14644
14645        // Install the system package
14646        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14647        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14648        if (locationIsPrivileged(disabledPs.codePath)) {
14649            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14650        }
14651
14652        final PackageParser.Package newPkg;
14653        try {
14654            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14655        } catch (PackageManagerException e) {
14656            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14657                    + e.getMessage());
14658            return false;
14659        }
14660
14661        prepareAppDataAfterInstall(newPkg);
14662
14663        // writer
14664        synchronized (mPackages) {
14665            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14666
14667            // Propagate the permissions state as we do not want to drop on the floor
14668            // runtime permissions. The update permissions method below will take
14669            // care of removing obsolete permissions and grant install permissions.
14670            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14671            updatePermissionsLPw(newPkg.packageName, newPkg,
14672                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14673
14674            if (applyUserRestrictions) {
14675                if (DEBUG_REMOVE) {
14676                    Slog.d(TAG, "Propagating install state across reinstall");
14677                }
14678                for (int userId : allUserHandles) {
14679                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14680                    if (DEBUG_REMOVE) {
14681                        Slog.d(TAG, "    user " + userId + " => " + installed);
14682                    }
14683                    ps.setInstalled(installed, userId);
14684
14685                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14686                }
14687                // Regardless of writeSettings we need to ensure that this restriction
14688                // state propagation is persisted
14689                mSettings.writeAllUsersPackageRestrictionsLPr();
14690            }
14691            // can downgrade to reader here
14692            if (writeSettings) {
14693                mSettings.writeLPr();
14694            }
14695        }
14696        return true;
14697    }
14698
14699    private boolean deleteInstalledPackageLI(PackageSetting ps,
14700            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14701            PackageRemovedInfo outInfo, boolean writeSettings,
14702            PackageParser.Package replacingPackage) {
14703        synchronized (mPackages) {
14704            if (outInfo != null) {
14705                outInfo.uid = ps.appId;
14706            }
14707
14708            if (outInfo != null && outInfo.removedChildPackages != null) {
14709                final int childCount = (ps.childPackageNames != null)
14710                        ? ps.childPackageNames.size() : 0;
14711                for (int i = 0; i < childCount; i++) {
14712                    String childPackageName = ps.childPackageNames.get(i);
14713                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14714                    if (childPs == null) {
14715                        return false;
14716                    }
14717                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14718                            childPackageName);
14719                    if (childInfo != null) {
14720                        childInfo.uid = childPs.appId;
14721                    }
14722                }
14723            }
14724        }
14725
14726        // Delete package data from internal structures and also remove data if flag is set
14727        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14728
14729        // Delete the child packages data
14730        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14731        for (int i = 0; i < childCount; i++) {
14732            PackageSetting childPs;
14733            synchronized (mPackages) {
14734                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14735            }
14736            if (childPs != null) {
14737                PackageRemovedInfo childOutInfo = (outInfo != null
14738                        && outInfo.removedChildPackages != null)
14739                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14740                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14741                        && (replacingPackage != null
14742                        && !replacingPackage.hasChildPackage(childPs.name))
14743                        ? flags & ~DELETE_KEEP_DATA : flags;
14744                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14745                        deleteFlags, writeSettings);
14746            }
14747        }
14748
14749        // Delete application code and resources only for parent packages
14750        if (ps.parentPackageName == null) {
14751            if (deleteCodeAndResources && (outInfo != null)) {
14752                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14753                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14754                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14755            }
14756        }
14757
14758        return true;
14759    }
14760
14761    @Override
14762    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14763            int userId) {
14764        mContext.enforceCallingOrSelfPermission(
14765                android.Manifest.permission.DELETE_PACKAGES, null);
14766        synchronized (mPackages) {
14767            PackageSetting ps = mSettings.mPackages.get(packageName);
14768            if (ps == null) {
14769                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14770                return false;
14771            }
14772            if (!ps.getInstalled(userId)) {
14773                // Can't block uninstall for an app that is not installed or enabled.
14774                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14775                return false;
14776            }
14777            ps.setBlockUninstall(blockUninstall, userId);
14778            mSettings.writePackageRestrictionsLPr(userId);
14779        }
14780        return true;
14781    }
14782
14783    @Override
14784    public boolean getBlockUninstallForUser(String packageName, int userId) {
14785        synchronized (mPackages) {
14786            PackageSetting ps = mSettings.mPackages.get(packageName);
14787            if (ps == null) {
14788                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14789                return false;
14790            }
14791            return ps.getBlockUninstall(userId);
14792        }
14793    }
14794
14795    @Override
14796    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14797        int callingUid = Binder.getCallingUid();
14798        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14799            throw new SecurityException(
14800                    "setRequiredForSystemUser can only be run by the system or root");
14801        }
14802        synchronized (mPackages) {
14803            PackageSetting ps = mSettings.mPackages.get(packageName);
14804            if (ps == null) {
14805                Log.w(TAG, "Package doesn't exist: " + packageName);
14806                return false;
14807            }
14808            if (systemUserApp) {
14809                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14810            } else {
14811                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14812            }
14813            mSettings.writeLPr();
14814        }
14815        return true;
14816    }
14817
14818    /*
14819     * This method handles package deletion in general
14820     */
14821    private boolean deletePackageLI(String packageName, UserHandle user,
14822            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14823            PackageRemovedInfo outInfo, boolean writeSettings,
14824            PackageParser.Package replacingPackage) {
14825        if (packageName == null) {
14826            Slog.w(TAG, "Attempt to delete null packageName.");
14827            return false;
14828        }
14829
14830        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14831
14832        PackageSetting ps;
14833
14834        synchronized (mPackages) {
14835            ps = mSettings.mPackages.get(packageName);
14836            if (ps == null) {
14837                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14838                return false;
14839            }
14840
14841            if (ps.parentPackageName != null && (!isSystemApp(ps)
14842                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14843                if (DEBUG_REMOVE) {
14844                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14845                            + ((user == null) ? UserHandle.USER_ALL : user));
14846                }
14847                final int removedUserId = (user != null) ? user.getIdentifier()
14848                        : UserHandle.USER_ALL;
14849                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14850                    return false;
14851                }
14852                markPackageUninstalledForUserLPw(ps, user);
14853                scheduleWritePackageRestrictionsLocked(user);
14854                return true;
14855            }
14856        }
14857
14858        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14859                && user.getIdentifier() != UserHandle.USER_ALL)) {
14860            // The caller is asking that the package only be deleted for a single
14861            // user.  To do this, we just mark its uninstalled state and delete
14862            // its data. If this is a system app, we only allow this to happen if
14863            // they have set the special DELETE_SYSTEM_APP which requests different
14864            // semantics than normal for uninstalling system apps.
14865            markPackageUninstalledForUserLPw(ps, user);
14866
14867            if (!isSystemApp(ps)) {
14868                // Do not uninstall the APK if an app should be cached
14869                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14870                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14871                    // Other user still have this package installed, so all
14872                    // we need to do is clear this user's data and save that
14873                    // it is uninstalled.
14874                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14875                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14876                        return false;
14877                    }
14878                    scheduleWritePackageRestrictionsLocked(user);
14879                    return true;
14880                } else {
14881                    // We need to set it back to 'installed' so the uninstall
14882                    // broadcasts will be sent correctly.
14883                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14884                    ps.setInstalled(true, user.getIdentifier());
14885                }
14886            } else {
14887                // This is a system app, so we assume that the
14888                // other users still have this package installed, so all
14889                // we need to do is clear this user's data and save that
14890                // it is uninstalled.
14891                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14892                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14893                    return false;
14894                }
14895                scheduleWritePackageRestrictionsLocked(user);
14896                return true;
14897            }
14898        }
14899
14900        // If we are deleting a composite package for all users, keep track
14901        // of result for each child.
14902        if (ps.childPackageNames != null && outInfo != null) {
14903            synchronized (mPackages) {
14904                final int childCount = ps.childPackageNames.size();
14905                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14906                for (int i = 0; i < childCount; i++) {
14907                    String childPackageName = ps.childPackageNames.get(i);
14908                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14909                    childInfo.removedPackage = childPackageName;
14910                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14911                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14912                    if (childPs != null) {
14913                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14914                    }
14915                }
14916            }
14917        }
14918
14919        boolean ret = false;
14920        if (isSystemApp(ps)) {
14921            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14922            // When an updated system application is deleted we delete the existing resources
14923            // as well and fall back to existing code in system partition
14924            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14925        } else {
14926            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14927            // Kill application pre-emptively especially for apps on sd.
14928            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
14929            if (killApp) {
14930                killApplication(packageName, ps.appId, "uninstall pkg");
14931            }
14932            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
14933                    outInfo, writeSettings, replacingPackage);
14934        }
14935
14936        // Take a note whether we deleted the package for all users
14937        if (outInfo != null) {
14938            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14939            if (outInfo.removedChildPackages != null) {
14940                synchronized (mPackages) {
14941                    final int childCount = outInfo.removedChildPackages.size();
14942                    for (int i = 0; i < childCount; i++) {
14943                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14944                        if (childInfo != null) {
14945                            childInfo.removedForAllUsers = mPackages.get(
14946                                    childInfo.removedPackage) == null;
14947                        }
14948                    }
14949                }
14950            }
14951            // If we uninstalled an update to a system app there may be some
14952            // child packages that appeared as they are declared in the system
14953            // app but were not declared in the update.
14954            if (isSystemApp(ps)) {
14955                synchronized (mPackages) {
14956                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14957                    final int childCount = (updatedPs.childPackageNames != null)
14958                            ? updatedPs.childPackageNames.size() : 0;
14959                    for (int i = 0; i < childCount; i++) {
14960                        String childPackageName = updatedPs.childPackageNames.get(i);
14961                        if (outInfo.removedChildPackages == null
14962                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14963                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14964                            if (childPs == null) {
14965                                continue;
14966                            }
14967                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14968                            installRes.name = childPackageName;
14969                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14970                            installRes.pkg = mPackages.get(childPackageName);
14971                            installRes.uid = childPs.pkg.applicationInfo.uid;
14972                            if (outInfo.appearedChildPackages == null) {
14973                                outInfo.appearedChildPackages = new ArrayMap<>();
14974                            }
14975                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14976                        }
14977                    }
14978                }
14979            }
14980        }
14981
14982        return ret;
14983    }
14984
14985    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14986        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14987                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14988        for (int nextUserId : userIds) {
14989            if (DEBUG_REMOVE) {
14990                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14991            }
14992            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14993                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14994                    false /*hidden*/, false /*suspended*/, null, null, null,
14995                    false /*blockUninstall*/,
14996                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14997        }
14998    }
14999
15000    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15001            PackageRemovedInfo outInfo) {
15002        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15003                : new int[] {userId};
15004        for (int nextUserId : userIds) {
15005            if (DEBUG_REMOVE) {
15006                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15007                        + nextUserId);
15008            }
15009            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15010            try {
15011                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15012            } catch (InstallerException e) {
15013                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15014                return false;
15015            }
15016            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15017            schedulePackageCleaning(ps.name, nextUserId, false);
15018            synchronized (mPackages) {
15019                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15020                    scheduleWritePackageRestrictionsLocked(nextUserId);
15021                }
15022                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15023            }
15024        }
15025
15026        if (outInfo != null) {
15027            outInfo.removedPackage = ps.name;
15028            outInfo.removedAppId = ps.appId;
15029            outInfo.removedUsers = userIds;
15030        }
15031
15032        return true;
15033    }
15034
15035    private final class ClearStorageConnection implements ServiceConnection {
15036        IMediaContainerService mContainerService;
15037
15038        @Override
15039        public void onServiceConnected(ComponentName name, IBinder service) {
15040            synchronized (this) {
15041                mContainerService = IMediaContainerService.Stub.asInterface(service);
15042                notifyAll();
15043            }
15044        }
15045
15046        @Override
15047        public void onServiceDisconnected(ComponentName name) {
15048        }
15049    }
15050
15051    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15052        final boolean mounted;
15053        if (Environment.isExternalStorageEmulated()) {
15054            mounted = true;
15055        } else {
15056            final String status = Environment.getExternalStorageState();
15057
15058            mounted = status.equals(Environment.MEDIA_MOUNTED)
15059                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15060        }
15061
15062        if (!mounted) {
15063            return;
15064        }
15065
15066        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15067        int[] users;
15068        if (userId == UserHandle.USER_ALL) {
15069            users = sUserManager.getUserIds();
15070        } else {
15071            users = new int[] { userId };
15072        }
15073        final ClearStorageConnection conn = new ClearStorageConnection();
15074        if (mContext.bindServiceAsUser(
15075                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15076            try {
15077                for (int curUser : users) {
15078                    long timeout = SystemClock.uptimeMillis() + 5000;
15079                    synchronized (conn) {
15080                        long now = SystemClock.uptimeMillis();
15081                        while (conn.mContainerService == null && now < timeout) {
15082                            try {
15083                                conn.wait(timeout - now);
15084                            } catch (InterruptedException e) {
15085                            }
15086                        }
15087                    }
15088                    if (conn.mContainerService == null) {
15089                        return;
15090                    }
15091
15092                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15093                    clearDirectory(conn.mContainerService,
15094                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15095                    if (allData) {
15096                        clearDirectory(conn.mContainerService,
15097                                userEnv.buildExternalStorageAppDataDirs(packageName));
15098                        clearDirectory(conn.mContainerService,
15099                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15100                    }
15101                }
15102            } finally {
15103                mContext.unbindService(conn);
15104            }
15105        }
15106    }
15107
15108    @Override
15109    public void clearApplicationUserData(final String packageName,
15110            final IPackageDataObserver observer, final int userId) {
15111        mContext.enforceCallingOrSelfPermission(
15112                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15114                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15115        // Queue up an async operation since the package deletion may take a little while.
15116        mHandler.post(new Runnable() {
15117            public void run() {
15118                mHandler.removeCallbacks(this);
15119                final boolean succeeded;
15120                synchronized (mInstallLock) {
15121                    succeeded = clearApplicationUserDataLI(packageName, userId);
15122                }
15123                clearExternalStorageDataSync(packageName, userId, true);
15124                if (succeeded) {
15125                    // invoke DeviceStorageMonitor's update method to clear any notifications
15126                    DeviceStorageMonitorInternal
15127                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15128                    if (dsm != null) {
15129                        dsm.checkMemory();
15130                    }
15131                }
15132                if(observer != null) {
15133                    try {
15134                        observer.onRemoveCompleted(packageName, succeeded);
15135                    } catch (RemoteException e) {
15136                        Log.i(TAG, "Observer no longer exists.");
15137                    }
15138                } //end if observer
15139            } //end run
15140        });
15141    }
15142
15143    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15144        if (packageName == null) {
15145            Slog.w(TAG, "Attempt to delete null packageName.");
15146            return false;
15147        }
15148
15149        // Try finding details about the requested package
15150        PackageParser.Package pkg;
15151        synchronized (mPackages) {
15152            pkg = mPackages.get(packageName);
15153            if (pkg == null) {
15154                final PackageSetting ps = mSettings.mPackages.get(packageName);
15155                if (ps != null) {
15156                    pkg = ps.pkg;
15157                }
15158            }
15159
15160            if (pkg == null) {
15161                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15162                return false;
15163            }
15164
15165            PackageSetting ps = (PackageSetting) pkg.mExtras;
15166            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15167        }
15168
15169        // Always delete data directories for package, even if we found no other
15170        // record of app. This helps users recover from UID mismatches without
15171        // resorting to a full data wipe.
15172        // TODO: triage flags as part of 26466827
15173        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15174        try {
15175            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15176        } catch (InstallerException e) {
15177            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15178            return false;
15179        }
15180
15181        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15182        removeKeystoreDataIfNeeded(userId, appId);
15183
15184        // Create a native library symlink only if we have native libraries
15185        // and if the native libraries are 32 bit libraries. We do not provide
15186        // this symlink for 64 bit libraries.
15187        if (pkg.applicationInfo.primaryCpuAbi != null &&
15188                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15189            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15190            try {
15191                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15192                        nativeLibPath, userId);
15193            } catch (InstallerException e) {
15194                Slog.w(TAG, "Failed linking native library dir", e);
15195                return false;
15196            }
15197        }
15198
15199        return true;
15200    }
15201
15202    /**
15203     * Reverts user permission state changes (permissions and flags) in
15204     * all packages for a given user.
15205     *
15206     * @param userId The device user for which to do a reset.
15207     */
15208    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15209        final int packageCount = mPackages.size();
15210        for (int i = 0; i < packageCount; i++) {
15211            PackageParser.Package pkg = mPackages.valueAt(i);
15212            PackageSetting ps = (PackageSetting) pkg.mExtras;
15213            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15214        }
15215    }
15216
15217    /**
15218     * Reverts user permission state changes (permissions and flags).
15219     *
15220     * @param ps The package for which to reset.
15221     * @param userId The device user for which to do a reset.
15222     */
15223    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15224            final PackageSetting ps, final int userId) {
15225        if (ps.pkg == null) {
15226            return;
15227        }
15228
15229        // These are flags that can change base on user actions.
15230        final int userSettableMask = FLAG_PERMISSION_USER_SET
15231                | FLAG_PERMISSION_USER_FIXED
15232                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15233                | FLAG_PERMISSION_REVIEW_REQUIRED;
15234
15235        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15236                | FLAG_PERMISSION_POLICY_FIXED;
15237
15238        boolean writeInstallPermissions = false;
15239        boolean writeRuntimePermissions = false;
15240
15241        final int permissionCount = ps.pkg.requestedPermissions.size();
15242        for (int i = 0; i < permissionCount; i++) {
15243            String permission = ps.pkg.requestedPermissions.get(i);
15244
15245            BasePermission bp = mSettings.mPermissions.get(permission);
15246            if (bp == null) {
15247                continue;
15248            }
15249
15250            // If shared user we just reset the state to which only this app contributed.
15251            if (ps.sharedUser != null) {
15252                boolean used = false;
15253                final int packageCount = ps.sharedUser.packages.size();
15254                for (int j = 0; j < packageCount; j++) {
15255                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15256                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15257                            && pkg.pkg.requestedPermissions.contains(permission)) {
15258                        used = true;
15259                        break;
15260                    }
15261                }
15262                if (used) {
15263                    continue;
15264                }
15265            }
15266
15267            PermissionsState permissionsState = ps.getPermissionsState();
15268
15269            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15270
15271            // Always clear the user settable flags.
15272            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15273                    bp.name) != null;
15274            // If permission review is enabled and this is a legacy app, mark the
15275            // permission as requiring a review as this is the initial state.
15276            int flags = 0;
15277            if (Build.PERMISSIONS_REVIEW_REQUIRED
15278                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15279                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15280            }
15281            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15282                if (hasInstallState) {
15283                    writeInstallPermissions = true;
15284                } else {
15285                    writeRuntimePermissions = true;
15286                }
15287            }
15288
15289            // Below is only runtime permission handling.
15290            if (!bp.isRuntime()) {
15291                continue;
15292            }
15293
15294            // Never clobber system or policy.
15295            if ((oldFlags & policyOrSystemFlags) != 0) {
15296                continue;
15297            }
15298
15299            // If this permission was granted by default, make sure it is.
15300            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15301                if (permissionsState.grantRuntimePermission(bp, userId)
15302                        != PERMISSION_OPERATION_FAILURE) {
15303                    writeRuntimePermissions = true;
15304                }
15305            // If permission review is enabled the permissions for a legacy apps
15306            // are represented as constantly granted runtime ones, so don't revoke.
15307            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15308                // Otherwise, reset the permission.
15309                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15310                switch (revokeResult) {
15311                    case PERMISSION_OPERATION_SUCCESS: {
15312                        writeRuntimePermissions = true;
15313                    } break;
15314
15315                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15316                        writeRuntimePermissions = true;
15317                        final int appId = ps.appId;
15318                        mHandler.post(new Runnable() {
15319                            @Override
15320                            public void run() {
15321                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15322                            }
15323                        });
15324                    } break;
15325                }
15326            }
15327        }
15328
15329        // Synchronously write as we are taking permissions away.
15330        if (writeRuntimePermissions) {
15331            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15332        }
15333
15334        // Synchronously write as we are taking permissions away.
15335        if (writeInstallPermissions) {
15336            mSettings.writeLPr();
15337        }
15338    }
15339
15340    /**
15341     * Remove entries from the keystore daemon. Will only remove it if the
15342     * {@code appId} is valid.
15343     */
15344    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15345        if (appId < 0) {
15346            return;
15347        }
15348
15349        final KeyStore keyStore = KeyStore.getInstance();
15350        if (keyStore != null) {
15351            if (userId == UserHandle.USER_ALL) {
15352                for (final int individual : sUserManager.getUserIds()) {
15353                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15354                }
15355            } else {
15356                keyStore.clearUid(UserHandle.getUid(userId, appId));
15357            }
15358        } else {
15359            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15360        }
15361    }
15362
15363    @Override
15364    public void deleteApplicationCacheFiles(final String packageName,
15365            final IPackageDataObserver observer) {
15366        mContext.enforceCallingOrSelfPermission(
15367                android.Manifest.permission.DELETE_CACHE_FILES, null);
15368        // Queue up an async operation since the package deletion may take a little while.
15369        final int userId = UserHandle.getCallingUserId();
15370        mHandler.post(new Runnable() {
15371            public void run() {
15372                mHandler.removeCallbacks(this);
15373                final boolean succeded;
15374                synchronized (mInstallLock) {
15375                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15376                }
15377                clearExternalStorageDataSync(packageName, userId, false);
15378                if (observer != null) {
15379                    try {
15380                        observer.onRemoveCompleted(packageName, succeded);
15381                    } catch (RemoteException e) {
15382                        Log.i(TAG, "Observer no longer exists.");
15383                    }
15384                } //end if observer
15385            } //end run
15386        });
15387    }
15388
15389    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15390        if (packageName == null) {
15391            Slog.w(TAG, "Attempt to delete null packageName.");
15392            return false;
15393        }
15394        PackageParser.Package p;
15395        synchronized (mPackages) {
15396            p = mPackages.get(packageName);
15397        }
15398        if (p == null) {
15399            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15400            return false;
15401        }
15402        final ApplicationInfo applicationInfo = p.applicationInfo;
15403        if (applicationInfo == null) {
15404            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15405            return false;
15406        }
15407        // TODO: triage flags as part of 26466827
15408        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15409        try {
15410            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15411                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15412        } catch (InstallerException e) {
15413            Slog.w(TAG, "Couldn't remove cache files for package "
15414                    + packageName + " u" + userId, e);
15415            return false;
15416        }
15417        return true;
15418    }
15419
15420    @Override
15421    public void getPackageSizeInfo(final String packageName, int userHandle,
15422            final IPackageStatsObserver observer) {
15423        mContext.enforceCallingOrSelfPermission(
15424                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15425        if (packageName == null) {
15426            throw new IllegalArgumentException("Attempt to get size of null packageName");
15427        }
15428
15429        PackageStats stats = new PackageStats(packageName, userHandle);
15430
15431        /*
15432         * Queue up an async operation since the package measurement may take a
15433         * little while.
15434         */
15435        Message msg = mHandler.obtainMessage(INIT_COPY);
15436        msg.obj = new MeasureParams(stats, observer);
15437        mHandler.sendMessage(msg);
15438    }
15439
15440    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15441            PackageStats pStats) {
15442        if (packageName == null) {
15443            Slog.w(TAG, "Attempt to get size of null packageName.");
15444            return false;
15445        }
15446        PackageParser.Package p;
15447        boolean dataOnly = false;
15448        String libDirRoot = null;
15449        String asecPath = null;
15450        PackageSetting ps = null;
15451        synchronized (mPackages) {
15452            p = mPackages.get(packageName);
15453            ps = mSettings.mPackages.get(packageName);
15454            if(p == null) {
15455                dataOnly = true;
15456                if((ps == null) || (ps.pkg == null)) {
15457                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15458                    return false;
15459                }
15460                p = ps.pkg;
15461            }
15462            if (ps != null) {
15463                libDirRoot = ps.legacyNativeLibraryPathString;
15464            }
15465            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15466                final long token = Binder.clearCallingIdentity();
15467                try {
15468                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15469                    if (secureContainerId != null) {
15470                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15471                    }
15472                } finally {
15473                    Binder.restoreCallingIdentity(token);
15474                }
15475            }
15476        }
15477        String publicSrcDir = null;
15478        if(!dataOnly) {
15479            final ApplicationInfo applicationInfo = p.applicationInfo;
15480            if (applicationInfo == null) {
15481                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15482                return false;
15483            }
15484            if (p.isForwardLocked()) {
15485                publicSrcDir = applicationInfo.getBaseResourcePath();
15486            }
15487        }
15488        // TODO: extend to measure size of split APKs
15489        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15490        // not just the first level.
15491        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15492        // just the primary.
15493        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15494
15495        String apkPath;
15496        File packageDir = new File(p.codePath);
15497
15498        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15499            apkPath = packageDir.getAbsolutePath();
15500            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15501            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15502                libDirRoot = null;
15503            }
15504        } else {
15505            apkPath = p.baseCodePath;
15506        }
15507
15508        // TODO: triage flags as part of 26466827
15509        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15510        try {
15511            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15512                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15513        } catch (InstallerException e) {
15514            return false;
15515        }
15516
15517        // Fix-up for forward-locked applications in ASEC containers.
15518        if (!isExternal(p)) {
15519            pStats.codeSize += pStats.externalCodeSize;
15520            pStats.externalCodeSize = 0L;
15521        }
15522
15523        return true;
15524    }
15525
15526
15527    @Override
15528    public void addPackageToPreferred(String packageName) {
15529        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15530    }
15531
15532    @Override
15533    public void removePackageFromPreferred(String packageName) {
15534        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15535    }
15536
15537    @Override
15538    public List<PackageInfo> getPreferredPackages(int flags) {
15539        return new ArrayList<PackageInfo>();
15540    }
15541
15542    private int getUidTargetSdkVersionLockedLPr(int uid) {
15543        Object obj = mSettings.getUserIdLPr(uid);
15544        if (obj instanceof SharedUserSetting) {
15545            final SharedUserSetting sus = (SharedUserSetting) obj;
15546            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15547            final Iterator<PackageSetting> it = sus.packages.iterator();
15548            while (it.hasNext()) {
15549                final PackageSetting ps = it.next();
15550                if (ps.pkg != null) {
15551                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15552                    if (v < vers) vers = v;
15553                }
15554            }
15555            return vers;
15556        } else if (obj instanceof PackageSetting) {
15557            final PackageSetting ps = (PackageSetting) obj;
15558            if (ps.pkg != null) {
15559                return ps.pkg.applicationInfo.targetSdkVersion;
15560            }
15561        }
15562        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15563    }
15564
15565    @Override
15566    public void addPreferredActivity(IntentFilter filter, int match,
15567            ComponentName[] set, ComponentName activity, int userId) {
15568        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15569                "Adding preferred");
15570    }
15571
15572    private void addPreferredActivityInternal(IntentFilter filter, int match,
15573            ComponentName[] set, ComponentName activity, boolean always, int userId,
15574            String opname) {
15575        // writer
15576        int callingUid = Binder.getCallingUid();
15577        enforceCrossUserPermission(callingUid, userId,
15578                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15579        if (filter.countActions() == 0) {
15580            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15581            return;
15582        }
15583        synchronized (mPackages) {
15584            if (mContext.checkCallingOrSelfPermission(
15585                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15586                    != PackageManager.PERMISSION_GRANTED) {
15587                if (getUidTargetSdkVersionLockedLPr(callingUid)
15588                        < Build.VERSION_CODES.FROYO) {
15589                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15590                            + callingUid);
15591                    return;
15592                }
15593                mContext.enforceCallingOrSelfPermission(
15594                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15595            }
15596
15597            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15598            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15599                    + userId + ":");
15600            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15601            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15602            scheduleWritePackageRestrictionsLocked(userId);
15603        }
15604    }
15605
15606    @Override
15607    public void replacePreferredActivity(IntentFilter filter, int match,
15608            ComponentName[] set, ComponentName activity, int userId) {
15609        if (filter.countActions() != 1) {
15610            throw new IllegalArgumentException(
15611                    "replacePreferredActivity expects filter to have only 1 action.");
15612        }
15613        if (filter.countDataAuthorities() != 0
15614                || filter.countDataPaths() != 0
15615                || filter.countDataSchemes() > 1
15616                || filter.countDataTypes() != 0) {
15617            throw new IllegalArgumentException(
15618                    "replacePreferredActivity expects filter to have no data authorities, " +
15619                    "paths, or types; and at most one scheme.");
15620        }
15621
15622        final int callingUid = Binder.getCallingUid();
15623        enforceCrossUserPermission(callingUid, userId,
15624                true /* requireFullPermission */, false /* checkShell */,
15625                "replace preferred activity");
15626        synchronized (mPackages) {
15627            if (mContext.checkCallingOrSelfPermission(
15628                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15629                    != PackageManager.PERMISSION_GRANTED) {
15630                if (getUidTargetSdkVersionLockedLPr(callingUid)
15631                        < Build.VERSION_CODES.FROYO) {
15632                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15633                            + Binder.getCallingUid());
15634                    return;
15635                }
15636                mContext.enforceCallingOrSelfPermission(
15637                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15638            }
15639
15640            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15641            if (pir != null) {
15642                // Get all of the existing entries that exactly match this filter.
15643                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15644                if (existing != null && existing.size() == 1) {
15645                    PreferredActivity cur = existing.get(0);
15646                    if (DEBUG_PREFERRED) {
15647                        Slog.i(TAG, "Checking replace of preferred:");
15648                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15649                        if (!cur.mPref.mAlways) {
15650                            Slog.i(TAG, "  -- CUR; not mAlways!");
15651                        } else {
15652                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15653                            Slog.i(TAG, "  -- CUR: mSet="
15654                                    + Arrays.toString(cur.mPref.mSetComponents));
15655                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15656                            Slog.i(TAG, "  -- NEW: mMatch="
15657                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15658                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15659                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15660                        }
15661                    }
15662                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15663                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15664                            && cur.mPref.sameSet(set)) {
15665                        // Setting the preferred activity to what it happens to be already
15666                        if (DEBUG_PREFERRED) {
15667                            Slog.i(TAG, "Replacing with same preferred activity "
15668                                    + cur.mPref.mShortComponent + " for user "
15669                                    + userId + ":");
15670                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15671                        }
15672                        return;
15673                    }
15674                }
15675
15676                if (existing != null) {
15677                    if (DEBUG_PREFERRED) {
15678                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15679                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15680                    }
15681                    for (int i = 0; i < existing.size(); i++) {
15682                        PreferredActivity pa = existing.get(i);
15683                        if (DEBUG_PREFERRED) {
15684                            Slog.i(TAG, "Removing existing preferred activity "
15685                                    + pa.mPref.mComponent + ":");
15686                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15687                        }
15688                        pir.removeFilter(pa);
15689                    }
15690                }
15691            }
15692            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15693                    "Replacing preferred");
15694        }
15695    }
15696
15697    @Override
15698    public void clearPackagePreferredActivities(String packageName) {
15699        final int uid = Binder.getCallingUid();
15700        // writer
15701        synchronized (mPackages) {
15702            PackageParser.Package pkg = mPackages.get(packageName);
15703            if (pkg == null || pkg.applicationInfo.uid != uid) {
15704                if (mContext.checkCallingOrSelfPermission(
15705                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15706                        != PackageManager.PERMISSION_GRANTED) {
15707                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15708                            < Build.VERSION_CODES.FROYO) {
15709                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15710                                + Binder.getCallingUid());
15711                        return;
15712                    }
15713                    mContext.enforceCallingOrSelfPermission(
15714                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15715                }
15716            }
15717
15718            int user = UserHandle.getCallingUserId();
15719            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15720                scheduleWritePackageRestrictionsLocked(user);
15721            }
15722        }
15723    }
15724
15725    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15726    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15727        ArrayList<PreferredActivity> removed = null;
15728        boolean changed = false;
15729        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15730            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15731            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15732            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15733                continue;
15734            }
15735            Iterator<PreferredActivity> it = pir.filterIterator();
15736            while (it.hasNext()) {
15737                PreferredActivity pa = it.next();
15738                // Mark entry for removal only if it matches the package name
15739                // and the entry is of type "always".
15740                if (packageName == null ||
15741                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15742                                && pa.mPref.mAlways)) {
15743                    if (removed == null) {
15744                        removed = new ArrayList<PreferredActivity>();
15745                    }
15746                    removed.add(pa);
15747                }
15748            }
15749            if (removed != null) {
15750                for (int j=0; j<removed.size(); j++) {
15751                    PreferredActivity pa = removed.get(j);
15752                    pir.removeFilter(pa);
15753                }
15754                changed = true;
15755            }
15756        }
15757        return changed;
15758    }
15759
15760    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15761    private void clearIntentFilterVerificationsLPw(int userId) {
15762        final int packageCount = mPackages.size();
15763        for (int i = 0; i < packageCount; i++) {
15764            PackageParser.Package pkg = mPackages.valueAt(i);
15765            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15766        }
15767    }
15768
15769    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15770    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15771        if (userId == UserHandle.USER_ALL) {
15772            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15773                    sUserManager.getUserIds())) {
15774                for (int oneUserId : sUserManager.getUserIds()) {
15775                    scheduleWritePackageRestrictionsLocked(oneUserId);
15776                }
15777            }
15778        } else {
15779            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15780                scheduleWritePackageRestrictionsLocked(userId);
15781            }
15782        }
15783    }
15784
15785    void clearDefaultBrowserIfNeeded(String packageName) {
15786        for (int oneUserId : sUserManager.getUserIds()) {
15787            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15788            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15789            if (packageName.equals(defaultBrowserPackageName)) {
15790                setDefaultBrowserPackageName(null, oneUserId);
15791            }
15792        }
15793    }
15794
15795    @Override
15796    public void resetApplicationPreferences(int userId) {
15797        mContext.enforceCallingOrSelfPermission(
15798                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15799        // writer
15800        synchronized (mPackages) {
15801            final long identity = Binder.clearCallingIdentity();
15802            try {
15803                clearPackagePreferredActivitiesLPw(null, userId);
15804                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15805                // TODO: We have to reset the default SMS and Phone. This requires
15806                // significant refactoring to keep all default apps in the package
15807                // manager (cleaner but more work) or have the services provide
15808                // callbacks to the package manager to request a default app reset.
15809                applyFactoryDefaultBrowserLPw(userId);
15810                clearIntentFilterVerificationsLPw(userId);
15811                primeDomainVerificationsLPw(userId);
15812                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15813                scheduleWritePackageRestrictionsLocked(userId);
15814            } finally {
15815                Binder.restoreCallingIdentity(identity);
15816            }
15817        }
15818    }
15819
15820    @Override
15821    public int getPreferredActivities(List<IntentFilter> outFilters,
15822            List<ComponentName> outActivities, String packageName) {
15823
15824        int num = 0;
15825        final int userId = UserHandle.getCallingUserId();
15826        // reader
15827        synchronized (mPackages) {
15828            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15829            if (pir != null) {
15830                final Iterator<PreferredActivity> it = pir.filterIterator();
15831                while (it.hasNext()) {
15832                    final PreferredActivity pa = it.next();
15833                    if (packageName == null
15834                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15835                                    && pa.mPref.mAlways)) {
15836                        if (outFilters != null) {
15837                            outFilters.add(new IntentFilter(pa));
15838                        }
15839                        if (outActivities != null) {
15840                            outActivities.add(pa.mPref.mComponent);
15841                        }
15842                    }
15843                }
15844            }
15845        }
15846
15847        return num;
15848    }
15849
15850    @Override
15851    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15852            int userId) {
15853        int callingUid = Binder.getCallingUid();
15854        if (callingUid != Process.SYSTEM_UID) {
15855            throw new SecurityException(
15856                    "addPersistentPreferredActivity can only be run by the system");
15857        }
15858        if (filter.countActions() == 0) {
15859            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15860            return;
15861        }
15862        synchronized (mPackages) {
15863            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15864                    ":");
15865            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15866            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15867                    new PersistentPreferredActivity(filter, activity));
15868            scheduleWritePackageRestrictionsLocked(userId);
15869        }
15870    }
15871
15872    @Override
15873    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15874        int callingUid = Binder.getCallingUid();
15875        if (callingUid != Process.SYSTEM_UID) {
15876            throw new SecurityException(
15877                    "clearPackagePersistentPreferredActivities can only be run by the system");
15878        }
15879        ArrayList<PersistentPreferredActivity> removed = null;
15880        boolean changed = false;
15881        synchronized (mPackages) {
15882            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15883                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15884                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15885                        .valueAt(i);
15886                if (userId != thisUserId) {
15887                    continue;
15888                }
15889                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15890                while (it.hasNext()) {
15891                    PersistentPreferredActivity ppa = it.next();
15892                    // Mark entry for removal only if it matches the package name.
15893                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15894                        if (removed == null) {
15895                            removed = new ArrayList<PersistentPreferredActivity>();
15896                        }
15897                        removed.add(ppa);
15898                    }
15899                }
15900                if (removed != null) {
15901                    for (int j=0; j<removed.size(); j++) {
15902                        PersistentPreferredActivity ppa = removed.get(j);
15903                        ppir.removeFilter(ppa);
15904                    }
15905                    changed = true;
15906                }
15907            }
15908
15909            if (changed) {
15910                scheduleWritePackageRestrictionsLocked(userId);
15911            }
15912        }
15913    }
15914
15915    /**
15916     * Common machinery for picking apart a restored XML blob and passing
15917     * it to a caller-supplied functor to be applied to the running system.
15918     */
15919    private void restoreFromXml(XmlPullParser parser, int userId,
15920            String expectedStartTag, BlobXmlRestorer functor)
15921            throws IOException, XmlPullParserException {
15922        int type;
15923        while ((type = parser.next()) != XmlPullParser.START_TAG
15924                && type != XmlPullParser.END_DOCUMENT) {
15925        }
15926        if (type != XmlPullParser.START_TAG) {
15927            // oops didn't find a start tag?!
15928            if (DEBUG_BACKUP) {
15929                Slog.e(TAG, "Didn't find start tag during restore");
15930            }
15931            return;
15932        }
15933Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15934        // this is supposed to be TAG_PREFERRED_BACKUP
15935        if (!expectedStartTag.equals(parser.getName())) {
15936            if (DEBUG_BACKUP) {
15937                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15938            }
15939            return;
15940        }
15941
15942        // skip interfering stuff, then we're aligned with the backing implementation
15943        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15944Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15945        functor.apply(parser, userId);
15946    }
15947
15948    private interface BlobXmlRestorer {
15949        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15950    }
15951
15952    /**
15953     * Non-Binder method, support for the backup/restore mechanism: write the
15954     * full set of preferred activities in its canonical XML format.  Returns the
15955     * XML output as a byte array, or null if there is none.
15956     */
15957    @Override
15958    public byte[] getPreferredActivityBackup(int userId) {
15959        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15960            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15961        }
15962
15963        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15964        try {
15965            final XmlSerializer serializer = new FastXmlSerializer();
15966            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15967            serializer.startDocument(null, true);
15968            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15969
15970            synchronized (mPackages) {
15971                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15972            }
15973
15974            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15975            serializer.endDocument();
15976            serializer.flush();
15977        } catch (Exception e) {
15978            if (DEBUG_BACKUP) {
15979                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15980            }
15981            return null;
15982        }
15983
15984        return dataStream.toByteArray();
15985    }
15986
15987    @Override
15988    public void restorePreferredActivities(byte[] backup, int userId) {
15989        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15990            throw new SecurityException("Only the system may call restorePreferredActivities()");
15991        }
15992
15993        try {
15994            final XmlPullParser parser = Xml.newPullParser();
15995            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15996            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15997                    new BlobXmlRestorer() {
15998                        @Override
15999                        public void apply(XmlPullParser parser, int userId)
16000                                throws XmlPullParserException, IOException {
16001                            synchronized (mPackages) {
16002                                mSettings.readPreferredActivitiesLPw(parser, userId);
16003                            }
16004                        }
16005                    } );
16006        } catch (Exception e) {
16007            if (DEBUG_BACKUP) {
16008                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16009            }
16010        }
16011    }
16012
16013    /**
16014     * Non-Binder method, support for the backup/restore mechanism: write the
16015     * default browser (etc) settings in its canonical XML format.  Returns the default
16016     * browser XML representation as a byte array, or null if there is none.
16017     */
16018    @Override
16019    public byte[] getDefaultAppsBackup(int userId) {
16020        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16021            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16022        }
16023
16024        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16025        try {
16026            final XmlSerializer serializer = new FastXmlSerializer();
16027            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16028            serializer.startDocument(null, true);
16029            serializer.startTag(null, TAG_DEFAULT_APPS);
16030
16031            synchronized (mPackages) {
16032                mSettings.writeDefaultAppsLPr(serializer, userId);
16033            }
16034
16035            serializer.endTag(null, TAG_DEFAULT_APPS);
16036            serializer.endDocument();
16037            serializer.flush();
16038        } catch (Exception e) {
16039            if (DEBUG_BACKUP) {
16040                Slog.e(TAG, "Unable to write default apps for backup", e);
16041            }
16042            return null;
16043        }
16044
16045        return dataStream.toByteArray();
16046    }
16047
16048    @Override
16049    public void restoreDefaultApps(byte[] backup, int userId) {
16050        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16051            throw new SecurityException("Only the system may call restoreDefaultApps()");
16052        }
16053
16054        try {
16055            final XmlPullParser parser = Xml.newPullParser();
16056            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16057            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16058                    new BlobXmlRestorer() {
16059                        @Override
16060                        public void apply(XmlPullParser parser, int userId)
16061                                throws XmlPullParserException, IOException {
16062                            synchronized (mPackages) {
16063                                mSettings.readDefaultAppsLPw(parser, userId);
16064                            }
16065                        }
16066                    } );
16067        } catch (Exception e) {
16068            if (DEBUG_BACKUP) {
16069                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16070            }
16071        }
16072    }
16073
16074    @Override
16075    public byte[] getIntentFilterVerificationBackup(int userId) {
16076        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16077            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16078        }
16079
16080        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16081        try {
16082            final XmlSerializer serializer = new FastXmlSerializer();
16083            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16084            serializer.startDocument(null, true);
16085            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16086
16087            synchronized (mPackages) {
16088                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16089            }
16090
16091            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16092            serializer.endDocument();
16093            serializer.flush();
16094        } catch (Exception e) {
16095            if (DEBUG_BACKUP) {
16096                Slog.e(TAG, "Unable to write default apps for backup", e);
16097            }
16098            return null;
16099        }
16100
16101        return dataStream.toByteArray();
16102    }
16103
16104    @Override
16105    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16106        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16107            throw new SecurityException("Only the system may call restorePreferredActivities()");
16108        }
16109
16110        try {
16111            final XmlPullParser parser = Xml.newPullParser();
16112            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16113            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16114                    new BlobXmlRestorer() {
16115                        @Override
16116                        public void apply(XmlPullParser parser, int userId)
16117                                throws XmlPullParserException, IOException {
16118                            synchronized (mPackages) {
16119                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16120                                mSettings.writeLPr();
16121                            }
16122                        }
16123                    } );
16124        } catch (Exception e) {
16125            if (DEBUG_BACKUP) {
16126                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16127            }
16128        }
16129    }
16130
16131    @Override
16132    public byte[] getPermissionGrantBackup(int userId) {
16133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16134            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16135        }
16136
16137        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16138        try {
16139            final XmlSerializer serializer = new FastXmlSerializer();
16140            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16141            serializer.startDocument(null, true);
16142            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16143
16144            synchronized (mPackages) {
16145                serializeRuntimePermissionGrantsLPr(serializer, userId);
16146            }
16147
16148            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16149            serializer.endDocument();
16150            serializer.flush();
16151        } catch (Exception e) {
16152            if (DEBUG_BACKUP) {
16153                Slog.e(TAG, "Unable to write default apps for backup", e);
16154            }
16155            return null;
16156        }
16157
16158        return dataStream.toByteArray();
16159    }
16160
16161    @Override
16162    public void restorePermissionGrants(byte[] backup, int userId) {
16163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16164            throw new SecurityException("Only the system may call restorePermissionGrants()");
16165        }
16166
16167        try {
16168            final XmlPullParser parser = Xml.newPullParser();
16169            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16170            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16171                    new BlobXmlRestorer() {
16172                        @Override
16173                        public void apply(XmlPullParser parser, int userId)
16174                                throws XmlPullParserException, IOException {
16175                            synchronized (mPackages) {
16176                                processRestoredPermissionGrantsLPr(parser, userId);
16177                            }
16178                        }
16179                    } );
16180        } catch (Exception e) {
16181            if (DEBUG_BACKUP) {
16182                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16183            }
16184        }
16185    }
16186
16187    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16188            throws IOException {
16189        serializer.startTag(null, TAG_ALL_GRANTS);
16190
16191        final int N = mSettings.mPackages.size();
16192        for (int i = 0; i < N; i++) {
16193            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16194            boolean pkgGrantsKnown = false;
16195
16196            PermissionsState packagePerms = ps.getPermissionsState();
16197
16198            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16199                final int grantFlags = state.getFlags();
16200                // only look at grants that are not system/policy fixed
16201                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16202                    final boolean isGranted = state.isGranted();
16203                    // And only back up the user-twiddled state bits
16204                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16205                        final String packageName = mSettings.mPackages.keyAt(i);
16206                        if (!pkgGrantsKnown) {
16207                            serializer.startTag(null, TAG_GRANT);
16208                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16209                            pkgGrantsKnown = true;
16210                        }
16211
16212                        final boolean userSet =
16213                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16214                        final boolean userFixed =
16215                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16216                        final boolean revoke =
16217                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16218
16219                        serializer.startTag(null, TAG_PERMISSION);
16220                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16221                        if (isGranted) {
16222                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16223                        }
16224                        if (userSet) {
16225                            serializer.attribute(null, ATTR_USER_SET, "true");
16226                        }
16227                        if (userFixed) {
16228                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16229                        }
16230                        if (revoke) {
16231                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16232                        }
16233                        serializer.endTag(null, TAG_PERMISSION);
16234                    }
16235                }
16236            }
16237
16238            if (pkgGrantsKnown) {
16239                serializer.endTag(null, TAG_GRANT);
16240            }
16241        }
16242
16243        serializer.endTag(null, TAG_ALL_GRANTS);
16244    }
16245
16246    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16247            throws XmlPullParserException, IOException {
16248        String pkgName = null;
16249        int outerDepth = parser.getDepth();
16250        int type;
16251        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16252                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16253            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16254                continue;
16255            }
16256
16257            final String tagName = parser.getName();
16258            if (tagName.equals(TAG_GRANT)) {
16259                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16260                if (DEBUG_BACKUP) {
16261                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16262                }
16263            } else if (tagName.equals(TAG_PERMISSION)) {
16264
16265                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16266                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16267
16268                int newFlagSet = 0;
16269                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16270                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16271                }
16272                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16273                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16274                }
16275                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16276                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16277                }
16278                if (DEBUG_BACKUP) {
16279                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16280                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16281                }
16282                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16283                if (ps != null) {
16284                    // Already installed so we apply the grant immediately
16285                    if (DEBUG_BACKUP) {
16286                        Slog.v(TAG, "        + already installed; applying");
16287                    }
16288                    PermissionsState perms = ps.getPermissionsState();
16289                    BasePermission bp = mSettings.mPermissions.get(permName);
16290                    if (bp != null) {
16291                        if (isGranted) {
16292                            perms.grantRuntimePermission(bp, userId);
16293                        }
16294                        if (newFlagSet != 0) {
16295                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16296                        }
16297                    }
16298                } else {
16299                    // Need to wait for post-restore install to apply the grant
16300                    if (DEBUG_BACKUP) {
16301                        Slog.v(TAG, "        - not yet installed; saving for later");
16302                    }
16303                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16304                            isGranted, newFlagSet, userId);
16305                }
16306            } else {
16307                PackageManagerService.reportSettingsProblem(Log.WARN,
16308                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16309                XmlUtils.skipCurrentTag(parser);
16310            }
16311        }
16312
16313        scheduleWriteSettingsLocked();
16314        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16315    }
16316
16317    @Override
16318    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16319            int sourceUserId, int targetUserId, int flags) {
16320        mContext.enforceCallingOrSelfPermission(
16321                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16322        int callingUid = Binder.getCallingUid();
16323        enforceOwnerRights(ownerPackage, callingUid);
16324        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16325        if (intentFilter.countActions() == 0) {
16326            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16327            return;
16328        }
16329        synchronized (mPackages) {
16330            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16331                    ownerPackage, targetUserId, flags);
16332            CrossProfileIntentResolver resolver =
16333                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16334            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16335            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16336            if (existing != null) {
16337                int size = existing.size();
16338                for (int i = 0; i < size; i++) {
16339                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16340                        return;
16341                    }
16342                }
16343            }
16344            resolver.addFilter(newFilter);
16345            scheduleWritePackageRestrictionsLocked(sourceUserId);
16346        }
16347    }
16348
16349    @Override
16350    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16351        mContext.enforceCallingOrSelfPermission(
16352                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16353        int callingUid = Binder.getCallingUid();
16354        enforceOwnerRights(ownerPackage, callingUid);
16355        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16356        synchronized (mPackages) {
16357            CrossProfileIntentResolver resolver =
16358                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16359            ArraySet<CrossProfileIntentFilter> set =
16360                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16361            for (CrossProfileIntentFilter filter : set) {
16362                if (filter.getOwnerPackage().equals(ownerPackage)) {
16363                    resolver.removeFilter(filter);
16364                }
16365            }
16366            scheduleWritePackageRestrictionsLocked(sourceUserId);
16367        }
16368    }
16369
16370    // Enforcing that callingUid is owning pkg on userId
16371    private void enforceOwnerRights(String pkg, int callingUid) {
16372        // The system owns everything.
16373        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16374            return;
16375        }
16376        int callingUserId = UserHandle.getUserId(callingUid);
16377        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16378        if (pi == null) {
16379            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16380                    + callingUserId);
16381        }
16382        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16383            throw new SecurityException("Calling uid " + callingUid
16384                    + " does not own package " + pkg);
16385        }
16386    }
16387
16388    @Override
16389    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16390        Intent intent = new Intent(Intent.ACTION_MAIN);
16391        intent.addCategory(Intent.CATEGORY_HOME);
16392
16393        final int callingUserId = UserHandle.getCallingUserId();
16394        List<ResolveInfo> list = queryIntentActivities(intent, null,
16395                PackageManager.GET_META_DATA, callingUserId);
16396        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16397                true, false, false, callingUserId);
16398
16399        allHomeCandidates.clear();
16400        if (list != null) {
16401            for (ResolveInfo ri : list) {
16402                allHomeCandidates.add(ri);
16403            }
16404        }
16405        return (preferred == null || preferred.activityInfo == null)
16406                ? null
16407                : new ComponentName(preferred.activityInfo.packageName,
16408                        preferred.activityInfo.name);
16409    }
16410
16411    @Override
16412    public void setApplicationEnabledSetting(String appPackageName,
16413            int newState, int flags, int userId, String callingPackage) {
16414        if (!sUserManager.exists(userId)) return;
16415        if (callingPackage == null) {
16416            callingPackage = Integer.toString(Binder.getCallingUid());
16417        }
16418        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16419    }
16420
16421    @Override
16422    public void setComponentEnabledSetting(ComponentName componentName,
16423            int newState, int flags, int userId) {
16424        if (!sUserManager.exists(userId)) return;
16425        setEnabledSetting(componentName.getPackageName(),
16426                componentName.getClassName(), newState, flags, userId, null);
16427    }
16428
16429    private void setEnabledSetting(final String packageName, String className, int newState,
16430            final int flags, int userId, String callingPackage) {
16431        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16432              || newState == COMPONENT_ENABLED_STATE_ENABLED
16433              || newState == COMPONENT_ENABLED_STATE_DISABLED
16434              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16435              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16436            throw new IllegalArgumentException("Invalid new component state: "
16437                    + newState);
16438        }
16439        PackageSetting pkgSetting;
16440        final int uid = Binder.getCallingUid();
16441        final int permission = mContext.checkCallingOrSelfPermission(
16442                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16443        enforceCrossUserPermission(uid, userId,
16444                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16445        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16446        boolean sendNow = false;
16447        boolean isApp = (className == null);
16448        String componentName = isApp ? packageName : className;
16449        int packageUid = -1;
16450        ArrayList<String> components;
16451
16452        // writer
16453        synchronized (mPackages) {
16454            pkgSetting = mSettings.mPackages.get(packageName);
16455            if (pkgSetting == null) {
16456                if (className == null) {
16457                    throw new IllegalArgumentException("Unknown package: " + packageName);
16458                }
16459                throw new IllegalArgumentException(
16460                        "Unknown component: " + packageName + "/" + className);
16461            }
16462            // Allow root and verify that userId is not being specified by a different user
16463            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16464                throw new SecurityException(
16465                        "Permission Denial: attempt to change component state from pid="
16466                        + Binder.getCallingPid()
16467                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16468            }
16469            if (className == null) {
16470                // We're dealing with an application/package level state change
16471                if (pkgSetting.getEnabled(userId) == newState) {
16472                    // Nothing to do
16473                    return;
16474                }
16475                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16476                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16477                    // Don't care about who enables an app.
16478                    callingPackage = null;
16479                }
16480                pkgSetting.setEnabled(newState, userId, callingPackage);
16481                // pkgSetting.pkg.mSetEnabled = newState;
16482            } else {
16483                // We're dealing with a component level state change
16484                // First, verify that this is a valid class name.
16485                PackageParser.Package pkg = pkgSetting.pkg;
16486                if (pkg == null || !pkg.hasComponentClassName(className)) {
16487                    if (pkg != null &&
16488                            pkg.applicationInfo.targetSdkVersion >=
16489                                    Build.VERSION_CODES.JELLY_BEAN) {
16490                        throw new IllegalArgumentException("Component class " + className
16491                                + " does not exist in " + packageName);
16492                    } else {
16493                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16494                                + className + " does not exist in " + packageName);
16495                    }
16496                }
16497                switch (newState) {
16498                case COMPONENT_ENABLED_STATE_ENABLED:
16499                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16500                        return;
16501                    }
16502                    break;
16503                case COMPONENT_ENABLED_STATE_DISABLED:
16504                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16505                        return;
16506                    }
16507                    break;
16508                case COMPONENT_ENABLED_STATE_DEFAULT:
16509                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16510                        return;
16511                    }
16512                    break;
16513                default:
16514                    Slog.e(TAG, "Invalid new component state: " + newState);
16515                    return;
16516                }
16517            }
16518            scheduleWritePackageRestrictionsLocked(userId);
16519            components = mPendingBroadcasts.get(userId, packageName);
16520            final boolean newPackage = components == null;
16521            if (newPackage) {
16522                components = new ArrayList<String>();
16523            }
16524            if (!components.contains(componentName)) {
16525                components.add(componentName);
16526            }
16527            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16528                sendNow = true;
16529                // Purge entry from pending broadcast list if another one exists already
16530                // since we are sending one right away.
16531                mPendingBroadcasts.remove(userId, packageName);
16532            } else {
16533                if (newPackage) {
16534                    mPendingBroadcasts.put(userId, packageName, components);
16535                }
16536                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16537                    // Schedule a message
16538                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16539                }
16540            }
16541        }
16542
16543        long callingId = Binder.clearCallingIdentity();
16544        try {
16545            if (sendNow) {
16546                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16547                sendPackageChangedBroadcast(packageName,
16548                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16549            }
16550        } finally {
16551            Binder.restoreCallingIdentity(callingId);
16552        }
16553    }
16554
16555    private void sendPackageChangedBroadcast(String packageName,
16556            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16557        if (DEBUG_INSTALL)
16558            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16559                    + componentNames);
16560        Bundle extras = new Bundle(4);
16561        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16562        String nameList[] = new String[componentNames.size()];
16563        componentNames.toArray(nameList);
16564        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16565        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16566        extras.putInt(Intent.EXTRA_UID, packageUid);
16567        // If this is not reporting a change of the overall package, then only send it
16568        // to registered receivers.  We don't want to launch a swath of apps for every
16569        // little component state change.
16570        final int flags = !componentNames.contains(packageName)
16571                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16572        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16573                new int[] {UserHandle.getUserId(packageUid)});
16574    }
16575
16576    @Override
16577    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16578        if (!sUserManager.exists(userId)) return;
16579        final int uid = Binder.getCallingUid();
16580        final int permission = mContext.checkCallingOrSelfPermission(
16581                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16582        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16583        enforceCrossUserPermission(uid, userId,
16584                true /* requireFullPermission */, true /* checkShell */, "stop package");
16585        // writer
16586        synchronized (mPackages) {
16587            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16588                    allowedByPermission, uid, userId)) {
16589                scheduleWritePackageRestrictionsLocked(userId);
16590            }
16591        }
16592    }
16593
16594    @Override
16595    public String getInstallerPackageName(String packageName) {
16596        // reader
16597        synchronized (mPackages) {
16598            return mSettings.getInstallerPackageNameLPr(packageName);
16599        }
16600    }
16601
16602    @Override
16603    public int getApplicationEnabledSetting(String packageName, int userId) {
16604        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16605        int uid = Binder.getCallingUid();
16606        enforceCrossUserPermission(uid, userId,
16607                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16608        // reader
16609        synchronized (mPackages) {
16610            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16611        }
16612    }
16613
16614    @Override
16615    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16616        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16617        int uid = Binder.getCallingUid();
16618        enforceCrossUserPermission(uid, userId,
16619                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16620        // reader
16621        synchronized (mPackages) {
16622            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16623        }
16624    }
16625
16626    @Override
16627    public void enterSafeMode() {
16628        enforceSystemOrRoot("Only the system can request entering safe mode");
16629
16630        if (!mSystemReady) {
16631            mSafeMode = true;
16632        }
16633    }
16634
16635    @Override
16636    public void systemReady() {
16637        mSystemReady = true;
16638
16639        // Read the compatibilty setting when the system is ready.
16640        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16641                mContext.getContentResolver(),
16642                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16643        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16644        if (DEBUG_SETTINGS) {
16645            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16646        }
16647
16648        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16649
16650        synchronized (mPackages) {
16651            // Verify that all of the preferred activity components actually
16652            // exist.  It is possible for applications to be updated and at
16653            // that point remove a previously declared activity component that
16654            // had been set as a preferred activity.  We try to clean this up
16655            // the next time we encounter that preferred activity, but it is
16656            // possible for the user flow to never be able to return to that
16657            // situation so here we do a sanity check to make sure we haven't
16658            // left any junk around.
16659            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16660            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16661                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16662                removed.clear();
16663                for (PreferredActivity pa : pir.filterSet()) {
16664                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16665                        removed.add(pa);
16666                    }
16667                }
16668                if (removed.size() > 0) {
16669                    for (int r=0; r<removed.size(); r++) {
16670                        PreferredActivity pa = removed.get(r);
16671                        Slog.w(TAG, "Removing dangling preferred activity: "
16672                                + pa.mPref.mComponent);
16673                        pir.removeFilter(pa);
16674                    }
16675                    mSettings.writePackageRestrictionsLPr(
16676                            mSettings.mPreferredActivities.keyAt(i));
16677                }
16678            }
16679
16680            for (int userId : UserManagerService.getInstance().getUserIds()) {
16681                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16682                    grantPermissionsUserIds = ArrayUtils.appendInt(
16683                            grantPermissionsUserIds, userId);
16684                }
16685            }
16686        }
16687        sUserManager.systemReady();
16688
16689        // If we upgraded grant all default permissions before kicking off.
16690        for (int userId : grantPermissionsUserIds) {
16691            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16692        }
16693
16694        // Kick off any messages waiting for system ready
16695        if (mPostSystemReadyMessages != null) {
16696            for (Message msg : mPostSystemReadyMessages) {
16697                msg.sendToTarget();
16698            }
16699            mPostSystemReadyMessages = null;
16700        }
16701
16702        // Watch for external volumes that come and go over time
16703        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16704        storage.registerListener(mStorageListener);
16705
16706        mInstallerService.systemReady();
16707        mPackageDexOptimizer.systemReady();
16708
16709        MountServiceInternal mountServiceInternal = LocalServices.getService(
16710                MountServiceInternal.class);
16711        mountServiceInternal.addExternalStoragePolicy(
16712                new MountServiceInternal.ExternalStorageMountPolicy() {
16713            @Override
16714            public int getMountMode(int uid, String packageName) {
16715                if (Process.isIsolated(uid)) {
16716                    return Zygote.MOUNT_EXTERNAL_NONE;
16717                }
16718                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16719                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16720                }
16721                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16722                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16723                }
16724                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16725                    return Zygote.MOUNT_EXTERNAL_READ;
16726                }
16727                return Zygote.MOUNT_EXTERNAL_WRITE;
16728            }
16729
16730            @Override
16731            public boolean hasExternalStorage(int uid, String packageName) {
16732                return true;
16733            }
16734        });
16735    }
16736
16737    @Override
16738    public boolean isSafeMode() {
16739        return mSafeMode;
16740    }
16741
16742    @Override
16743    public boolean hasSystemUidErrors() {
16744        return mHasSystemUidErrors;
16745    }
16746
16747    static String arrayToString(int[] array) {
16748        StringBuffer buf = new StringBuffer(128);
16749        buf.append('[');
16750        if (array != null) {
16751            for (int i=0; i<array.length; i++) {
16752                if (i > 0) buf.append(", ");
16753                buf.append(array[i]);
16754            }
16755        }
16756        buf.append(']');
16757        return buf.toString();
16758    }
16759
16760    static class DumpState {
16761        public static final int DUMP_LIBS = 1 << 0;
16762        public static final int DUMP_FEATURES = 1 << 1;
16763        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16764        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16765        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16766        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16767        public static final int DUMP_PERMISSIONS = 1 << 6;
16768        public static final int DUMP_PACKAGES = 1 << 7;
16769        public static final int DUMP_SHARED_USERS = 1 << 8;
16770        public static final int DUMP_MESSAGES = 1 << 9;
16771        public static final int DUMP_PROVIDERS = 1 << 10;
16772        public static final int DUMP_VERIFIERS = 1 << 11;
16773        public static final int DUMP_PREFERRED = 1 << 12;
16774        public static final int DUMP_PREFERRED_XML = 1 << 13;
16775        public static final int DUMP_KEYSETS = 1 << 14;
16776        public static final int DUMP_VERSION = 1 << 15;
16777        public static final int DUMP_INSTALLS = 1 << 16;
16778        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16779        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16780
16781        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16782
16783        private int mTypes;
16784
16785        private int mOptions;
16786
16787        private boolean mTitlePrinted;
16788
16789        private SharedUserSetting mSharedUser;
16790
16791        public boolean isDumping(int type) {
16792            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16793                return true;
16794            }
16795
16796            return (mTypes & type) != 0;
16797        }
16798
16799        public void setDump(int type) {
16800            mTypes |= type;
16801        }
16802
16803        public boolean isOptionEnabled(int option) {
16804            return (mOptions & option) != 0;
16805        }
16806
16807        public void setOptionEnabled(int option) {
16808            mOptions |= option;
16809        }
16810
16811        public boolean onTitlePrinted() {
16812            final boolean printed = mTitlePrinted;
16813            mTitlePrinted = true;
16814            return printed;
16815        }
16816
16817        public boolean getTitlePrinted() {
16818            return mTitlePrinted;
16819        }
16820
16821        public void setTitlePrinted(boolean enabled) {
16822            mTitlePrinted = enabled;
16823        }
16824
16825        public SharedUserSetting getSharedUser() {
16826            return mSharedUser;
16827        }
16828
16829        public void setSharedUser(SharedUserSetting user) {
16830            mSharedUser = user;
16831        }
16832    }
16833
16834    @Override
16835    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16836            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16837        (new PackageManagerShellCommand(this)).exec(
16838                this, in, out, err, args, resultReceiver);
16839    }
16840
16841    @Override
16842    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16843        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16844                != PackageManager.PERMISSION_GRANTED) {
16845            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16846                    + Binder.getCallingPid()
16847                    + ", uid=" + Binder.getCallingUid()
16848                    + " without permission "
16849                    + android.Manifest.permission.DUMP);
16850            return;
16851        }
16852
16853        DumpState dumpState = new DumpState();
16854        boolean fullPreferred = false;
16855        boolean checkin = false;
16856
16857        String packageName = null;
16858        ArraySet<String> permissionNames = null;
16859
16860        int opti = 0;
16861        while (opti < args.length) {
16862            String opt = args[opti];
16863            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16864                break;
16865            }
16866            opti++;
16867
16868            if ("-a".equals(opt)) {
16869                // Right now we only know how to print all.
16870            } else if ("-h".equals(opt)) {
16871                pw.println("Package manager dump options:");
16872                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16873                pw.println("    --checkin: dump for a checkin");
16874                pw.println("    -f: print details of intent filters");
16875                pw.println("    -h: print this help");
16876                pw.println("  cmd may be one of:");
16877                pw.println("    l[ibraries]: list known shared libraries");
16878                pw.println("    f[eatures]: list device features");
16879                pw.println("    k[eysets]: print known keysets");
16880                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16881                pw.println("    perm[issions]: dump permissions");
16882                pw.println("    permission [name ...]: dump declaration and use of given permission");
16883                pw.println("    pref[erred]: print preferred package settings");
16884                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16885                pw.println("    prov[iders]: dump content providers");
16886                pw.println("    p[ackages]: dump installed packages");
16887                pw.println("    s[hared-users]: dump shared user IDs");
16888                pw.println("    m[essages]: print collected runtime messages");
16889                pw.println("    v[erifiers]: print package verifier info");
16890                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16891                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16892                pw.println("    version: print database version info");
16893                pw.println("    write: write current settings now");
16894                pw.println("    installs: details about install sessions");
16895                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16896                pw.println("    <package.name>: info about given package");
16897                return;
16898            } else if ("--checkin".equals(opt)) {
16899                checkin = true;
16900            } else if ("-f".equals(opt)) {
16901                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16902            } else {
16903                pw.println("Unknown argument: " + opt + "; use -h for help");
16904            }
16905        }
16906
16907        // Is the caller requesting to dump a particular piece of data?
16908        if (opti < args.length) {
16909            String cmd = args[opti];
16910            opti++;
16911            // Is this a package name?
16912            if ("android".equals(cmd) || cmd.contains(".")) {
16913                packageName = cmd;
16914                // When dumping a single package, we always dump all of its
16915                // filter information since the amount of data will be reasonable.
16916                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16917            } else if ("check-permission".equals(cmd)) {
16918                if (opti >= args.length) {
16919                    pw.println("Error: check-permission missing permission argument");
16920                    return;
16921                }
16922                String perm = args[opti];
16923                opti++;
16924                if (opti >= args.length) {
16925                    pw.println("Error: check-permission missing package argument");
16926                    return;
16927                }
16928                String pkg = args[opti];
16929                opti++;
16930                int user = UserHandle.getUserId(Binder.getCallingUid());
16931                if (opti < args.length) {
16932                    try {
16933                        user = Integer.parseInt(args[opti]);
16934                    } catch (NumberFormatException e) {
16935                        pw.println("Error: check-permission user argument is not a number: "
16936                                + args[opti]);
16937                        return;
16938                    }
16939                }
16940                pw.println(checkPermission(perm, pkg, user));
16941                return;
16942            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16943                dumpState.setDump(DumpState.DUMP_LIBS);
16944            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16945                dumpState.setDump(DumpState.DUMP_FEATURES);
16946            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16947                if (opti >= args.length) {
16948                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16949                            | DumpState.DUMP_SERVICE_RESOLVERS
16950                            | DumpState.DUMP_RECEIVER_RESOLVERS
16951                            | DumpState.DUMP_CONTENT_RESOLVERS);
16952                } else {
16953                    while (opti < args.length) {
16954                        String name = args[opti];
16955                        if ("a".equals(name) || "activity".equals(name)) {
16956                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16957                        } else if ("s".equals(name) || "service".equals(name)) {
16958                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16959                        } else if ("r".equals(name) || "receiver".equals(name)) {
16960                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16961                        } else if ("c".equals(name) || "content".equals(name)) {
16962                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16963                        } else {
16964                            pw.println("Error: unknown resolver table type: " + name);
16965                            return;
16966                        }
16967                        opti++;
16968                    }
16969                }
16970            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16971                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16972            } else if ("permission".equals(cmd)) {
16973                if (opti >= args.length) {
16974                    pw.println("Error: permission requires permission name");
16975                    return;
16976                }
16977                permissionNames = new ArraySet<>();
16978                while (opti < args.length) {
16979                    permissionNames.add(args[opti]);
16980                    opti++;
16981                }
16982                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16983                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16984            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16985                dumpState.setDump(DumpState.DUMP_PREFERRED);
16986            } else if ("preferred-xml".equals(cmd)) {
16987                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16988                if (opti < args.length && "--full".equals(args[opti])) {
16989                    fullPreferred = true;
16990                    opti++;
16991                }
16992            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16993                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16994            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16995                dumpState.setDump(DumpState.DUMP_PACKAGES);
16996            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16997                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16998            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16999                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17000            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17001                dumpState.setDump(DumpState.DUMP_MESSAGES);
17002            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17003                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17004            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17005                    || "intent-filter-verifiers".equals(cmd)) {
17006                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17007            } else if ("version".equals(cmd)) {
17008                dumpState.setDump(DumpState.DUMP_VERSION);
17009            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17010                dumpState.setDump(DumpState.DUMP_KEYSETS);
17011            } else if ("installs".equals(cmd)) {
17012                dumpState.setDump(DumpState.DUMP_INSTALLS);
17013            } else if ("write".equals(cmd)) {
17014                synchronized (mPackages) {
17015                    mSettings.writeLPr();
17016                    pw.println("Settings written.");
17017                    return;
17018                }
17019            }
17020        }
17021
17022        if (checkin) {
17023            pw.println("vers,1");
17024        }
17025
17026        // reader
17027        synchronized (mPackages) {
17028            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17029                if (!checkin) {
17030                    if (dumpState.onTitlePrinted())
17031                        pw.println();
17032                    pw.println("Database versions:");
17033                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17034                }
17035            }
17036
17037            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17038                if (!checkin) {
17039                    if (dumpState.onTitlePrinted())
17040                        pw.println();
17041                    pw.println("Verifiers:");
17042                    pw.print("  Required: ");
17043                    pw.print(mRequiredVerifierPackage);
17044                    pw.print(" (uid=");
17045                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17046                            UserHandle.USER_SYSTEM));
17047                    pw.println(")");
17048                } else if (mRequiredVerifierPackage != null) {
17049                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17050                    pw.print(",");
17051                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17052                            UserHandle.USER_SYSTEM));
17053                }
17054            }
17055
17056            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17057                    packageName == null) {
17058                if (mIntentFilterVerifierComponent != null) {
17059                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17060                    if (!checkin) {
17061                        if (dumpState.onTitlePrinted())
17062                            pw.println();
17063                        pw.println("Intent Filter Verifier:");
17064                        pw.print("  Using: ");
17065                        pw.print(verifierPackageName);
17066                        pw.print(" (uid=");
17067                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17068                                UserHandle.USER_SYSTEM));
17069                        pw.println(")");
17070                    } else if (verifierPackageName != null) {
17071                        pw.print("ifv,"); pw.print(verifierPackageName);
17072                        pw.print(",");
17073                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17074                                UserHandle.USER_SYSTEM));
17075                    }
17076                } else {
17077                    pw.println();
17078                    pw.println("No Intent Filter Verifier available!");
17079                }
17080            }
17081
17082            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17083                boolean printedHeader = false;
17084                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17085                while (it.hasNext()) {
17086                    String name = it.next();
17087                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17088                    if (!checkin) {
17089                        if (!printedHeader) {
17090                            if (dumpState.onTitlePrinted())
17091                                pw.println();
17092                            pw.println("Libraries:");
17093                            printedHeader = true;
17094                        }
17095                        pw.print("  ");
17096                    } else {
17097                        pw.print("lib,");
17098                    }
17099                    pw.print(name);
17100                    if (!checkin) {
17101                        pw.print(" -> ");
17102                    }
17103                    if (ent.path != null) {
17104                        if (!checkin) {
17105                            pw.print("(jar) ");
17106                            pw.print(ent.path);
17107                        } else {
17108                            pw.print(",jar,");
17109                            pw.print(ent.path);
17110                        }
17111                    } else {
17112                        if (!checkin) {
17113                            pw.print("(apk) ");
17114                            pw.print(ent.apk);
17115                        } else {
17116                            pw.print(",apk,");
17117                            pw.print(ent.apk);
17118                        }
17119                    }
17120                    pw.println();
17121                }
17122            }
17123
17124            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17125                if (dumpState.onTitlePrinted())
17126                    pw.println();
17127                if (!checkin) {
17128                    pw.println("Features:");
17129                }
17130
17131                for (FeatureInfo feat : mAvailableFeatures.values()) {
17132                    if (checkin) {
17133                        pw.print("feat,");
17134                        pw.print(feat.name);
17135                        pw.print(",");
17136                        pw.println(feat.version);
17137                    } else {
17138                        pw.print("  ");
17139                        pw.print(feat.name);
17140                        if (feat.version > 0) {
17141                            pw.print(" version=");
17142                            pw.print(feat.version);
17143                        }
17144                        pw.println();
17145                    }
17146                }
17147            }
17148
17149            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17150                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17151                        : "Activity Resolver Table:", "  ", packageName,
17152                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17153                    dumpState.setTitlePrinted(true);
17154                }
17155            }
17156            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17157                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17158                        : "Receiver Resolver Table:", "  ", packageName,
17159                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17160                    dumpState.setTitlePrinted(true);
17161                }
17162            }
17163            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17164                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17165                        : "Service Resolver Table:", "  ", packageName,
17166                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17167                    dumpState.setTitlePrinted(true);
17168                }
17169            }
17170            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17171                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17172                        : "Provider Resolver Table:", "  ", packageName,
17173                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17174                    dumpState.setTitlePrinted(true);
17175                }
17176            }
17177
17178            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17179                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17180                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17181                    int user = mSettings.mPreferredActivities.keyAt(i);
17182                    if (pir.dump(pw,
17183                            dumpState.getTitlePrinted()
17184                                ? "\nPreferred Activities User " + user + ":"
17185                                : "Preferred Activities User " + user + ":", "  ",
17186                            packageName, true, false)) {
17187                        dumpState.setTitlePrinted(true);
17188                    }
17189                }
17190            }
17191
17192            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17193                pw.flush();
17194                FileOutputStream fout = new FileOutputStream(fd);
17195                BufferedOutputStream str = new BufferedOutputStream(fout);
17196                XmlSerializer serializer = new FastXmlSerializer();
17197                try {
17198                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17199                    serializer.startDocument(null, true);
17200                    serializer.setFeature(
17201                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17202                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17203                    serializer.endDocument();
17204                    serializer.flush();
17205                } catch (IllegalArgumentException e) {
17206                    pw.println("Failed writing: " + e);
17207                } catch (IllegalStateException e) {
17208                    pw.println("Failed writing: " + e);
17209                } catch (IOException e) {
17210                    pw.println("Failed writing: " + e);
17211                }
17212            }
17213
17214            if (!checkin
17215                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17216                    && packageName == null) {
17217                pw.println();
17218                int count = mSettings.mPackages.size();
17219                if (count == 0) {
17220                    pw.println("No applications!");
17221                    pw.println();
17222                } else {
17223                    final String prefix = "  ";
17224                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17225                    if (allPackageSettings.size() == 0) {
17226                        pw.println("No domain preferred apps!");
17227                        pw.println();
17228                    } else {
17229                        pw.println("App verification status:");
17230                        pw.println();
17231                        count = 0;
17232                        for (PackageSetting ps : allPackageSettings) {
17233                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17234                            if (ivi == null || ivi.getPackageName() == null) continue;
17235                            pw.println(prefix + "Package: " + ivi.getPackageName());
17236                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17237                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17238                            pw.println();
17239                            count++;
17240                        }
17241                        if (count == 0) {
17242                            pw.println(prefix + "No app verification established.");
17243                            pw.println();
17244                        }
17245                        for (int userId : sUserManager.getUserIds()) {
17246                            pw.println("App linkages for user " + userId + ":");
17247                            pw.println();
17248                            count = 0;
17249                            for (PackageSetting ps : allPackageSettings) {
17250                                final long status = ps.getDomainVerificationStatusForUser(userId);
17251                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17252                                    continue;
17253                                }
17254                                pw.println(prefix + "Package: " + ps.name);
17255                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17256                                String statusStr = IntentFilterVerificationInfo.
17257                                        getStatusStringFromValue(status);
17258                                pw.println(prefix + "Status:  " + statusStr);
17259                                pw.println();
17260                                count++;
17261                            }
17262                            if (count == 0) {
17263                                pw.println(prefix + "No configured app linkages.");
17264                                pw.println();
17265                            }
17266                        }
17267                    }
17268                }
17269            }
17270
17271            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17272                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17273                if (packageName == null && permissionNames == null) {
17274                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17275                        if (iperm == 0) {
17276                            if (dumpState.onTitlePrinted())
17277                                pw.println();
17278                            pw.println("AppOp Permissions:");
17279                        }
17280                        pw.print("  AppOp Permission ");
17281                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17282                        pw.println(":");
17283                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17284                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17285                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17286                        }
17287                    }
17288                }
17289            }
17290
17291            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17292                boolean printedSomething = false;
17293                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17294                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17295                        continue;
17296                    }
17297                    if (!printedSomething) {
17298                        if (dumpState.onTitlePrinted())
17299                            pw.println();
17300                        pw.println("Registered ContentProviders:");
17301                        printedSomething = true;
17302                    }
17303                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17304                    pw.print("    "); pw.println(p.toString());
17305                }
17306                printedSomething = false;
17307                for (Map.Entry<String, PackageParser.Provider> entry :
17308                        mProvidersByAuthority.entrySet()) {
17309                    PackageParser.Provider p = entry.getValue();
17310                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17311                        continue;
17312                    }
17313                    if (!printedSomething) {
17314                        if (dumpState.onTitlePrinted())
17315                            pw.println();
17316                        pw.println("ContentProvider Authorities:");
17317                        printedSomething = true;
17318                    }
17319                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17320                    pw.print("    "); pw.println(p.toString());
17321                    if (p.info != null && p.info.applicationInfo != null) {
17322                        final String appInfo = p.info.applicationInfo.toString();
17323                        pw.print("      applicationInfo="); pw.println(appInfo);
17324                    }
17325                }
17326            }
17327
17328            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17329                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17330            }
17331
17332            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17333                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17334            }
17335
17336            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17337                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17338            }
17339
17340            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17341                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17342            }
17343
17344            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17345                // XXX should handle packageName != null by dumping only install data that
17346                // the given package is involved with.
17347                if (dumpState.onTitlePrinted()) pw.println();
17348                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17349            }
17350
17351            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17352                if (dumpState.onTitlePrinted()) pw.println();
17353                mSettings.dumpReadMessagesLPr(pw, dumpState);
17354
17355                pw.println();
17356                pw.println("Package warning messages:");
17357                BufferedReader in = null;
17358                String line = null;
17359                try {
17360                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17361                    while ((line = in.readLine()) != null) {
17362                        if (line.contains("ignored: updated version")) continue;
17363                        pw.println(line);
17364                    }
17365                } catch (IOException ignored) {
17366                } finally {
17367                    IoUtils.closeQuietly(in);
17368                }
17369            }
17370
17371            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17372                BufferedReader in = null;
17373                String line = null;
17374                try {
17375                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17376                    while ((line = in.readLine()) != null) {
17377                        if (line.contains("ignored: updated version")) continue;
17378                        pw.print("msg,");
17379                        pw.println(line);
17380                    }
17381                } catch (IOException ignored) {
17382                } finally {
17383                    IoUtils.closeQuietly(in);
17384                }
17385            }
17386        }
17387    }
17388
17389    private String dumpDomainString(String packageName) {
17390        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17391        List<IntentFilter> filters = getAllIntentFilters(packageName);
17392
17393        ArraySet<String> result = new ArraySet<>();
17394        if (iviList.size() > 0) {
17395            for (IntentFilterVerificationInfo ivi : iviList) {
17396                for (String host : ivi.getDomains()) {
17397                    result.add(host);
17398                }
17399            }
17400        }
17401        if (filters != null && filters.size() > 0) {
17402            for (IntentFilter filter : filters) {
17403                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17404                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17405                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17406                    result.addAll(filter.getHostsList());
17407                }
17408            }
17409        }
17410
17411        StringBuilder sb = new StringBuilder(result.size() * 16);
17412        for (String domain : result) {
17413            if (sb.length() > 0) sb.append(" ");
17414            sb.append(domain);
17415        }
17416        return sb.toString();
17417    }
17418
17419    // ------- apps on sdcard specific code -------
17420    static final boolean DEBUG_SD_INSTALL = false;
17421
17422    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17423
17424    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17425
17426    private boolean mMediaMounted = false;
17427
17428    static String getEncryptKey() {
17429        try {
17430            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17431                    SD_ENCRYPTION_KEYSTORE_NAME);
17432            if (sdEncKey == null) {
17433                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17434                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17435                if (sdEncKey == null) {
17436                    Slog.e(TAG, "Failed to create encryption keys");
17437                    return null;
17438                }
17439            }
17440            return sdEncKey;
17441        } catch (NoSuchAlgorithmException nsae) {
17442            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17443            return null;
17444        } catch (IOException ioe) {
17445            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17446            return null;
17447        }
17448    }
17449
17450    /*
17451     * Update media status on PackageManager.
17452     */
17453    @Override
17454    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17455        int callingUid = Binder.getCallingUid();
17456        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17457            throw new SecurityException("Media status can only be updated by the system");
17458        }
17459        // reader; this apparently protects mMediaMounted, but should probably
17460        // be a different lock in that case.
17461        synchronized (mPackages) {
17462            Log.i(TAG, "Updating external media status from "
17463                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17464                    + (mediaStatus ? "mounted" : "unmounted"));
17465            if (DEBUG_SD_INSTALL)
17466                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17467                        + ", mMediaMounted=" + mMediaMounted);
17468            if (mediaStatus == mMediaMounted) {
17469                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17470                        : 0, -1);
17471                mHandler.sendMessage(msg);
17472                return;
17473            }
17474            mMediaMounted = mediaStatus;
17475        }
17476        // Queue up an async operation since the package installation may take a
17477        // little while.
17478        mHandler.post(new Runnable() {
17479            public void run() {
17480                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17481            }
17482        });
17483    }
17484
17485    /**
17486     * Called by MountService when the initial ASECs to scan are available.
17487     * Should block until all the ASEC containers are finished being scanned.
17488     */
17489    public void scanAvailableAsecs() {
17490        updateExternalMediaStatusInner(true, false, false);
17491    }
17492
17493    /*
17494     * Collect information of applications on external media, map them against
17495     * existing containers and update information based on current mount status.
17496     * Please note that we always have to report status if reportStatus has been
17497     * set to true especially when unloading packages.
17498     */
17499    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17500            boolean externalStorage) {
17501        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17502        int[] uidArr = EmptyArray.INT;
17503
17504        final String[] list = PackageHelper.getSecureContainerList();
17505        if (ArrayUtils.isEmpty(list)) {
17506            Log.i(TAG, "No secure containers found");
17507        } else {
17508            // Process list of secure containers and categorize them
17509            // as active or stale based on their package internal state.
17510
17511            // reader
17512            synchronized (mPackages) {
17513                for (String cid : list) {
17514                    // Leave stages untouched for now; installer service owns them
17515                    if (PackageInstallerService.isStageName(cid)) continue;
17516
17517                    if (DEBUG_SD_INSTALL)
17518                        Log.i(TAG, "Processing container " + cid);
17519                    String pkgName = getAsecPackageName(cid);
17520                    if (pkgName == null) {
17521                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17522                        continue;
17523                    }
17524                    if (DEBUG_SD_INSTALL)
17525                        Log.i(TAG, "Looking for pkg : " + pkgName);
17526
17527                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17528                    if (ps == null) {
17529                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17530                        continue;
17531                    }
17532
17533                    /*
17534                     * Skip packages that are not external if we're unmounting
17535                     * external storage.
17536                     */
17537                    if (externalStorage && !isMounted && !isExternal(ps)) {
17538                        continue;
17539                    }
17540
17541                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17542                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17543                    // The package status is changed only if the code path
17544                    // matches between settings and the container id.
17545                    if (ps.codePathString != null
17546                            && ps.codePathString.startsWith(args.getCodePath())) {
17547                        if (DEBUG_SD_INSTALL) {
17548                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17549                                    + " at code path: " + ps.codePathString);
17550                        }
17551
17552                        // We do have a valid package installed on sdcard
17553                        processCids.put(args, ps.codePathString);
17554                        final int uid = ps.appId;
17555                        if (uid != -1) {
17556                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17557                        }
17558                    } else {
17559                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17560                                + ps.codePathString);
17561                    }
17562                }
17563            }
17564
17565            Arrays.sort(uidArr);
17566        }
17567
17568        // Process packages with valid entries.
17569        if (isMounted) {
17570            if (DEBUG_SD_INSTALL)
17571                Log.i(TAG, "Loading packages");
17572            loadMediaPackages(processCids, uidArr, externalStorage);
17573            startCleaningPackages();
17574            mInstallerService.onSecureContainersAvailable();
17575        } else {
17576            if (DEBUG_SD_INSTALL)
17577                Log.i(TAG, "Unloading packages");
17578            unloadMediaPackages(processCids, uidArr, reportStatus);
17579        }
17580    }
17581
17582    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17583            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17584        final int size = infos.size();
17585        final String[] packageNames = new String[size];
17586        final int[] packageUids = new int[size];
17587        for (int i = 0; i < size; i++) {
17588            final ApplicationInfo info = infos.get(i);
17589            packageNames[i] = info.packageName;
17590            packageUids[i] = info.uid;
17591        }
17592        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17593                finishedReceiver);
17594    }
17595
17596    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17597            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17598        sendResourcesChangedBroadcast(mediaStatus, replacing,
17599                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17600    }
17601
17602    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17603            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17604        int size = pkgList.length;
17605        if (size > 0) {
17606            // Send broadcasts here
17607            Bundle extras = new Bundle();
17608            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17609            if (uidArr != null) {
17610                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17611            }
17612            if (replacing) {
17613                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17614            }
17615            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17616                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17617            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17618        }
17619    }
17620
17621   /*
17622     * Look at potentially valid container ids from processCids If package
17623     * information doesn't match the one on record or package scanning fails,
17624     * the cid is added to list of removeCids. We currently don't delete stale
17625     * containers.
17626     */
17627    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17628            boolean externalStorage) {
17629        ArrayList<String> pkgList = new ArrayList<String>();
17630        Set<AsecInstallArgs> keys = processCids.keySet();
17631
17632        for (AsecInstallArgs args : keys) {
17633            String codePath = processCids.get(args);
17634            if (DEBUG_SD_INSTALL)
17635                Log.i(TAG, "Loading container : " + args.cid);
17636            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17637            try {
17638                // Make sure there are no container errors first.
17639                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17640                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17641                            + " when installing from sdcard");
17642                    continue;
17643                }
17644                // Check code path here.
17645                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17646                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17647                            + " does not match one in settings " + codePath);
17648                    continue;
17649                }
17650                // Parse package
17651                int parseFlags = mDefParseFlags;
17652                if (args.isExternalAsec()) {
17653                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17654                }
17655                if (args.isFwdLocked()) {
17656                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17657                }
17658
17659                synchronized (mInstallLock) {
17660                    PackageParser.Package pkg = null;
17661                    try {
17662                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17663                    } catch (PackageManagerException e) {
17664                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17665                    }
17666                    // Scan the package
17667                    if (pkg != null) {
17668                        /*
17669                         * TODO why is the lock being held? doPostInstall is
17670                         * called in other places without the lock. This needs
17671                         * to be straightened out.
17672                         */
17673                        // writer
17674                        synchronized (mPackages) {
17675                            retCode = PackageManager.INSTALL_SUCCEEDED;
17676                            pkgList.add(pkg.packageName);
17677                            // Post process args
17678                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17679                                    pkg.applicationInfo.uid);
17680                        }
17681                    } else {
17682                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17683                    }
17684                }
17685
17686            } finally {
17687                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17688                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17689                }
17690            }
17691        }
17692        // writer
17693        synchronized (mPackages) {
17694            // If the platform SDK has changed since the last time we booted,
17695            // we need to re-grant app permission to catch any new ones that
17696            // appear. This is really a hack, and means that apps can in some
17697            // cases get permissions that the user didn't initially explicitly
17698            // allow... it would be nice to have some better way to handle
17699            // this situation.
17700            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17701                    : mSettings.getInternalVersion();
17702            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17703                    : StorageManager.UUID_PRIVATE_INTERNAL;
17704
17705            int updateFlags = UPDATE_PERMISSIONS_ALL;
17706            if (ver.sdkVersion != mSdkVersion) {
17707                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17708                        + mSdkVersion + "; regranting permissions for external");
17709                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17710            }
17711            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17712
17713            // Yay, everything is now upgraded
17714            ver.forceCurrent();
17715
17716            // can downgrade to reader
17717            // Persist settings
17718            mSettings.writeLPr();
17719        }
17720        // Send a broadcast to let everyone know we are done processing
17721        if (pkgList.size() > 0) {
17722            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17723        }
17724    }
17725
17726   /*
17727     * Utility method to unload a list of specified containers
17728     */
17729    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17730        // Just unmount all valid containers.
17731        for (AsecInstallArgs arg : cidArgs) {
17732            synchronized (mInstallLock) {
17733                arg.doPostDeleteLI(false);
17734           }
17735       }
17736   }
17737
17738    /*
17739     * Unload packages mounted on external media. This involves deleting package
17740     * data from internal structures, sending broadcasts about disabled packages,
17741     * gc'ing to free up references, unmounting all secure containers
17742     * corresponding to packages on external media, and posting a
17743     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17744     * that we always have to post this message if status has been requested no
17745     * matter what.
17746     */
17747    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17748            final boolean reportStatus) {
17749        if (DEBUG_SD_INSTALL)
17750            Log.i(TAG, "unloading media packages");
17751        ArrayList<String> pkgList = new ArrayList<String>();
17752        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17753        final Set<AsecInstallArgs> keys = processCids.keySet();
17754        for (AsecInstallArgs args : keys) {
17755            String pkgName = args.getPackageName();
17756            if (DEBUG_SD_INSTALL)
17757                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17758            // Delete package internally
17759            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17760            synchronized (mInstallLock) {
17761                boolean res = deletePackageLI(pkgName, null, false, null,
17762                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17763                if (res) {
17764                    pkgList.add(pkgName);
17765                } else {
17766                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17767                    failedList.add(args);
17768                }
17769            }
17770        }
17771
17772        // reader
17773        synchronized (mPackages) {
17774            // We didn't update the settings after removing each package;
17775            // write them now for all packages.
17776            mSettings.writeLPr();
17777        }
17778
17779        // We have to absolutely send UPDATED_MEDIA_STATUS only
17780        // after confirming that all the receivers processed the ordered
17781        // broadcast when packages get disabled, force a gc to clean things up.
17782        // and unload all the containers.
17783        if (pkgList.size() > 0) {
17784            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17785                    new IIntentReceiver.Stub() {
17786                public void performReceive(Intent intent, int resultCode, String data,
17787                        Bundle extras, boolean ordered, boolean sticky,
17788                        int sendingUser) throws RemoteException {
17789                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17790                            reportStatus ? 1 : 0, 1, keys);
17791                    mHandler.sendMessage(msg);
17792                }
17793            });
17794        } else {
17795            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17796                    keys);
17797            mHandler.sendMessage(msg);
17798        }
17799    }
17800
17801    private void loadPrivatePackages(final VolumeInfo vol) {
17802        mHandler.post(new Runnable() {
17803            @Override
17804            public void run() {
17805                loadPrivatePackagesInner(vol);
17806            }
17807        });
17808    }
17809
17810    private void loadPrivatePackagesInner(VolumeInfo vol) {
17811        final String volumeUuid = vol.fsUuid;
17812        if (TextUtils.isEmpty(volumeUuid)) {
17813            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17814            return;
17815        }
17816
17817        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17818        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17819
17820        final VersionInfo ver;
17821        final List<PackageSetting> packages;
17822        synchronized (mPackages) {
17823            ver = mSettings.findOrCreateVersion(volumeUuid);
17824            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17825        }
17826
17827        // TODO: introduce a new concept similar to "frozen" to prevent these
17828        // apps from being launched until after data has been fully reconciled
17829        for (PackageSetting ps : packages) {
17830            synchronized (mInstallLock) {
17831                final PackageParser.Package pkg;
17832                try {
17833                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17834                    loaded.add(pkg.applicationInfo);
17835
17836                } catch (PackageManagerException e) {
17837                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17838                }
17839
17840                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17841                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17842                }
17843            }
17844        }
17845
17846        // Reconcile app data for all started/unlocked users
17847        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17848        final UserManager um = mContext.getSystemService(UserManager.class);
17849        for (UserInfo user : um.getUsers()) {
17850            final int flags;
17851            if (um.isUserUnlocked(user.id)) {
17852                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17853            } else if (um.isUserRunning(user.id)) {
17854                flags = StorageManager.FLAG_STORAGE_DE;
17855            } else {
17856                continue;
17857            }
17858
17859            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17860            reconcileAppsData(volumeUuid, user.id, flags);
17861        }
17862
17863        synchronized (mPackages) {
17864            int updateFlags = UPDATE_PERMISSIONS_ALL;
17865            if (ver.sdkVersion != mSdkVersion) {
17866                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17867                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17868                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17869            }
17870            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17871
17872            // Yay, everything is now upgraded
17873            ver.forceCurrent();
17874
17875            mSettings.writeLPr();
17876        }
17877
17878        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17879        sendResourcesChangedBroadcast(true, false, loaded, null);
17880    }
17881
17882    private void unloadPrivatePackages(final VolumeInfo vol) {
17883        mHandler.post(new Runnable() {
17884            @Override
17885            public void run() {
17886                unloadPrivatePackagesInner(vol);
17887            }
17888        });
17889    }
17890
17891    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17892        final String volumeUuid = vol.fsUuid;
17893        if (TextUtils.isEmpty(volumeUuid)) {
17894            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17895            return;
17896        }
17897
17898        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17899        synchronized (mInstallLock) {
17900        synchronized (mPackages) {
17901            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17902            for (PackageSetting ps : packages) {
17903                if (ps.pkg == null) continue;
17904
17905                final ApplicationInfo info = ps.pkg.applicationInfo;
17906                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17907                if (deletePackageLI(ps.name, null, false, null,
17908                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17909                    unloaded.add(info);
17910                } else {
17911                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17912                }
17913            }
17914
17915            mSettings.writeLPr();
17916        }
17917        }
17918
17919        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17920        sendResourcesChangedBroadcast(false, false, unloaded, null);
17921    }
17922
17923    /**
17924     * Examine all users present on given mounted volume, and destroy data
17925     * belonging to users that are no longer valid, or whose user ID has been
17926     * recycled.
17927     */
17928    private void reconcileUsers(String volumeUuid) {
17929        // TODO: also reconcile DE directories
17930        final File[] files = FileUtils
17931                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17932        for (File file : files) {
17933            if (!file.isDirectory()) continue;
17934
17935            final int userId;
17936            final UserInfo info;
17937            try {
17938                userId = Integer.parseInt(file.getName());
17939                info = sUserManager.getUserInfo(userId);
17940            } catch (NumberFormatException e) {
17941                Slog.w(TAG, "Invalid user directory " + file);
17942                continue;
17943            }
17944
17945            boolean destroyUser = false;
17946            if (info == null) {
17947                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17948                        + " because no matching user was found");
17949                destroyUser = true;
17950            } else {
17951                try {
17952                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17953                } catch (IOException e) {
17954                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17955                            + " because we failed to enforce serial number: " + e);
17956                    destroyUser = true;
17957                }
17958            }
17959
17960            if (destroyUser) {
17961                synchronized (mInstallLock) {
17962                    try {
17963                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17964                    } catch (InstallerException e) {
17965                        Slog.w(TAG, "Failed to clean up user dirs", e);
17966                    }
17967                }
17968            }
17969        }
17970    }
17971
17972    private void assertPackageKnown(String volumeUuid, String packageName)
17973            throws PackageManagerException {
17974        synchronized (mPackages) {
17975            final PackageSetting ps = mSettings.mPackages.get(packageName);
17976            if (ps == null) {
17977                throw new PackageManagerException("Package " + packageName + " is unknown");
17978            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17979                throw new PackageManagerException(
17980                        "Package " + packageName + " found on unknown volume " + volumeUuid
17981                                + "; expected volume " + ps.volumeUuid);
17982            }
17983        }
17984    }
17985
17986    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17987            throws PackageManagerException {
17988        synchronized (mPackages) {
17989            final PackageSetting ps = mSettings.mPackages.get(packageName);
17990            if (ps == null) {
17991                throw new PackageManagerException("Package " + packageName + " is unknown");
17992            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17993                throw new PackageManagerException(
17994                        "Package " + packageName + " found on unknown volume " + volumeUuid
17995                                + "; expected volume " + ps.volumeUuid);
17996            } else if (!ps.getInstalled(userId)) {
17997                throw new PackageManagerException(
17998                        "Package " + packageName + " not installed for user " + userId);
17999            }
18000        }
18001    }
18002
18003    /**
18004     * Examine all apps present on given mounted volume, and destroy apps that
18005     * aren't expected, either due to uninstallation or reinstallation on
18006     * another volume.
18007     */
18008    private void reconcileApps(String volumeUuid) {
18009        final File[] files = FileUtils
18010                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18011        for (File file : files) {
18012            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18013                    && !PackageInstallerService.isStageName(file.getName());
18014            if (!isPackage) {
18015                // Ignore entries which are not packages
18016                continue;
18017            }
18018
18019            try {
18020                final PackageLite pkg = PackageParser.parsePackageLite(file,
18021                        PackageParser.PARSE_MUST_BE_APK);
18022                assertPackageKnown(volumeUuid, pkg.packageName);
18023
18024            } catch (PackageParserException | PackageManagerException e) {
18025                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18026                synchronized (mInstallLock) {
18027                    removeCodePathLI(file);
18028                }
18029            }
18030        }
18031    }
18032
18033    /**
18034     * Reconcile all app data for the given user.
18035     * <p>
18036     * Verifies that directories exist and that ownership and labeling is
18037     * correct for all installed apps on all mounted volumes.
18038     */
18039    void reconcileAppsData(int userId, int flags) {
18040        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18041        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18042            final String volumeUuid = vol.getFsUuid();
18043            reconcileAppsData(volumeUuid, userId, flags);
18044        }
18045    }
18046
18047    /**
18048     * Reconcile all app data on given mounted volume.
18049     * <p>
18050     * Destroys app data that isn't expected, either due to uninstallation or
18051     * reinstallation on another volume.
18052     * <p>
18053     * Verifies that directories exist and that ownership and labeling is
18054     * correct for all installed apps.
18055     */
18056    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18057        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18058                + Integer.toHexString(flags));
18059
18060        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18061        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18062
18063        boolean restoreconNeeded = false;
18064
18065        // First look for stale data that doesn't belong, and check if things
18066        // have changed since we did our last restorecon
18067        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18068            if (!isUserKeyUnlocked(userId)) {
18069                throw new RuntimeException(
18070                        "Yikes, someone asked us to reconcile CE storage while " + userId
18071                                + " was still locked; this would have caused massive data loss!");
18072            }
18073
18074            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18075
18076            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18077            for (File file : files) {
18078                final String packageName = file.getName();
18079                try {
18080                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18081                } catch (PackageManagerException e) {
18082                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18083                    synchronized (mInstallLock) {
18084                        destroyAppDataLI(volumeUuid, packageName, userId,
18085                                StorageManager.FLAG_STORAGE_CE);
18086                    }
18087                }
18088            }
18089        }
18090        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18091            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18092
18093            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18094            for (File file : files) {
18095                final String packageName = file.getName();
18096                try {
18097                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18098                } catch (PackageManagerException e) {
18099                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18100                    synchronized (mInstallLock) {
18101                        destroyAppDataLI(volumeUuid, packageName, userId,
18102                                StorageManager.FLAG_STORAGE_DE);
18103                    }
18104                }
18105            }
18106        }
18107
18108        // Ensure that data directories are ready to roll for all packages
18109        // installed for this volume and user
18110        final List<PackageSetting> packages;
18111        synchronized (mPackages) {
18112            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18113        }
18114        int preparedCount = 0;
18115        for (PackageSetting ps : packages) {
18116            final String packageName = ps.name;
18117            if (ps.pkg == null) {
18118                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18119                // TODO: might be due to legacy ASEC apps; we should circle back
18120                // and reconcile again once they're scanned
18121                continue;
18122            }
18123
18124            if (ps.getInstalled(userId)) {
18125                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18126
18127                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18128                    // We may have just shuffled around app data directories, so
18129                    // prepare them one more time
18130                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18131                }
18132
18133                preparedCount++;
18134            }
18135        }
18136
18137        if (restoreconNeeded) {
18138            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18139                SELinuxMMAC.setRestoreconDone(ceDir);
18140            }
18141            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18142                SELinuxMMAC.setRestoreconDone(deDir);
18143            }
18144        }
18145
18146        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18147                + " packages; restoreconNeeded was " + restoreconNeeded);
18148    }
18149
18150    /**
18151     * Prepare app data for the given app just after it was installed or
18152     * upgraded. This method carefully only touches users that it's installed
18153     * for, and it forces a restorecon to handle any seinfo changes.
18154     * <p>
18155     * Verifies that directories exist and that ownership and labeling is
18156     * correct for all installed apps. If there is an ownership mismatch, it
18157     * will try recovering system apps by wiping data; third-party app data is
18158     * left intact.
18159     * <p>
18160     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18161     */
18162    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18163        prepareAppDataAfterInstallInternal(pkg);
18164        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18165        for (int i = 0; i < childCount; i++) {
18166            PackageParser.Package childPackage = pkg.childPackages.get(i);
18167            prepareAppDataAfterInstallInternal(childPackage);
18168        }
18169    }
18170
18171    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18172        final PackageSetting ps;
18173        synchronized (mPackages) {
18174            ps = mSettings.mPackages.get(pkg.packageName);
18175            mSettings.writeKernelMappingLPr(ps);
18176        }
18177
18178        final UserManager um = mContext.getSystemService(UserManager.class);
18179        for (UserInfo user : um.getUsers()) {
18180            final int flags;
18181            if (um.isUserUnlocked(user.id)) {
18182                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18183            } else if (um.isUserRunning(user.id)) {
18184                flags = StorageManager.FLAG_STORAGE_DE;
18185            } else {
18186                continue;
18187            }
18188
18189            if (ps.getInstalled(user.id)) {
18190                // Whenever an app changes, force a restorecon of its data
18191                // TODO: when user data is locked, mark that we're still dirty
18192                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18193            }
18194        }
18195    }
18196
18197    /**
18198     * Prepare app data for the given app.
18199     * <p>
18200     * Verifies that directories exist and that ownership and labeling is
18201     * correct for all installed apps. If there is an ownership mismatch, this
18202     * will try recovering system apps by wiping data; third-party app data is
18203     * left intact.
18204     */
18205    private void prepareAppData(String volumeUuid, int userId, int flags,
18206            PackageParser.Package pkg, boolean restoreconNeeded) {
18207        if (DEBUG_APP_DATA) {
18208            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18209                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18210        }
18211
18212        final String packageName = pkg.packageName;
18213        final ApplicationInfo app = pkg.applicationInfo;
18214        final int appId = UserHandle.getAppId(app.uid);
18215
18216        Preconditions.checkNotNull(app.seinfo);
18217
18218        synchronized (mInstallLock) {
18219            try {
18220                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18221                        appId, app.seinfo, app.targetSdkVersion);
18222            } catch (InstallerException e) {
18223                if (app.isSystemApp()) {
18224                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18225                            + ", but trying to recover: " + e);
18226                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18227                    try {
18228                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18229                                appId, app.seinfo, app.targetSdkVersion);
18230                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18231                    } catch (InstallerException e2) {
18232                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18233                    }
18234                } else {
18235                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18236                }
18237            }
18238
18239            if (restoreconNeeded) {
18240                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18241            }
18242
18243            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18244                // Create a native library symlink only if we have native libraries
18245                // and if the native libraries are 32 bit libraries. We do not provide
18246                // this symlink for 64 bit libraries.
18247                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18248                    final String nativeLibPath = app.nativeLibraryDir;
18249                    try {
18250                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18251                                nativeLibPath, userId);
18252                    } catch (InstallerException e) {
18253                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18254                    }
18255                }
18256            }
18257        }
18258    }
18259
18260    /**
18261     * For system apps on non-FBE devices, this method migrates any existing
18262     * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by
18263     * the app.
18264     */
18265    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18266        if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled()
18267                && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
18268            final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted()
18269                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18270            synchronized (mInstallLock) {
18271                try {
18272                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18273                } catch (InstallerException e) {
18274                    logCriticalInfo(Log.WARN,
18275                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18276                }
18277            }
18278            return true;
18279        } else {
18280            return false;
18281        }
18282    }
18283
18284    private void unfreezePackage(String packageName) {
18285        synchronized (mPackages) {
18286            final PackageSetting ps = mSettings.mPackages.get(packageName);
18287            if (ps != null) {
18288                ps.frozen = false;
18289            }
18290        }
18291    }
18292
18293    @Override
18294    public int movePackage(final String packageName, final String volumeUuid) {
18295        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18296
18297        final int moveId = mNextMoveId.getAndIncrement();
18298        mHandler.post(new Runnable() {
18299            @Override
18300            public void run() {
18301                try {
18302                    movePackageInternal(packageName, volumeUuid, moveId);
18303                } catch (PackageManagerException e) {
18304                    Slog.w(TAG, "Failed to move " + packageName, e);
18305                    mMoveCallbacks.notifyStatusChanged(moveId,
18306                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18307                }
18308            }
18309        });
18310        return moveId;
18311    }
18312
18313    private void movePackageInternal(final String packageName, final String volumeUuid,
18314            final int moveId) throws PackageManagerException {
18315        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18316        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18317        final PackageManager pm = mContext.getPackageManager();
18318
18319        final boolean currentAsec;
18320        final String currentVolumeUuid;
18321        final File codeFile;
18322        final String installerPackageName;
18323        final String packageAbiOverride;
18324        final int appId;
18325        final String seinfo;
18326        final String label;
18327        final int targetSdkVersion;
18328
18329        // reader
18330        synchronized (mPackages) {
18331            final PackageParser.Package pkg = mPackages.get(packageName);
18332            final PackageSetting ps = mSettings.mPackages.get(packageName);
18333            if (pkg == null || ps == null) {
18334                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18335            }
18336
18337            if (pkg.applicationInfo.isSystemApp()) {
18338                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18339                        "Cannot move system application");
18340            }
18341
18342            if (pkg.applicationInfo.isExternalAsec()) {
18343                currentAsec = true;
18344                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18345            } else if (pkg.applicationInfo.isForwardLocked()) {
18346                currentAsec = true;
18347                currentVolumeUuid = "forward_locked";
18348            } else {
18349                currentAsec = false;
18350                currentVolumeUuid = ps.volumeUuid;
18351
18352                final File probe = new File(pkg.codePath);
18353                final File probeOat = new File(probe, "oat");
18354                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18355                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18356                            "Move only supported for modern cluster style installs");
18357                }
18358            }
18359
18360            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18361                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18362                        "Package already moved to " + volumeUuid);
18363            }
18364            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18365                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18366                        "Device admin cannot be moved");
18367            }
18368
18369            if (ps.frozen) {
18370                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18371                        "Failed to move already frozen package");
18372            }
18373            ps.frozen = true;
18374
18375            codeFile = new File(pkg.codePath);
18376            installerPackageName = ps.installerPackageName;
18377            packageAbiOverride = ps.cpuAbiOverrideString;
18378            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18379            seinfo = pkg.applicationInfo.seinfo;
18380            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18381            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18382        }
18383
18384        // Now that we're guarded by frozen state, kill app during move
18385        final long token = Binder.clearCallingIdentity();
18386        try {
18387            killApplication(packageName, appId, "move pkg");
18388        } finally {
18389            Binder.restoreCallingIdentity(token);
18390        }
18391
18392        final Bundle extras = new Bundle();
18393        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18394        extras.putString(Intent.EXTRA_TITLE, label);
18395        mMoveCallbacks.notifyCreated(moveId, extras);
18396
18397        int installFlags;
18398        final boolean moveCompleteApp;
18399        final File measurePath;
18400
18401        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18402            installFlags = INSTALL_INTERNAL;
18403            moveCompleteApp = !currentAsec;
18404            measurePath = Environment.getDataAppDirectory(volumeUuid);
18405        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18406            installFlags = INSTALL_EXTERNAL;
18407            moveCompleteApp = false;
18408            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18409        } else {
18410            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18411            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18412                    || !volume.isMountedWritable()) {
18413                unfreezePackage(packageName);
18414                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18415                        "Move location not mounted private volume");
18416            }
18417
18418            Preconditions.checkState(!currentAsec);
18419
18420            installFlags = INSTALL_INTERNAL;
18421            moveCompleteApp = true;
18422            measurePath = Environment.getDataAppDirectory(volumeUuid);
18423        }
18424
18425        final PackageStats stats = new PackageStats(null, -1);
18426        synchronized (mInstaller) {
18427            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18428                unfreezePackage(packageName);
18429                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18430                        "Failed to measure package size");
18431            }
18432        }
18433
18434        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18435                + stats.dataSize);
18436
18437        final long startFreeBytes = measurePath.getFreeSpace();
18438        final long sizeBytes;
18439        if (moveCompleteApp) {
18440            sizeBytes = stats.codeSize + stats.dataSize;
18441        } else {
18442            sizeBytes = stats.codeSize;
18443        }
18444
18445        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18446            unfreezePackage(packageName);
18447            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18448                    "Not enough free space to move");
18449        }
18450
18451        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18452
18453        final CountDownLatch installedLatch = new CountDownLatch(1);
18454        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18455            @Override
18456            public void onUserActionRequired(Intent intent) throws RemoteException {
18457                throw new IllegalStateException();
18458            }
18459
18460            @Override
18461            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18462                    Bundle extras) throws RemoteException {
18463                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18464                        + PackageManager.installStatusToString(returnCode, msg));
18465
18466                installedLatch.countDown();
18467
18468                // Regardless of success or failure of the move operation,
18469                // always unfreeze the package
18470                unfreezePackage(packageName);
18471
18472                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18473                switch (status) {
18474                    case PackageInstaller.STATUS_SUCCESS:
18475                        mMoveCallbacks.notifyStatusChanged(moveId,
18476                                PackageManager.MOVE_SUCCEEDED);
18477                        break;
18478                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18479                        mMoveCallbacks.notifyStatusChanged(moveId,
18480                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18481                        break;
18482                    default:
18483                        mMoveCallbacks.notifyStatusChanged(moveId,
18484                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18485                        break;
18486                }
18487            }
18488        };
18489
18490        final MoveInfo move;
18491        if (moveCompleteApp) {
18492            // Kick off a thread to report progress estimates
18493            new Thread() {
18494                @Override
18495                public void run() {
18496                    while (true) {
18497                        try {
18498                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18499                                break;
18500                            }
18501                        } catch (InterruptedException ignored) {
18502                        }
18503
18504                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18505                        final int progress = 10 + (int) MathUtils.constrain(
18506                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18507                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18508                    }
18509                }
18510            }.start();
18511
18512            final String dataAppName = codeFile.getName();
18513            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18514                    dataAppName, appId, seinfo, targetSdkVersion);
18515        } else {
18516            move = null;
18517        }
18518
18519        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18520
18521        final Message msg = mHandler.obtainMessage(INIT_COPY);
18522        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18523        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18524                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18525                packageAbiOverride, null);
18526        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18527        msg.obj = params;
18528
18529        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18530                System.identityHashCode(msg.obj));
18531        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18532                System.identityHashCode(msg.obj));
18533
18534        mHandler.sendMessage(msg);
18535    }
18536
18537    @Override
18538    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18539        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18540
18541        final int realMoveId = mNextMoveId.getAndIncrement();
18542        final Bundle extras = new Bundle();
18543        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18544        mMoveCallbacks.notifyCreated(realMoveId, extras);
18545
18546        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18547            @Override
18548            public void onCreated(int moveId, Bundle extras) {
18549                // Ignored
18550            }
18551
18552            @Override
18553            public void onStatusChanged(int moveId, int status, long estMillis) {
18554                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18555            }
18556        };
18557
18558        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18559        storage.setPrimaryStorageUuid(volumeUuid, callback);
18560        return realMoveId;
18561    }
18562
18563    @Override
18564    public int getMoveStatus(int moveId) {
18565        mContext.enforceCallingOrSelfPermission(
18566                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18567        return mMoveCallbacks.mLastStatus.get(moveId);
18568    }
18569
18570    @Override
18571    public void registerMoveCallback(IPackageMoveObserver callback) {
18572        mContext.enforceCallingOrSelfPermission(
18573                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18574        mMoveCallbacks.register(callback);
18575    }
18576
18577    @Override
18578    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18579        mContext.enforceCallingOrSelfPermission(
18580                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18581        mMoveCallbacks.unregister(callback);
18582    }
18583
18584    @Override
18585    public boolean setInstallLocation(int loc) {
18586        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18587                null);
18588        if (getInstallLocation() == loc) {
18589            return true;
18590        }
18591        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18592                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18593            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18594                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18595            return true;
18596        }
18597        return false;
18598   }
18599
18600    @Override
18601    public int getInstallLocation() {
18602        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18603                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18604                PackageHelper.APP_INSTALL_AUTO);
18605    }
18606
18607    /** Called by UserManagerService */
18608    void cleanUpUser(UserManagerService userManager, int userHandle) {
18609        synchronized (mPackages) {
18610            mDirtyUsers.remove(userHandle);
18611            mUserNeedsBadging.delete(userHandle);
18612            mSettings.removeUserLPw(userHandle);
18613            mPendingBroadcasts.remove(userHandle);
18614            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18615        }
18616        synchronized (mInstallLock) {
18617            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18618            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18619                final String volumeUuid = vol.getFsUuid();
18620                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18621                try {
18622                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18623                } catch (InstallerException e) {
18624                    Slog.w(TAG, "Failed to remove user data", e);
18625                }
18626            }
18627            synchronized (mPackages) {
18628                removeUnusedPackagesLILPw(userManager, userHandle);
18629            }
18630        }
18631    }
18632
18633    /**
18634     * We're removing userHandle and would like to remove any downloaded packages
18635     * that are no longer in use by any other user.
18636     * @param userHandle the user being removed
18637     */
18638    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18639        final boolean DEBUG_CLEAN_APKS = false;
18640        int [] users = userManager.getUserIds();
18641        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18642        while (psit.hasNext()) {
18643            PackageSetting ps = psit.next();
18644            if (ps.pkg == null) {
18645                continue;
18646            }
18647            final String packageName = ps.pkg.packageName;
18648            // Skip over if system app
18649            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18650                continue;
18651            }
18652            if (DEBUG_CLEAN_APKS) {
18653                Slog.i(TAG, "Checking package " + packageName);
18654            }
18655            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18656            if (keep) {
18657                if (DEBUG_CLEAN_APKS) {
18658                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18659                }
18660            } else {
18661                for (int i = 0; i < users.length; i++) {
18662                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18663                        keep = true;
18664                        if (DEBUG_CLEAN_APKS) {
18665                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18666                                    + users[i]);
18667                        }
18668                        break;
18669                    }
18670                }
18671            }
18672            if (!keep) {
18673                if (DEBUG_CLEAN_APKS) {
18674                    Slog.i(TAG, "  Removing package " + packageName);
18675                }
18676                mHandler.post(new Runnable() {
18677                    public void run() {
18678                        deletePackageX(packageName, userHandle, 0);
18679                    } //end run
18680                });
18681            }
18682        }
18683    }
18684
18685    /** Called by UserManagerService */
18686    void createNewUser(int userHandle) {
18687        synchronized (mInstallLock) {
18688            try {
18689                mInstaller.createUserConfig(userHandle);
18690            } catch (InstallerException e) {
18691                Slog.w(TAG, "Failed to create user config", e);
18692            }
18693            mSettings.createNewUserLI(this, mInstaller, userHandle);
18694        }
18695        synchronized (mPackages) {
18696            applyFactoryDefaultBrowserLPw(userHandle);
18697            primeDomainVerificationsLPw(userHandle);
18698        }
18699    }
18700
18701    void newUserCreated(final int userHandle) {
18702        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18703        // If permission review for legacy apps is required, we represent
18704        // dagerous permissions for such apps as always granted runtime
18705        // permissions to keep per user flag state whether review is needed.
18706        // Hence, if a new user is added we have to propagate dangerous
18707        // permission grants for these legacy apps.
18708        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18709            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18710                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18711        }
18712    }
18713
18714    @Override
18715    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18716        mContext.enforceCallingOrSelfPermission(
18717                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18718                "Only package verification agents can read the verifier device identity");
18719
18720        synchronized (mPackages) {
18721            return mSettings.getVerifierDeviceIdentityLPw();
18722        }
18723    }
18724
18725    @Override
18726    public void setPermissionEnforced(String permission, boolean enforced) {
18727        // TODO: Now that we no longer change GID for storage, this should to away.
18728        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18729                "setPermissionEnforced");
18730        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18731            synchronized (mPackages) {
18732                if (mSettings.mReadExternalStorageEnforced == null
18733                        || mSettings.mReadExternalStorageEnforced != enforced) {
18734                    mSettings.mReadExternalStorageEnforced = enforced;
18735                    mSettings.writeLPr();
18736                }
18737            }
18738            // kill any non-foreground processes so we restart them and
18739            // grant/revoke the GID.
18740            final IActivityManager am = ActivityManagerNative.getDefault();
18741            if (am != null) {
18742                final long token = Binder.clearCallingIdentity();
18743                try {
18744                    am.killProcessesBelowForeground("setPermissionEnforcement");
18745                } catch (RemoteException e) {
18746                } finally {
18747                    Binder.restoreCallingIdentity(token);
18748                }
18749            }
18750        } else {
18751            throw new IllegalArgumentException("No selective enforcement for " + permission);
18752        }
18753    }
18754
18755    @Override
18756    @Deprecated
18757    public boolean isPermissionEnforced(String permission) {
18758        return true;
18759    }
18760
18761    @Override
18762    public boolean isStorageLow() {
18763        final long token = Binder.clearCallingIdentity();
18764        try {
18765            final DeviceStorageMonitorInternal
18766                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18767            if (dsm != null) {
18768                return dsm.isMemoryLow();
18769            } else {
18770                return false;
18771            }
18772        } finally {
18773            Binder.restoreCallingIdentity(token);
18774        }
18775    }
18776
18777    @Override
18778    public IPackageInstaller getPackageInstaller() {
18779        return mInstallerService;
18780    }
18781
18782    private boolean userNeedsBadging(int userId) {
18783        int index = mUserNeedsBadging.indexOfKey(userId);
18784        if (index < 0) {
18785            final UserInfo userInfo;
18786            final long token = Binder.clearCallingIdentity();
18787            try {
18788                userInfo = sUserManager.getUserInfo(userId);
18789            } finally {
18790                Binder.restoreCallingIdentity(token);
18791            }
18792            final boolean b;
18793            if (userInfo != null && userInfo.isManagedProfile()) {
18794                b = true;
18795            } else {
18796                b = false;
18797            }
18798            mUserNeedsBadging.put(userId, b);
18799            return b;
18800        }
18801        return mUserNeedsBadging.valueAt(index);
18802    }
18803
18804    @Override
18805    public KeySet getKeySetByAlias(String packageName, String alias) {
18806        if (packageName == null || alias == null) {
18807            return null;
18808        }
18809        synchronized(mPackages) {
18810            final PackageParser.Package pkg = mPackages.get(packageName);
18811            if (pkg == null) {
18812                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18813                throw new IllegalArgumentException("Unknown package: " + packageName);
18814            }
18815            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18816            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18817        }
18818    }
18819
18820    @Override
18821    public KeySet getSigningKeySet(String packageName) {
18822        if (packageName == null) {
18823            return null;
18824        }
18825        synchronized(mPackages) {
18826            final PackageParser.Package pkg = mPackages.get(packageName);
18827            if (pkg == null) {
18828                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18829                throw new IllegalArgumentException("Unknown package: " + packageName);
18830            }
18831            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18832                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18833                throw new SecurityException("May not access signing KeySet of other apps.");
18834            }
18835            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18836            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18837        }
18838    }
18839
18840    @Override
18841    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18842        if (packageName == null || ks == null) {
18843            return false;
18844        }
18845        synchronized(mPackages) {
18846            final PackageParser.Package pkg = mPackages.get(packageName);
18847            if (pkg == null) {
18848                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18849                throw new IllegalArgumentException("Unknown package: " + packageName);
18850            }
18851            IBinder ksh = ks.getToken();
18852            if (ksh instanceof KeySetHandle) {
18853                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18854                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18855            }
18856            return false;
18857        }
18858    }
18859
18860    @Override
18861    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18862        if (packageName == null || ks == null) {
18863            return false;
18864        }
18865        synchronized(mPackages) {
18866            final PackageParser.Package pkg = mPackages.get(packageName);
18867            if (pkg == null) {
18868                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18869                throw new IllegalArgumentException("Unknown package: " + packageName);
18870            }
18871            IBinder ksh = ks.getToken();
18872            if (ksh instanceof KeySetHandle) {
18873                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18874                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18875            }
18876            return false;
18877        }
18878    }
18879
18880    private void deletePackageIfUnusedLPr(final String packageName) {
18881        PackageSetting ps = mSettings.mPackages.get(packageName);
18882        if (ps == null) {
18883            return;
18884        }
18885        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18886            // TODO Implement atomic delete if package is unused
18887            // It is currently possible that the package will be deleted even if it is installed
18888            // after this method returns.
18889            mHandler.post(new Runnable() {
18890                public void run() {
18891                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18892                }
18893            });
18894        }
18895    }
18896
18897    /**
18898     * Check and throw if the given before/after packages would be considered a
18899     * downgrade.
18900     */
18901    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18902            throws PackageManagerException {
18903        if (after.versionCode < before.mVersionCode) {
18904            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18905                    "Update version code " + after.versionCode + " is older than current "
18906                    + before.mVersionCode);
18907        } else if (after.versionCode == before.mVersionCode) {
18908            if (after.baseRevisionCode < before.baseRevisionCode) {
18909                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18910                        "Update base revision code " + after.baseRevisionCode
18911                        + " is older than current " + before.baseRevisionCode);
18912            }
18913
18914            if (!ArrayUtils.isEmpty(after.splitNames)) {
18915                for (int i = 0; i < after.splitNames.length; i++) {
18916                    final String splitName = after.splitNames[i];
18917                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18918                    if (j != -1) {
18919                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18920                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18921                                    "Update split " + splitName + " revision code "
18922                                    + after.splitRevisionCodes[i] + " is older than current "
18923                                    + before.splitRevisionCodes[j]);
18924                        }
18925                    }
18926                }
18927            }
18928        }
18929    }
18930
18931    private static class MoveCallbacks extends Handler {
18932        private static final int MSG_CREATED = 1;
18933        private static final int MSG_STATUS_CHANGED = 2;
18934
18935        private final RemoteCallbackList<IPackageMoveObserver>
18936                mCallbacks = new RemoteCallbackList<>();
18937
18938        private final SparseIntArray mLastStatus = new SparseIntArray();
18939
18940        public MoveCallbacks(Looper looper) {
18941            super(looper);
18942        }
18943
18944        public void register(IPackageMoveObserver callback) {
18945            mCallbacks.register(callback);
18946        }
18947
18948        public void unregister(IPackageMoveObserver callback) {
18949            mCallbacks.unregister(callback);
18950        }
18951
18952        @Override
18953        public void handleMessage(Message msg) {
18954            final SomeArgs args = (SomeArgs) msg.obj;
18955            final int n = mCallbacks.beginBroadcast();
18956            for (int i = 0; i < n; i++) {
18957                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18958                try {
18959                    invokeCallback(callback, msg.what, args);
18960                } catch (RemoteException ignored) {
18961                }
18962            }
18963            mCallbacks.finishBroadcast();
18964            args.recycle();
18965        }
18966
18967        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18968                throws RemoteException {
18969            switch (what) {
18970                case MSG_CREATED: {
18971                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18972                    break;
18973                }
18974                case MSG_STATUS_CHANGED: {
18975                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18976                    break;
18977                }
18978            }
18979        }
18980
18981        private void notifyCreated(int moveId, Bundle extras) {
18982            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18983
18984            final SomeArgs args = SomeArgs.obtain();
18985            args.argi1 = moveId;
18986            args.arg2 = extras;
18987            obtainMessage(MSG_CREATED, args).sendToTarget();
18988        }
18989
18990        private void notifyStatusChanged(int moveId, int status) {
18991            notifyStatusChanged(moveId, status, -1);
18992        }
18993
18994        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18995            Slog.v(TAG, "Move " + moveId + " status " + status);
18996
18997            final SomeArgs args = SomeArgs.obtain();
18998            args.argi1 = moveId;
18999            args.argi2 = status;
19000            args.arg3 = estMillis;
19001            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19002
19003            synchronized (mLastStatus) {
19004                mLastStatus.put(moveId, status);
19005            }
19006        }
19007    }
19008
19009    private final static class OnPermissionChangeListeners extends Handler {
19010        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19011
19012        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19013                new RemoteCallbackList<>();
19014
19015        public OnPermissionChangeListeners(Looper looper) {
19016            super(looper);
19017        }
19018
19019        @Override
19020        public void handleMessage(Message msg) {
19021            switch (msg.what) {
19022                case MSG_ON_PERMISSIONS_CHANGED: {
19023                    final int uid = msg.arg1;
19024                    handleOnPermissionsChanged(uid);
19025                } break;
19026            }
19027        }
19028
19029        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19030            mPermissionListeners.register(listener);
19031
19032        }
19033
19034        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19035            mPermissionListeners.unregister(listener);
19036        }
19037
19038        public void onPermissionsChanged(int uid) {
19039            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19040                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19041            }
19042        }
19043
19044        private void handleOnPermissionsChanged(int uid) {
19045            final int count = mPermissionListeners.beginBroadcast();
19046            try {
19047                for (int i = 0; i < count; i++) {
19048                    IOnPermissionsChangeListener callback = mPermissionListeners
19049                            .getBroadcastItem(i);
19050                    try {
19051                        callback.onPermissionsChanged(uid);
19052                    } catch (RemoteException e) {
19053                        Log.e(TAG, "Permission listener is dead", e);
19054                    }
19055                }
19056            } finally {
19057                mPermissionListeners.finishBroadcast();
19058            }
19059        }
19060    }
19061
19062    private class PackageManagerInternalImpl extends PackageManagerInternal {
19063        @Override
19064        public void setLocationPackagesProvider(PackagesProvider provider) {
19065            synchronized (mPackages) {
19066                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19067            }
19068        }
19069
19070        @Override
19071        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19072            synchronized (mPackages) {
19073                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19074            }
19075        }
19076
19077        @Override
19078        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19079            synchronized (mPackages) {
19080                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19081            }
19082        }
19083
19084        @Override
19085        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19086            synchronized (mPackages) {
19087                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19088            }
19089        }
19090
19091        @Override
19092        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19093            synchronized (mPackages) {
19094                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19095            }
19096        }
19097
19098        @Override
19099        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19100            synchronized (mPackages) {
19101                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19102            }
19103        }
19104
19105        @Override
19106        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19107            synchronized (mPackages) {
19108                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19109                        packageName, userId);
19110            }
19111        }
19112
19113        @Override
19114        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19115            synchronized (mPackages) {
19116                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19117                        packageName, userId);
19118            }
19119        }
19120
19121        @Override
19122        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19123            synchronized (mPackages) {
19124                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19125                        packageName, userId);
19126            }
19127        }
19128
19129        @Override
19130        public void setKeepUninstalledPackages(final List<String> packageList) {
19131            Preconditions.checkNotNull(packageList);
19132            List<String> removedFromList = null;
19133            synchronized (mPackages) {
19134                if (mKeepUninstalledPackages != null) {
19135                    final int packagesCount = mKeepUninstalledPackages.size();
19136                    for (int i = 0; i < packagesCount; i++) {
19137                        String oldPackage = mKeepUninstalledPackages.get(i);
19138                        if (packageList != null && packageList.contains(oldPackage)) {
19139                            continue;
19140                        }
19141                        if (removedFromList == null) {
19142                            removedFromList = new ArrayList<>();
19143                        }
19144                        removedFromList.add(oldPackage);
19145                    }
19146                }
19147                mKeepUninstalledPackages = new ArrayList<>(packageList);
19148                if (removedFromList != null) {
19149                    final int removedCount = removedFromList.size();
19150                    for (int i = 0; i < removedCount; i++) {
19151                        deletePackageIfUnusedLPr(removedFromList.get(i));
19152                    }
19153                }
19154            }
19155        }
19156
19157        @Override
19158        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19159            synchronized (mPackages) {
19160                // If we do not support permission review, done.
19161                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19162                    return false;
19163                }
19164
19165                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19166                if (packageSetting == null) {
19167                    return false;
19168                }
19169
19170                // Permission review applies only to apps not supporting the new permission model.
19171                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19172                    return false;
19173                }
19174
19175                // Legacy apps have the permission and get user consent on launch.
19176                PermissionsState permissionsState = packageSetting.getPermissionsState();
19177                return permissionsState.isPermissionReviewRequired(userId);
19178            }
19179        }
19180
19181        @Override
19182        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19183            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19184        }
19185    }
19186
19187    @Override
19188    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19189        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19190        synchronized (mPackages) {
19191            final long identity = Binder.clearCallingIdentity();
19192            try {
19193                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19194                        packageNames, userId);
19195            } finally {
19196                Binder.restoreCallingIdentity(identity);
19197            }
19198        }
19199    }
19200
19201    private static void enforceSystemOrPhoneCaller(String tag) {
19202        int callingUid = Binder.getCallingUid();
19203        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19204            throw new SecurityException(
19205                    "Cannot call " + tag + " from UID " + callingUid);
19206        }
19207    }
19208
19209    boolean isHistoricalPackageUsageAvailable() {
19210        return mPackageUsage.isHistoricalPackageUsageAvailable();
19211    }
19212}
19213