PackageManagerService.java revision abcbe2f62e6278d8aeb0b8c302d23aeae59899d4
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
364    static final int REMOVE_CHATTY = 1<<16;
365
366    private static final int[] EMPTY_INT_ARRAY = new int[0];
367
368    /**
369     * Timeout (in milliseconds) after which the watchdog should declare that
370     * our handler thread is wedged.  The usual default for such things is one
371     * minute but we sometimes do very lengthy I/O operations on this thread,
372     * such as installing multi-gigabyte applications, so ours needs to be longer.
373     */
374    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
375
376    /**
377     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
378     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
379     * settings entry if available, otherwise we use the hardcoded default.  If it's been
380     * more than this long since the last fstrim, we force one during the boot sequence.
381     *
382     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
383     * one gets run at the next available charging+idle time.  This final mandatory
384     * no-fstrim check kicks in only of the other scheduling criteria is never met.
385     */
386    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
387
388    /**
389     * Whether verification is enabled by default.
390     */
391    private static final boolean DEFAULT_VERIFY_ENABLE = true;
392
393    /**
394     * The default maximum time to wait for the verification agent to return in
395     * milliseconds.
396     */
397    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
398
399    /**
400     * The default response for package verification timeout.
401     *
402     * This can be either PackageManager.VERIFICATION_ALLOW or
403     * PackageManager.VERIFICATION_REJECT.
404     */
405    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
406
407    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
408
409    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
410            DEFAULT_CONTAINER_PACKAGE,
411            "com.android.defcontainer.DefaultContainerService");
412
413    private static final String KILL_APP_REASON_GIDS_CHANGED =
414            "permission grant or revoke changed gids";
415
416    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
417            "permissions revoked";
418
419    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
420
421    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
422
423    /** Permission grant: not grant the permission. */
424    private static final int GRANT_DENIED = 1;
425
426    /** Permission grant: grant the permission as an install permission. */
427    private static final int GRANT_INSTALL = 2;
428
429    /** Permission grant: grant the permission as a runtime one. */
430    private static final int GRANT_RUNTIME = 3;
431
432    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
433    private static final int GRANT_UPGRADE = 4;
434
435    /** Canonical intent used to identify what counts as a "web browser" app */
436    private static final Intent sBrowserIntent;
437    static {
438        sBrowserIntent = new Intent();
439        sBrowserIntent.setAction(Intent.ACTION_VIEW);
440        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
441        sBrowserIntent.setData(Uri.parse("http:"));
442    }
443
444    final ServiceThread mHandlerThread;
445
446    final PackageHandler mHandler;
447
448    /**
449     * Messages for {@link #mHandler} that need to wait for system ready before
450     * being dispatched.
451     */
452    private ArrayList<Message> mPostSystemReadyMessages;
453
454    final int mSdkVersion = Build.VERSION.SDK_INT;
455
456    final Context mContext;
457    final boolean mFactoryTest;
458    final boolean mOnlyCore;
459    final DisplayMetrics mMetrics;
460    final int mDefParseFlags;
461    final String[] mSeparateProcesses;
462    final boolean mIsUpgrade;
463
464    /** The location for ASEC container files on internal storage. */
465    final String mAsecInternalPath;
466
467    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
468    // LOCK HELD.  Can be called with mInstallLock held.
469    @GuardedBy("mInstallLock")
470    final Installer mInstaller;
471
472    /** Directory where installed third-party apps stored */
473    final File mAppInstallDir;
474    final File mEphemeralInstallDir;
475
476    /**
477     * Directory to which applications installed internally have their
478     * 32 bit native libraries copied.
479     */
480    private File mAppLib32InstallDir;
481
482    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
483    // apps.
484    final File mDrmAppPrivateInstallDir;
485
486    // ----------------------------------------------------------------
487
488    // Lock for state used when installing and doing other long running
489    // operations.  Methods that must be called with this lock held have
490    // the suffix "LI".
491    final Object mInstallLock = new Object();
492
493    // ----------------------------------------------------------------
494
495    // Keys are String (package name), values are Package.  This also serves
496    // as the lock for the global state.  Methods that must be called with
497    // this lock held have the prefix "LP".
498    @GuardedBy("mPackages")
499    final ArrayMap<String, PackageParser.Package> mPackages =
500            new ArrayMap<String, PackageParser.Package>();
501
502    // Tracks available target package names -> overlay package paths.
503    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
504        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
505
506    /**
507     * Tracks new system packages [received in an OTA] that we expect to
508     * find updated user-installed versions. Keys are package name, values
509     * are package location.
510     */
511    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
512
513    /**
514     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
515     */
516    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
517    /**
518     * Whether or not system app permissions should be promoted from install to runtime.
519     */
520    boolean mPromoteSystemApps;
521
522    final Settings mSettings;
523    boolean mRestoredSettings;
524
525    // System configuration read by SystemConfig.
526    final int[] mGlobalGids;
527    final SparseArray<ArraySet<String>> mSystemPermissions;
528    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
529
530    // If mac_permissions.xml was found for seinfo labeling.
531    boolean mFoundPolicyFile;
532
533    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
534
535    public static final class SharedLibraryEntry {
536        public final String path;
537        public final String apk;
538
539        SharedLibraryEntry(String _path, String _apk) {
540            path = _path;
541            apk = _apk;
542        }
543    }
544
545    // Currently known shared libraries.
546    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
547            new ArrayMap<String, SharedLibraryEntry>();
548
549    // All available activities, for your resolving pleasure.
550    final ActivityIntentResolver mActivities =
551            new ActivityIntentResolver();
552
553    // All available receivers, for your resolving pleasure.
554    final ActivityIntentResolver mReceivers =
555            new ActivityIntentResolver();
556
557    // All available services, for your resolving pleasure.
558    final ServiceIntentResolver mServices = new ServiceIntentResolver();
559
560    // All available providers, for your resolving pleasure.
561    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
562
563    // Mapping from provider base names (first directory in content URI codePath)
564    // to the provider information.
565    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
566            new ArrayMap<String, PackageParser.Provider>();
567
568    // Mapping from instrumentation class names to info about them.
569    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
570            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
571
572    // Mapping from permission names to info about them.
573    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
574            new ArrayMap<String, PackageParser.PermissionGroup>();
575
576    // Packages whose data we have transfered into another package, thus
577    // should no longer exist.
578    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
579
580    // Broadcast actions that are only available to the system.
581    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
582
583    /** List of packages waiting for verification. */
584    final SparseArray<PackageVerificationState> mPendingVerification
585            = new SparseArray<PackageVerificationState>();
586
587    /** Set of packages associated with each app op permission. */
588    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
589
590    final PackageInstallerService mInstallerService;
591
592    private final PackageDexOptimizer mPackageDexOptimizer;
593
594    private AtomicInteger mNextMoveId = new AtomicInteger();
595    private final MoveCallbacks mMoveCallbacks;
596
597    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
598
599    // Cache of users who need badging.
600    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
601
602    /** Token for keys in mPendingVerification. */
603    private int mPendingVerificationToken = 0;
604
605    volatile boolean mSystemReady;
606    volatile boolean mSafeMode;
607    volatile boolean mHasSystemUidErrors;
608
609    ApplicationInfo mAndroidApplication;
610    final ActivityInfo mResolveActivity = new ActivityInfo();
611    final ResolveInfo mResolveInfo = new ResolveInfo();
612    ComponentName mResolveComponentName;
613    PackageParser.Package mPlatformPackage;
614    ComponentName mCustomResolverComponentName;
615
616    boolean mResolverReplaced = false;
617
618    private final @Nullable ComponentName mIntentFilterVerifierComponent;
619    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
620
621    private int mIntentFilterVerificationToken = 0;
622
623    /** Component that knows whether or not an ephemeral application exists */
624    final ComponentName mEphemeralResolverComponent;
625    /** The service connection to the ephemeral resolver */
626    final EphemeralResolverConnection mEphemeralResolverConnection;
627
628    /** Component used to install ephemeral applications */
629    final ComponentName mEphemeralInstallerComponent;
630    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
631    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
632
633    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
634            = new SparseArray<IntentFilterVerificationState>();
635
636    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
637            new DefaultPermissionGrantPolicy(this);
638
639    // List of packages names to keep cached, even if they are uninstalled for all users
640    private List<String> mKeepUninstalledPackages;
641
642    private static class IFVerificationParams {
643        PackageParser.Package pkg;
644        boolean replacing;
645        int userId;
646        int verifierUid;
647
648        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
649                int _userId, int _verifierUid) {
650            pkg = _pkg;
651            replacing = _replacing;
652            userId = _userId;
653            replacing = _replacing;
654            verifierUid = _verifierUid;
655        }
656    }
657
658    private interface IntentFilterVerifier<T extends IntentFilter> {
659        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
660                                               T filter, String packageName);
661        void startVerifications(int userId);
662        void receiveVerificationResponse(int verificationId);
663    }
664
665    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
666        private Context mContext;
667        private ComponentName mIntentFilterVerifierComponent;
668        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
669
670        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
671            mContext = context;
672            mIntentFilterVerifierComponent = verifierComponent;
673        }
674
675        private String getDefaultScheme() {
676            return IntentFilter.SCHEME_HTTPS;
677        }
678
679        @Override
680        public void startVerifications(int userId) {
681            // Launch verifications requests
682            int count = mCurrentIntentFilterVerifications.size();
683            for (int n=0; n<count; n++) {
684                int verificationId = mCurrentIntentFilterVerifications.get(n);
685                final IntentFilterVerificationState ivs =
686                        mIntentFilterVerificationStates.get(verificationId);
687
688                String packageName = ivs.getPackageName();
689
690                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
691                final int filterCount = filters.size();
692                ArraySet<String> domainsSet = new ArraySet<>();
693                for (int m=0; m<filterCount; m++) {
694                    PackageParser.ActivityIntentInfo filter = filters.get(m);
695                    domainsSet.addAll(filter.getHostsList());
696                }
697                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
698                synchronized (mPackages) {
699                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
700                            packageName, domainsList) != null) {
701                        scheduleWriteSettingsLocked();
702                    }
703                }
704                sendVerificationRequest(userId, verificationId, ivs);
705            }
706            mCurrentIntentFilterVerifications.clear();
707        }
708
709        private void sendVerificationRequest(int userId, int verificationId,
710                IntentFilterVerificationState ivs) {
711
712            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
713            verificationIntent.putExtra(
714                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
715                    verificationId);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
718                    getDefaultScheme());
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
721                    ivs.getHostsString());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
724                    ivs.getPackageName());
725            verificationIntent.setComponent(mIntentFilterVerifierComponent);
726            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
727
728            UserHandle user = new UserHandle(userId);
729            mContext.sendBroadcastAsUser(verificationIntent, user);
730            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
731                    "Sending IntentFilter verification broadcast");
732        }
733
734        public void receiveVerificationResponse(int verificationId) {
735            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
736
737            final boolean verified = ivs.isVerified();
738
739            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
740            final int count = filters.size();
741            if (DEBUG_DOMAIN_VERIFICATION) {
742                Slog.i(TAG, "Received verification response " + verificationId
743                        + " for " + count + " filters, verified=" + verified);
744            }
745            for (int n=0; n<count; n++) {
746                PackageParser.ActivityIntentInfo filter = filters.get(n);
747                filter.setVerified(verified);
748
749                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
750                        + " verified with result:" + verified + " and hosts:"
751                        + ivs.getHostsString());
752            }
753
754            mIntentFilterVerificationStates.remove(verificationId);
755
756            final String packageName = ivs.getPackageName();
757            IntentFilterVerificationInfo ivi = null;
758
759            synchronized (mPackages) {
760                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
761            }
762            if (ivi == null) {
763                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
764                        + verificationId + " packageName:" + packageName);
765                return;
766            }
767            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
768                    "Updating IntentFilterVerificationInfo for package " + packageName
769                            +" verificationId:" + verificationId);
770
771            synchronized (mPackages) {
772                if (verified) {
773                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
774                } else {
775                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
776                }
777                scheduleWriteSettingsLocked();
778
779                final int userId = ivs.getUserId();
780                if (userId != UserHandle.USER_ALL) {
781                    final int userStatus =
782                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
783
784                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
785                    boolean needUpdate = false;
786
787                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
788                    // already been set by the User thru the Disambiguation dialog
789                    switch (userStatus) {
790                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
791                            if (verified) {
792                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
793                            } else {
794                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
795                            }
796                            needUpdate = true;
797                            break;
798
799                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
800                            if (verified) {
801                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
802                                needUpdate = true;
803                            }
804                            break;
805
806                        default:
807                            // Nothing to do
808                    }
809
810                    if (needUpdate) {
811                        mSettings.updateIntentFilterVerificationStatusLPw(
812                                packageName, updatedStatus, userId);
813                        scheduleWritePackageRestrictionsLocked(userId);
814                    }
815                }
816            }
817        }
818
819        @Override
820        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
821                    ActivityIntentInfo filter, String packageName) {
822            if (!hasValidDomains(filter)) {
823                return false;
824            }
825            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
826            if (ivs == null) {
827                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
828                        packageName);
829            }
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
832            }
833            ivs.addFilter(filter);
834            return true;
835        }
836
837        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
838                int userId, int verificationId, String packageName) {
839            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
840                    verifierUid, userId, packageName);
841            ivs.setPendingState();
842            synchronized (mPackages) {
843                mIntentFilterVerificationStates.append(verificationId, ivs);
844                mCurrentIntentFilterVerifications.add(verificationId);
845            }
846            return ivs;
847        }
848    }
849
850    private static boolean hasValidDomains(ActivityIntentInfo filter) {
851        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
852                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
853                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
854    }
855
856    // Set of pending broadcasts for aggregating enable/disable of components.
857    static class PendingPackageBroadcasts {
858        // for each user id, a map of <package name -> components within that package>
859        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
860
861        public PendingPackageBroadcasts() {
862            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
863        }
864
865        public ArrayList<String> get(int userId, String packageName) {
866            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
867            return packages.get(packageName);
868        }
869
870        public void put(int userId, String packageName, ArrayList<String> components) {
871            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
872            packages.put(packageName, components);
873        }
874
875        public void remove(int userId, String packageName) {
876            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
877            if (packages != null) {
878                packages.remove(packageName);
879            }
880        }
881
882        public void remove(int userId) {
883            mUidMap.remove(userId);
884        }
885
886        public int userIdCount() {
887            return mUidMap.size();
888        }
889
890        public int userIdAt(int n) {
891            return mUidMap.keyAt(n);
892        }
893
894        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
895            return mUidMap.get(userId);
896        }
897
898        public int size() {
899            // total number of pending broadcast entries across all userIds
900            int num = 0;
901            for (int i = 0; i< mUidMap.size(); i++) {
902                num += mUidMap.valueAt(i).size();
903            }
904            return num;
905        }
906
907        public void clear() {
908            mUidMap.clear();
909        }
910
911        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
912            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
913            if (map == null) {
914                map = new ArrayMap<String, ArrayList<String>>();
915                mUidMap.put(userId, map);
916            }
917            return map;
918        }
919    }
920    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
921
922    // Service Connection to remote media container service to copy
923    // package uri's from external media onto secure containers
924    // or internal storage.
925    private IMediaContainerService mContainerService = null;
926
927    static final int SEND_PENDING_BROADCAST = 1;
928    static final int MCS_BOUND = 3;
929    static final int END_COPY = 4;
930    static final int INIT_COPY = 5;
931    static final int MCS_UNBIND = 6;
932    static final int START_CLEANING_PACKAGE = 7;
933    static final int FIND_INSTALL_LOC = 8;
934    static final int POST_INSTALL = 9;
935    static final int MCS_RECONNECT = 10;
936    static final int MCS_GIVE_UP = 11;
937    static final int UPDATED_MEDIA_STATUS = 12;
938    static final int WRITE_SETTINGS = 13;
939    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
940    static final int PACKAGE_VERIFIED = 15;
941    static final int CHECK_PENDING_VERIFICATION = 16;
942    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
943    static final int INTENT_FILTER_VERIFIED = 18;
944
945    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
946
947    // Delay time in millisecs
948    static final int BROADCAST_DELAY = 10 * 1000;
949
950    static UserManagerService sUserManager;
951
952    // Stores a list of users whose package restrictions file needs to be updated
953    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
954
955    final private DefaultContainerConnection mDefContainerConn =
956            new DefaultContainerConnection();
957    class DefaultContainerConnection implements ServiceConnection {
958        public void onServiceConnected(ComponentName name, IBinder service) {
959            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
960            IMediaContainerService imcs =
961                IMediaContainerService.Stub.asInterface(service);
962            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
963        }
964
965        public void onServiceDisconnected(ComponentName name) {
966            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
967        }
968    }
969
970    // Recordkeeping of restore-after-install operations that are currently in flight
971    // between the Package Manager and the Backup Manager
972    static class PostInstallData {
973        public InstallArgs args;
974        public PackageInstalledInfo res;
975
976        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
977            args = _a;
978            res = _r;
979        }
980    }
981
982    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
983    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
984
985    // XML tags for backup/restore of various bits of state
986    private static final String TAG_PREFERRED_BACKUP = "pa";
987    private static final String TAG_DEFAULT_APPS = "da";
988    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
989
990    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
991    private static final String TAG_ALL_GRANTS = "rt-grants";
992    private static final String TAG_GRANT = "grant";
993    private static final String ATTR_PACKAGE_NAME = "pkg";
994
995    private static final String TAG_PERMISSION = "perm";
996    private static final String ATTR_PERMISSION_NAME = "name";
997    private static final String ATTR_IS_GRANTED = "g";
998    private static final String ATTR_USER_SET = "set";
999    private static final String ATTR_USER_FIXED = "fixed";
1000    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1001
1002    // System/policy permission grants are not backed up
1003    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1004            FLAG_PERMISSION_POLICY_FIXED
1005            | FLAG_PERMISSION_SYSTEM_FIXED
1006            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1007
1008    // And we back up these user-adjusted states
1009    private static final int USER_RUNTIME_GRANT_MASK =
1010            FLAG_PERMISSION_USER_SET
1011            | FLAG_PERMISSION_USER_FIXED
1012            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1013
1014    final @Nullable String mRequiredVerifierPackage;
1015    final @Nullable String mRequiredInstallerPackage;
1016
1017    private final PackageUsage mPackageUsage = new PackageUsage();
1018
1019    private class PackageUsage {
1020        private static final int WRITE_INTERVAL
1021            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1022
1023        private final Object mFileLock = new Object();
1024        private final AtomicLong mLastWritten = new AtomicLong(0);
1025        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1026
1027        private boolean mIsHistoricalPackageUsageAvailable = true;
1028
1029        boolean isHistoricalPackageUsageAvailable() {
1030            return mIsHistoricalPackageUsageAvailable;
1031        }
1032
1033        void write(boolean force) {
1034            if (force) {
1035                writeInternal();
1036                return;
1037            }
1038            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1039                && !DEBUG_DEXOPT) {
1040                return;
1041            }
1042            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1043                new Thread("PackageUsage_DiskWriter") {
1044                    @Override
1045                    public void run() {
1046                        try {
1047                            writeInternal();
1048                        } finally {
1049                            mBackgroundWriteRunning.set(false);
1050                        }
1051                    }
1052                }.start();
1053            }
1054        }
1055
1056        private void writeInternal() {
1057            synchronized (mPackages) {
1058                synchronized (mFileLock) {
1059                    AtomicFile file = getFile();
1060                    FileOutputStream f = null;
1061                    try {
1062                        f = file.startWrite();
1063                        BufferedOutputStream out = new BufferedOutputStream(f);
1064                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1065                        StringBuilder sb = new StringBuilder();
1066                        for (PackageParser.Package pkg : mPackages.values()) {
1067                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1068                                continue;
1069                            }
1070                            sb.setLength(0);
1071                            sb.append(pkg.packageName);
1072                            sb.append(' ');
1073                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1074                            sb.append('\n');
1075                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1076                        }
1077                        out.flush();
1078                        file.finishWrite(f);
1079                    } catch (IOException e) {
1080                        if (f != null) {
1081                            file.failWrite(f);
1082                        }
1083                        Log.e(TAG, "Failed to write package usage times", e);
1084                    }
1085                }
1086            }
1087            mLastWritten.set(SystemClock.elapsedRealtime());
1088        }
1089
1090        void readLP() {
1091            synchronized (mFileLock) {
1092                AtomicFile file = getFile();
1093                BufferedInputStream in = null;
1094                try {
1095                    in = new BufferedInputStream(file.openRead());
1096                    StringBuffer sb = new StringBuffer();
1097                    while (true) {
1098                        String packageName = readToken(in, sb, ' ');
1099                        if (packageName == null) {
1100                            break;
1101                        }
1102                        String timeInMillisString = readToken(in, sb, '\n');
1103                        if (timeInMillisString == null) {
1104                            throw new IOException("Failed to find last usage time for package "
1105                                                  + packageName);
1106                        }
1107                        PackageParser.Package pkg = mPackages.get(packageName);
1108                        if (pkg == null) {
1109                            continue;
1110                        }
1111                        long timeInMillis;
1112                        try {
1113                            timeInMillis = Long.parseLong(timeInMillisString);
1114                        } catch (NumberFormatException e) {
1115                            throw new IOException("Failed to parse " + timeInMillisString
1116                                                  + " as a long.", e);
1117                        }
1118                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1119                    }
1120                } catch (FileNotFoundException expected) {
1121                    mIsHistoricalPackageUsageAvailable = false;
1122                } catch (IOException e) {
1123                    Log.w(TAG, "Failed to read package usage times", e);
1124                } finally {
1125                    IoUtils.closeQuietly(in);
1126                }
1127            }
1128            mLastWritten.set(SystemClock.elapsedRealtime());
1129        }
1130
1131        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1132                throws IOException {
1133            sb.setLength(0);
1134            while (true) {
1135                int ch = in.read();
1136                if (ch == -1) {
1137                    if (sb.length() == 0) {
1138                        return null;
1139                    }
1140                    throw new IOException("Unexpected EOF");
1141                }
1142                if (ch == endOfToken) {
1143                    return sb.toString();
1144                }
1145                sb.append((char)ch);
1146            }
1147        }
1148
1149        private AtomicFile getFile() {
1150            File dataDir = Environment.getDataDirectory();
1151            File systemDir = new File(dataDir, "system");
1152            File fname = new File(systemDir, "package-usage.list");
1153            return new AtomicFile(fname);
1154        }
1155    }
1156
1157    class PackageHandler extends Handler {
1158        private boolean mBound = false;
1159        final ArrayList<HandlerParams> mPendingInstalls =
1160            new ArrayList<HandlerParams>();
1161
1162        private boolean connectToService() {
1163            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1164                    " DefaultContainerService");
1165            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1166            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1167            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1168                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1169                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170                mBound = true;
1171                return true;
1172            }
1173            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174            return false;
1175        }
1176
1177        private void disconnectService() {
1178            mContainerService = null;
1179            mBound = false;
1180            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1181            mContext.unbindService(mDefContainerConn);
1182            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1183        }
1184
1185        PackageHandler(Looper looper) {
1186            super(looper);
1187        }
1188
1189        public void handleMessage(Message msg) {
1190            try {
1191                doHandleMessage(msg);
1192            } finally {
1193                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1194            }
1195        }
1196
1197        void doHandleMessage(Message msg) {
1198            switch (msg.what) {
1199                case INIT_COPY: {
1200                    HandlerParams params = (HandlerParams) msg.obj;
1201                    int idx = mPendingInstalls.size();
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1203                    // If a bind was already initiated we dont really
1204                    // need to do anything. The pending install
1205                    // will be processed later on.
1206                    if (!mBound) {
1207                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                System.identityHashCode(mHandler));
1209                        // If this is the only one pending we might
1210                        // have to bind to the service again.
1211                        if (!connectToService()) {
1212                            Slog.e(TAG, "Failed to bind to media container service");
1213                            params.serviceError();
1214                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                    System.identityHashCode(mHandler));
1216                            if (params.traceMethod != null) {
1217                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1218                                        params.traceCookie);
1219                            }
1220                            return;
1221                        } else {
1222                            // Once we bind to the service, the first
1223                            // pending request will be processed.
1224                            mPendingInstalls.add(idx, params);
1225                        }
1226                    } else {
1227                        mPendingInstalls.add(idx, params);
1228                        // Already bound to the service. Just make
1229                        // sure we trigger off processing the first request.
1230                        if (idx == 0) {
1231                            mHandler.sendEmptyMessage(MCS_BOUND);
1232                        }
1233                    }
1234                    break;
1235                }
1236                case MCS_BOUND: {
1237                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1238                    if (msg.obj != null) {
1239                        mContainerService = (IMediaContainerService) msg.obj;
1240                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1241                                System.identityHashCode(mHandler));
1242                    }
1243                    if (mContainerService == null) {
1244                        if (!mBound) {
1245                            // Something seriously wrong since we are not bound and we are not
1246                            // waiting for connection. Bail out.
1247                            Slog.e(TAG, "Cannot bind to media container service");
1248                            for (HandlerParams params : mPendingInstalls) {
1249                                // Indicate service bind error
1250                                params.serviceError();
1251                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1252                                        System.identityHashCode(params));
1253                                if (params.traceMethod != null) {
1254                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1255                                            params.traceMethod, params.traceCookie);
1256                                }
1257                                return;
1258                            }
1259                            mPendingInstalls.clear();
1260                        } else {
1261                            Slog.w(TAG, "Waiting to connect to media container service");
1262                        }
1263                    } else if (mPendingInstalls.size() > 0) {
1264                        HandlerParams params = mPendingInstalls.get(0);
1265                        if (params != null) {
1266                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1267                                    System.identityHashCode(params));
1268                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1269                            if (params.startCopy()) {
1270                                // We are done...  look for more work or to
1271                                // go idle.
1272                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                        "Checking for more work or unbind...");
1274                                // Delete pending install
1275                                if (mPendingInstalls.size() > 0) {
1276                                    mPendingInstalls.remove(0);
1277                                }
1278                                if (mPendingInstalls.size() == 0) {
1279                                    if (mBound) {
1280                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1281                                                "Posting delayed MCS_UNBIND");
1282                                        removeMessages(MCS_UNBIND);
1283                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1284                                        // Unbind after a little delay, to avoid
1285                                        // continual thrashing.
1286                                        sendMessageDelayed(ubmsg, 10000);
1287                                    }
1288                                } else {
1289                                    // There are more pending requests in queue.
1290                                    // Just post MCS_BOUND message to trigger processing
1291                                    // of next pending install.
1292                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1293                                            "Posting MCS_BOUND for next work");
1294                                    mHandler.sendEmptyMessage(MCS_BOUND);
1295                                }
1296                            }
1297                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1298                        }
1299                    } else {
1300                        // Should never happen ideally.
1301                        Slog.w(TAG, "Empty queue");
1302                    }
1303                    break;
1304                }
1305                case MCS_RECONNECT: {
1306                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1307                    if (mPendingInstalls.size() > 0) {
1308                        if (mBound) {
1309                            disconnectService();
1310                        }
1311                        if (!connectToService()) {
1312                            Slog.e(TAG, "Failed to bind to media container service");
1313                            for (HandlerParams params : mPendingInstalls) {
1314                                // Indicate service bind error
1315                                params.serviceError();
1316                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                                        System.identityHashCode(params));
1318                            }
1319                            mPendingInstalls.clear();
1320                        }
1321                    }
1322                    break;
1323                }
1324                case MCS_UNBIND: {
1325                    // If there is no actual work left, then time to unbind.
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1327
1328                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1329                        if (mBound) {
1330                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1331
1332                            disconnectService();
1333                        }
1334                    } else if (mPendingInstalls.size() > 0) {
1335                        // There are more pending requests in queue.
1336                        // Just post MCS_BOUND message to trigger processing
1337                        // of next pending install.
1338                        mHandler.sendEmptyMessage(MCS_BOUND);
1339                    }
1340
1341                    break;
1342                }
1343                case MCS_GIVE_UP: {
1344                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1345                    HandlerParams params = mPendingInstalls.remove(0);
1346                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                            System.identityHashCode(params));
1348                    break;
1349                }
1350                case SEND_PENDING_BROADCAST: {
1351                    String packages[];
1352                    ArrayList<String> components[];
1353                    int size = 0;
1354                    int uids[];
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356                    synchronized (mPackages) {
1357                        if (mPendingBroadcasts == null) {
1358                            return;
1359                        }
1360                        size = mPendingBroadcasts.size();
1361                        if (size <= 0) {
1362                            // Nothing to be done. Just return
1363                            return;
1364                        }
1365                        packages = new String[size];
1366                        components = new ArrayList[size];
1367                        uids = new int[size];
1368                        int i = 0;  // filling out the above arrays
1369
1370                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1371                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1372                            Iterator<Map.Entry<String, ArrayList<String>>> it
1373                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1374                                            .entrySet().iterator();
1375                            while (it.hasNext() && i < size) {
1376                                Map.Entry<String, ArrayList<String>> ent = it.next();
1377                                packages[i] = ent.getKey();
1378                                components[i] = ent.getValue();
1379                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1380                                uids[i] = (ps != null)
1381                                        ? UserHandle.getUid(packageUserId, ps.appId)
1382                                        : -1;
1383                                i++;
1384                            }
1385                        }
1386                        size = i;
1387                        mPendingBroadcasts.clear();
1388                    }
1389                    // Send broadcasts
1390                    for (int i = 0; i < size; i++) {
1391                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1392                    }
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1394                    break;
1395                }
1396                case START_CLEANING_PACKAGE: {
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398                    final String packageName = (String)msg.obj;
1399                    final int userId = msg.arg1;
1400                    final boolean andCode = msg.arg2 != 0;
1401                    synchronized (mPackages) {
1402                        if (userId == UserHandle.USER_ALL) {
1403                            int[] users = sUserManager.getUserIds();
1404                            for (int user : users) {
1405                                mSettings.addPackageToCleanLPw(
1406                                        new PackageCleanItem(user, packageName, andCode));
1407                            }
1408                        } else {
1409                            mSettings.addPackageToCleanLPw(
1410                                    new PackageCleanItem(userId, packageName, andCode));
1411                        }
1412                    }
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                    startCleaningPackages();
1415                } break;
1416                case POST_INSTALL: {
1417                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1418
1419                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1420                    mRunningInstalls.delete(msg.arg1);
1421
1422                    if (data != null) {
1423                        InstallArgs args = data.args;
1424                        PackageInstalledInfo parentRes = data.res;
1425
1426                        final boolean grantPermissions = (args.installFlags
1427                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1428                        final String[] grantedPermissions = args.installGrantPermissions;
1429
1430                        // Handle the parent package
1431                        handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, grantedPermissions,
1440                                    args.observer);
1441                        }
1442
1443                        // Log tracing if needed
1444                        if (args.traceMethod != null) {
1445                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1446                                    args.traceCookie);
1447                        }
1448                    } else {
1449                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1450                    }
1451
1452                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1453                } break;
1454                case UPDATED_MEDIA_STATUS: {
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1456                    boolean reportStatus = msg.arg1 == 1;
1457                    boolean doGc = msg.arg2 == 1;
1458                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1459                    if (doGc) {
1460                        // Force a gc to clear up stale containers.
1461                        Runtime.getRuntime().gc();
1462                    }
1463                    if (msg.obj != null) {
1464                        @SuppressWarnings("unchecked")
1465                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1466                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1467                        // Unload containers
1468                        unloadAllContainers(args);
1469                    }
1470                    if (reportStatus) {
1471                        try {
1472                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1473                            PackageHelper.getMountService().finishMediaUpdate();
1474                        } catch (RemoteException e) {
1475                            Log.e(TAG, "MountService not running?");
1476                        }
1477                    }
1478                } break;
1479                case WRITE_SETTINGS: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_SETTINGS);
1483                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1484                        mSettings.writeLPr();
1485                        mDirtyUsers.clear();
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                } break;
1489                case WRITE_PACKAGE_RESTRICTIONS: {
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1491                    synchronized (mPackages) {
1492                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1493                        for (int userId : mDirtyUsers) {
1494                            mSettings.writePackageRestrictionsLPr(userId);
1495                        }
1496                        mDirtyUsers.clear();
1497                    }
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1499                } break;
1500                case CHECK_PENDING_VERIFICATION: {
1501                    final int verificationId = msg.arg1;
1502                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1503
1504                    if ((state != null) && !state.timeoutExtended()) {
1505                        final InstallArgs args = state.getInstallArgs();
1506                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1507
1508                        Slog.i(TAG, "Verification timed out for " + originUri);
1509                        mPendingVerification.remove(verificationId);
1510
1511                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1512
1513                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1514                            Slog.i(TAG, "Continuing with installation of " + originUri);
1515                            state.setVerifierResponse(Binder.getCallingUid(),
1516                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1517                            broadcastPackageVerified(verificationId, originUri,
1518                                    PackageManager.VERIFICATION_ALLOW,
1519                                    state.getInstallArgs().getUser());
1520                            try {
1521                                ret = args.copyApk(mContainerService, true);
1522                            } catch (RemoteException e) {
1523                                Slog.e(TAG, "Could not contact the ContainerService");
1524                            }
1525                        } else {
1526                            broadcastPackageVerified(verificationId, originUri,
1527                                    PackageManager.VERIFICATION_REJECT,
1528                                    state.getInstallArgs().getUser());
1529                        }
1530
1531                        Trace.asyncTraceEnd(
1532                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1533
1534                        processPendingInstall(args, ret);
1535                        mHandler.sendEmptyMessage(MCS_UNBIND);
1536                    }
1537                    break;
1538                }
1539                case PACKAGE_VERIFIED: {
1540                    final int verificationId = msg.arg1;
1541
1542                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1543                    if (state == null) {
1544                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1545                        break;
1546                    }
1547
1548                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1549
1550                    state.setVerifierResponse(response.callerUid, response.code);
1551
1552                    if (state.isVerificationComplete()) {
1553                        mPendingVerification.remove(verificationId);
1554
1555                        final InstallArgs args = state.getInstallArgs();
1556                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1557
1558                        int ret;
1559                        if (state.isInstallAllowed()) {
1560                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1561                            broadcastPackageVerified(verificationId, originUri,
1562                                    response.code, state.getInstallArgs().getUser());
1563                            try {
1564                                ret = args.copyApk(mContainerService, true);
1565                            } catch (RemoteException e) {
1566                                Slog.e(TAG, "Could not contact the ContainerService");
1567                            }
1568                        } else {
1569                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1570                        }
1571
1572                        Trace.asyncTraceEnd(
1573                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1574
1575                        processPendingInstall(args, ret);
1576                        mHandler.sendEmptyMessage(MCS_UNBIND);
1577                    }
1578
1579                    break;
1580                }
1581                case START_INTENT_FILTER_VERIFICATIONS: {
1582                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1583                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1584                            params.replacing, params.pkg);
1585                    break;
1586                }
1587                case INTENT_FILTER_VERIFIED: {
1588                    final int verificationId = msg.arg1;
1589
1590                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1591                            verificationId);
1592                    if (state == null) {
1593                        Slog.w(TAG, "Invalid IntentFilter verification token "
1594                                + verificationId + " received");
1595                        break;
1596                    }
1597
1598                    final int userId = state.getUserId();
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "Processing IntentFilter verification with token:"
1602                            + verificationId + " and userId:" + userId);
1603
1604                    final IntentFilterVerificationResponse response =
1605                            (IntentFilterVerificationResponse) msg.obj;
1606
1607                    state.setVerifierResponse(response.callerUid, response.code);
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "IntentFilter verification with token:" + verificationId
1611                            + " and userId:" + userId
1612                            + " is settings verifier response with response code:"
1613                            + response.code);
1614
1615                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1616                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1617                                + response.getFailedDomainsString());
1618                    }
1619
1620                    if (state.isVerificationComplete()) {
1621                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1622                    } else {
1623                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1624                                "IntentFilter verification with token:" + verificationId
1625                                + " was not said to be complete");
1626                    }
1627
1628                    break;
1629                }
1630            }
1631        }
1632    }
1633
1634    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1635            String[] grantedPermissions, IPackageInstallObserver2 installObserver) {
1636        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1637            // Send the removed broadcasts
1638            if (res.removedInfo != null) {
1639                res.removedInfo.sendPackageRemovedBroadcasts();
1640            }
1641
1642            // Now that we successfully installed the package, grant runtime
1643            // permissions if requested before broadcasting the install.
1644            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1645                    >= Build.VERSION_CODES.M) {
1646                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1647            }
1648
1649            final boolean update = res.removedInfo != null
1650                    && res.removedInfo.removedPackage != null;
1651
1652            // If this is the first time we have child packages for a disabled privileged
1653            // app that had no children, we grant requested runtime permissions to the new
1654            // children if the parent on the system image had them already granted.
1655            if (res.pkg.parentPackage != null) {
1656                synchronized (mPackages) {
1657                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1658                }
1659            }
1660
1661            synchronized (mPackages) {
1662                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1663            }
1664
1665            final String packageName = res.pkg.applicationInfo.packageName;
1666            Bundle extras = new Bundle(1);
1667            extras.putInt(Intent.EXTRA_UID, res.uid);
1668
1669            // Determine the set of users who are adding this package for
1670            // the first time vs. those who are seeing an update.
1671            int[] firstUsers = EMPTY_INT_ARRAY;
1672            int[] updateUsers = EMPTY_INT_ARRAY;
1673            if (res.origUsers == null || res.origUsers.length == 0) {
1674                firstUsers = res.newUsers;
1675            } else {
1676                for (int newUser : res.newUsers) {
1677                    boolean isNew = true;
1678                    for (int origUser : res.origUsers) {
1679                        if (origUser == newUser) {
1680                            isNew = false;
1681                            break;
1682                        }
1683                    }
1684                    if (isNew) {
1685                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1686                    } else {
1687                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1688                    }
1689                }
1690            }
1691
1692            // Send installed broadcasts if the install/update is not ephemeral
1693            if (!isEphemeral(res.pkg)) {
1694                // Send added for users that see the package for the first time
1695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1696                        extras, 0 /*flags*/, null /*targetPackage*/,
1697                        null /*finishedReceiver*/, firstUsers);
1698
1699                // Send added for users that don't see the package for the first time
1700                if (update) {
1701                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1702                }
1703                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1704                        extras, 0 /*flags*/, null /*targetPackage*/,
1705                        null /*finishedReceiver*/, updateUsers);
1706
1707                // Send replaced for users that don't see the package for the first time
1708                if (update) {
1709                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1710                            packageName, extras, 0 /*flags*/,
1711                            null /*targetPackage*/, null /*finishedReceiver*/,
1712                            updateUsers);
1713                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1714                            null /*package*/, null /*extras*/, 0 /*flags*/,
1715                            packageName /*targetPackage*/,
1716                            null /*finishedReceiver*/, updateUsers);
1717                }
1718
1719                // Send broadcast package appeared if forward locked/external for all users
1720                // treat asec-hosted packages like removable media on upgrade
1721                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1722                    if (DEBUG_INSTALL) {
1723                        Slog.i(TAG, "upgrading pkg " + res.pkg
1724                                + " is ASEC-hosted -> AVAILABLE");
1725                    }
1726                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1727                    ArrayList<String> pkgList = new ArrayList<>(1);
1728                    pkgList.add(packageName);
1729                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1730                }
1731            }
1732
1733            // Work that needs to happen on first install within each user
1734            if (firstUsers != null && firstUsers.length > 0) {
1735                synchronized (mPackages) {
1736                    for (int userId : firstUsers) {
1737                        // If this app is a browser and it's newly-installed for some
1738                        // users, clear any default-browser state in those users. The
1739                        // app's nature doesn't depend on the user, so we can just check
1740                        // its browser nature in any user and generalize.
1741                        if (packageIsBrowser(packageName, userId)) {
1742                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1743                        }
1744
1745                        // We may also need to apply pending (restored) runtime
1746                        // permission grants within these users.
1747                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1748                    }
1749                }
1750            }
1751
1752            // Log current value of "unknown sources" setting
1753            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1754                    getUnknownSourcesSettings());
1755
1756            // Force a gc to clear up things
1757            Runtime.getRuntime().gc();
1758
1759            // Remove the replaced package's older resources safely now
1760            // We delete after a gc for applications  on sdcard.
1761            if (res.removedInfo != null && res.removedInfo.args != null) {
1762                synchronized (mInstallLock) {
1763                    res.removedInfo.args.doPostDeleteLI(true);
1764                }
1765            }
1766        }
1767
1768        // If someone is watching installs - notify them
1769        if (installObserver != null) {
1770            try {
1771                Bundle extras = extrasForInstallResult(res);
1772                installObserver.onPackageInstalled(res.name, res.returnCode,
1773                        res.returnMsg, extras);
1774            } catch (RemoteException e) {
1775                Slog.i(TAG, "Observer no longer exists.");
1776            }
1777        }
1778    }
1779
1780    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1781            PackageParser.Package pkg) {
1782        if (pkg.parentPackage == null) {
1783            return;
1784        }
1785        if (pkg.requestedPermissions == null) {
1786            return;
1787        }
1788        final PackageSetting disabledSysParentPs = mSettings
1789                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1790        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1791                || !disabledSysParentPs.isPrivileged()
1792                || (disabledSysParentPs.childPackageNames != null
1793                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1794            return;
1795        }
1796        final int[] allUserIds = sUserManager.getUserIds();
1797        final int permCount = pkg.requestedPermissions.size();
1798        for (int i = 0; i < permCount; i++) {
1799            String permission = pkg.requestedPermissions.get(i);
1800            BasePermission bp = mSettings.mPermissions.get(permission);
1801            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1802                continue;
1803            }
1804            for (int userId : allUserIds) {
1805                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1806                        permission, userId)) {
1807                    grantRuntimePermission(pkg.packageName, permission, userId);
1808                }
1809            }
1810        }
1811    }
1812
1813    private StorageEventListener mStorageListener = new StorageEventListener() {
1814        @Override
1815        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1816            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1817                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1818                    final String volumeUuid = vol.getFsUuid();
1819
1820                    // Clean up any users or apps that were removed or recreated
1821                    // while this volume was missing
1822                    reconcileUsers(volumeUuid);
1823                    reconcileApps(volumeUuid);
1824
1825                    // Clean up any install sessions that expired or were
1826                    // cancelled while this volume was missing
1827                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1828
1829                    loadPrivatePackages(vol);
1830
1831                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1832                    unloadPrivatePackages(vol);
1833                }
1834            }
1835
1836            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1837                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1838                    updateExternalMediaStatus(true, false);
1839                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1840                    updateExternalMediaStatus(false, false);
1841                }
1842            }
1843        }
1844
1845        @Override
1846        public void onVolumeForgotten(String fsUuid) {
1847            if (TextUtils.isEmpty(fsUuid)) {
1848                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1849                return;
1850            }
1851
1852            // Remove any apps installed on the forgotten volume
1853            synchronized (mPackages) {
1854                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1855                for (PackageSetting ps : packages) {
1856                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1857                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1858                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1859                }
1860
1861                mSettings.onVolumeForgotten(fsUuid);
1862                mSettings.writeLPr();
1863            }
1864        }
1865    };
1866
1867    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1868            String[] grantedPermissions) {
1869        for (int userId : userIds) {
1870            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1871        }
1872
1873        // We could have touched GID membership, so flush out packages.list
1874        synchronized (mPackages) {
1875            mSettings.writePackageListLPr();
1876        }
1877    }
1878
1879    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1880            String[] grantedPermissions) {
1881        SettingBase sb = (SettingBase) pkg.mExtras;
1882        if (sb == null) {
1883            return;
1884        }
1885
1886        PermissionsState permissionsState = sb.getPermissionsState();
1887
1888        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1889                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1890
1891        synchronized (mPackages) {
1892            for (String permission : pkg.requestedPermissions) {
1893                BasePermission bp = mSettings.mPermissions.get(permission);
1894                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1895                        && (grantedPermissions == null
1896                               || ArrayUtils.contains(grantedPermissions, permission))) {
1897                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1898                    // Installer cannot change immutable permissions.
1899                    if ((flags & immutableFlags) == 0) {
1900                        grantRuntimePermission(pkg.packageName, permission, userId);
1901                    }
1902                }
1903            }
1904        }
1905    }
1906
1907    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1908        Bundle extras = null;
1909        switch (res.returnCode) {
1910            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1911                extras = new Bundle();
1912                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1913                        res.origPermission);
1914                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1915                        res.origPackage);
1916                break;
1917            }
1918            case PackageManager.INSTALL_SUCCEEDED: {
1919                extras = new Bundle();
1920                extras.putBoolean(Intent.EXTRA_REPLACING,
1921                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1922                break;
1923            }
1924        }
1925        return extras;
1926    }
1927
1928    void scheduleWriteSettingsLocked() {
1929        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1930            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1931        }
1932    }
1933
1934    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1935        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1936        scheduleWritePackageRestrictionsLocked(userId);
1937    }
1938
1939    void scheduleWritePackageRestrictionsLocked(int userId) {
1940        final int[] userIds = (userId == UserHandle.USER_ALL)
1941                ? sUserManager.getUserIds() : new int[]{userId};
1942        for (int nextUserId : userIds) {
1943            if (!sUserManager.exists(nextUserId)) return;
1944            mDirtyUsers.add(nextUserId);
1945            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1946                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1947            }
1948        }
1949    }
1950
1951    public static PackageManagerService main(Context context, Installer installer,
1952            boolean factoryTest, boolean onlyCore) {
1953        PackageManagerService m = new PackageManagerService(context, installer,
1954                factoryTest, onlyCore);
1955        m.enableSystemUserPackages();
1956        ServiceManager.addService("package", m);
1957        return m;
1958    }
1959
1960    private void enableSystemUserPackages() {
1961        if (!UserManager.isSplitSystemUser()) {
1962            return;
1963        }
1964        // For system user, enable apps based on the following conditions:
1965        // - app is whitelisted or belong to one of these groups:
1966        //   -- system app which has no launcher icons
1967        //   -- system app which has INTERACT_ACROSS_USERS permission
1968        //   -- system IME app
1969        // - app is not in the blacklist
1970        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1971        Set<String> enableApps = new ArraySet<>();
1972        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1973                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1974                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1975        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1976        enableApps.addAll(wlApps);
1977        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1978                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1979        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1980        enableApps.removeAll(blApps);
1981        Log.i(TAG, "Applications installed for system user: " + enableApps);
1982        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1983                UserHandle.SYSTEM);
1984        final int allAppsSize = allAps.size();
1985        synchronized (mPackages) {
1986            for (int i = 0; i < allAppsSize; i++) {
1987                String pName = allAps.get(i);
1988                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1989                // Should not happen, but we shouldn't be failing if it does
1990                if (pkgSetting == null) {
1991                    continue;
1992                }
1993                boolean install = enableApps.contains(pName);
1994                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1995                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1996                            + " for system user");
1997                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1998                }
1999            }
2000        }
2001    }
2002
2003    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2004        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2005                Context.DISPLAY_SERVICE);
2006        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2007    }
2008
2009    public PackageManagerService(Context context, Installer installer,
2010            boolean factoryTest, boolean onlyCore) {
2011        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2012                SystemClock.uptimeMillis());
2013
2014        if (mSdkVersion <= 0) {
2015            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2016        }
2017
2018        mContext = context;
2019        mFactoryTest = factoryTest;
2020        mOnlyCore = onlyCore;
2021        mMetrics = new DisplayMetrics();
2022        mSettings = new Settings(mPackages);
2023        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2024                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2025        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2026                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2027        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2028                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2029        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2030                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2031        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2032                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2033        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2034                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2035
2036        String separateProcesses = SystemProperties.get("debug.separate_processes");
2037        if (separateProcesses != null && separateProcesses.length() > 0) {
2038            if ("*".equals(separateProcesses)) {
2039                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2040                mSeparateProcesses = null;
2041                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2042            } else {
2043                mDefParseFlags = 0;
2044                mSeparateProcesses = separateProcesses.split(",");
2045                Slog.w(TAG, "Running with debug.separate_processes: "
2046                        + separateProcesses);
2047            }
2048        } else {
2049            mDefParseFlags = 0;
2050            mSeparateProcesses = null;
2051        }
2052
2053        mInstaller = installer;
2054        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2055                "*dexopt*");
2056        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2057
2058        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2059                FgThread.get().getLooper());
2060
2061        getDefaultDisplayMetrics(context, mMetrics);
2062
2063        SystemConfig systemConfig = SystemConfig.getInstance();
2064        mGlobalGids = systemConfig.getGlobalGids();
2065        mSystemPermissions = systemConfig.getSystemPermissions();
2066        mAvailableFeatures = systemConfig.getAvailableFeatures();
2067
2068        synchronized (mInstallLock) {
2069        // writer
2070        synchronized (mPackages) {
2071            mHandlerThread = new ServiceThread(TAG,
2072                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2073            mHandlerThread.start();
2074            mHandler = new PackageHandler(mHandlerThread.getLooper());
2075            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2076
2077            File dataDir = Environment.getDataDirectory();
2078            mAppInstallDir = new File(dataDir, "app");
2079            mAppLib32InstallDir = new File(dataDir, "app-lib");
2080            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2081            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2082            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2083
2084            sUserManager = new UserManagerService(context, this, mPackages);
2085
2086            // Propagate permission configuration in to package manager.
2087            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2088                    = systemConfig.getPermissions();
2089            for (int i=0; i<permConfig.size(); i++) {
2090                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2091                BasePermission bp = mSettings.mPermissions.get(perm.name);
2092                if (bp == null) {
2093                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2094                    mSettings.mPermissions.put(perm.name, bp);
2095                }
2096                if (perm.gids != null) {
2097                    bp.setGids(perm.gids, perm.perUser);
2098                }
2099            }
2100
2101            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2102            for (int i=0; i<libConfig.size(); i++) {
2103                mSharedLibraries.put(libConfig.keyAt(i),
2104                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2105            }
2106
2107            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2108
2109            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2110
2111            String customResolverActivity = Resources.getSystem().getString(
2112                    R.string.config_customResolverActivity);
2113            if (TextUtils.isEmpty(customResolverActivity)) {
2114                customResolverActivity = null;
2115            } else {
2116                mCustomResolverComponentName = ComponentName.unflattenFromString(
2117                        customResolverActivity);
2118            }
2119
2120            long startTime = SystemClock.uptimeMillis();
2121
2122            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2123                    startTime);
2124
2125            // Set flag to monitor and not change apk file paths when
2126            // scanning install directories.
2127            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2128
2129            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2130            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2131
2132            if (bootClassPath == null) {
2133                Slog.w(TAG, "No BOOTCLASSPATH found!");
2134            }
2135
2136            if (systemServerClassPath == null) {
2137                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2138            }
2139
2140            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2141            final String[] dexCodeInstructionSets =
2142                    getDexCodeInstructionSets(
2143                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2144
2145            /**
2146             * Ensure all external libraries have had dexopt run on them.
2147             */
2148            if (mSharedLibraries.size() > 0) {
2149                // NOTE: For now, we're compiling these system "shared libraries"
2150                // (and framework jars) into all available architectures. It's possible
2151                // to compile them only when we come across an app that uses them (there's
2152                // already logic for that in scanPackageLI) but that adds some complexity.
2153                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2154                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2155                        final String lib = libEntry.path;
2156                        if (lib == null) {
2157                            continue;
2158                        }
2159
2160                        try {
2161                            // Shared libraries do not have profiles so we perform a full
2162                            // AOT compilation (if needed).
2163                            int dexoptNeeded = DexFile.getDexOptNeeded(
2164                                    lib, dexCodeInstructionSet,
2165                                    DexFile.COMPILATION_TYPE_FULL);
2166                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2167                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2168                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2169                                        StorageManager.UUID_PRIVATE_INTERNAL,
2170                                        false /*useProfiles*/);
2171                            }
2172                        } catch (FileNotFoundException e) {
2173                            Slog.w(TAG, "Library not found: " + lib);
2174                        } catch (IOException | InstallerException e) {
2175                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2176                                    + e.getMessage());
2177                        }
2178                    }
2179                }
2180            }
2181
2182            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2183
2184            final VersionInfo ver = mSettings.getInternalVersion();
2185            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2186            // when upgrading from pre-M, promote system app permissions from install to runtime
2187            mPromoteSystemApps =
2188                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2189
2190            // save off the names of pre-existing system packages prior to scanning; we don't
2191            // want to automatically grant runtime permissions for new system apps
2192            if (mPromoteSystemApps) {
2193                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2194                while (pkgSettingIter.hasNext()) {
2195                    PackageSetting ps = pkgSettingIter.next();
2196                    if (isSystemApp(ps)) {
2197                        mExistingSystemPackages.add(ps.name);
2198                    }
2199                }
2200            }
2201
2202            // Collect vendor overlay packages.
2203            // (Do this before scanning any apps.)
2204            // For security and version matching reason, only consider
2205            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2206            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2207            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2208                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2209
2210            // Find base frameworks (resource packages without code).
2211            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2212                    | PackageParser.PARSE_IS_SYSTEM_DIR
2213                    | PackageParser.PARSE_IS_PRIVILEGED,
2214                    scanFlags | SCAN_NO_DEX, 0);
2215
2216            // Collected privileged system packages.
2217            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2218            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2219                    | PackageParser.PARSE_IS_SYSTEM_DIR
2220                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2221
2222            // Collect ordinary system packages.
2223            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2224            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2225                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2226
2227            // Collect all vendor packages.
2228            File vendorAppDir = new File("/vendor/app");
2229            try {
2230                vendorAppDir = vendorAppDir.getCanonicalFile();
2231            } catch (IOException e) {
2232                // failed to look up canonical path, continue with original one
2233            }
2234            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2235                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2236
2237            // Collect all OEM packages.
2238            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2239            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2240                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2241
2242            // Prune any system packages that no longer exist.
2243            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2244            if (!mOnlyCore) {
2245                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2246                while (psit.hasNext()) {
2247                    PackageSetting ps = psit.next();
2248
2249                    /*
2250                     * If this is not a system app, it can't be a
2251                     * disable system app.
2252                     */
2253                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2254                        continue;
2255                    }
2256
2257                    /*
2258                     * If the package is scanned, it's not erased.
2259                     */
2260                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2261                    if (scannedPkg != null) {
2262                        /*
2263                         * If the system app is both scanned and in the
2264                         * disabled packages list, then it must have been
2265                         * added via OTA. Remove it from the currently
2266                         * scanned package so the previously user-installed
2267                         * application can be scanned.
2268                         */
2269                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2270                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2271                                    + ps.name + "; removing system app.  Last known codePath="
2272                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2273                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2274                                    + scannedPkg.mVersionCode);
2275                            removePackageLI(scannedPkg, true);
2276                            mExpectingBetter.put(ps.name, ps.codePath);
2277                        }
2278
2279                        continue;
2280                    }
2281
2282                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2283                        psit.remove();
2284                        logCriticalInfo(Log.WARN, "System package " + ps.name
2285                                + " no longer exists; wiping its data");
2286                        removeDataDirsLI(null, ps.name);
2287                    } else {
2288                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2289                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2290                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2291                        }
2292                    }
2293                }
2294            }
2295
2296            //look for any incomplete package installations
2297            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2298            //clean up list
2299            for(int i = 0; i < deletePkgsList.size(); i++) {
2300                //clean up here
2301                cleanupInstallFailedPackage(deletePkgsList.get(i));
2302            }
2303            //delete tmp files
2304            deleteTempPackageFiles();
2305
2306            // Remove any shared userIDs that have no associated packages
2307            mSettings.pruneSharedUsersLPw();
2308
2309            if (!mOnlyCore) {
2310                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2311                        SystemClock.uptimeMillis());
2312                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2313
2314                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2315                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2316
2317                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2318                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2319
2320                /**
2321                 * Remove disable package settings for any updated system
2322                 * apps that were removed via an OTA. If they're not a
2323                 * previously-updated app, remove them completely.
2324                 * Otherwise, just revoke their system-level permissions.
2325                 */
2326                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2327                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2328                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2329
2330                    String msg;
2331                    if (deletedPkg == null) {
2332                        msg = "Updated system package " + deletedAppName
2333                                + " no longer exists; wiping its data";
2334                        removeDataDirsLI(null, deletedAppName);
2335                    } else {
2336                        msg = "Updated system app + " + deletedAppName
2337                                + " no longer present; removing system privileges for "
2338                                + deletedAppName;
2339
2340                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2341
2342                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2343                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2344                    }
2345                    logCriticalInfo(Log.WARN, msg);
2346                }
2347
2348                /**
2349                 * Make sure all system apps that we expected to appear on
2350                 * the userdata partition actually showed up. If they never
2351                 * appeared, crawl back and revive the system version.
2352                 */
2353                for (int i = 0; i < mExpectingBetter.size(); i++) {
2354                    final String packageName = mExpectingBetter.keyAt(i);
2355                    if (!mPackages.containsKey(packageName)) {
2356                        final File scanFile = mExpectingBetter.valueAt(i);
2357
2358                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2359                                + " but never showed up; reverting to system");
2360
2361                        final int reparseFlags;
2362                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2363                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2364                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2365                                    | PackageParser.PARSE_IS_PRIVILEGED;
2366                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2367                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2368                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2369                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2370                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2371                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2372                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2373                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2374                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2375                        } else {
2376                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2377                            continue;
2378                        }
2379
2380                        mSettings.enableSystemPackageLPw(packageName);
2381
2382                        try {
2383                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2384                        } catch (PackageManagerException e) {
2385                            Slog.e(TAG, "Failed to parse original system package: "
2386                                    + e.getMessage());
2387                        }
2388                    }
2389                }
2390            }
2391            mExpectingBetter.clear();
2392
2393            // Now that we know all of the shared libraries, update all clients to have
2394            // the correct library paths.
2395            updateAllSharedLibrariesLPw();
2396
2397            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2398                // NOTE: We ignore potential failures here during a system scan (like
2399                // the rest of the commands above) because there's precious little we
2400                // can do about it. A settings error is reported, though.
2401                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2402                        false /* boot complete */);
2403            }
2404
2405            // Now that we know all the packages we are keeping,
2406            // read and update their last usage times.
2407            mPackageUsage.readLP();
2408
2409            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2410                    SystemClock.uptimeMillis());
2411            Slog.i(TAG, "Time to scan packages: "
2412                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2413                    + " seconds");
2414
2415            // If the platform SDK has changed since the last time we booted,
2416            // we need to re-grant app permission to catch any new ones that
2417            // appear.  This is really a hack, and means that apps can in some
2418            // cases get permissions that the user didn't initially explicitly
2419            // allow...  it would be nice to have some better way to handle
2420            // this situation.
2421            int updateFlags = UPDATE_PERMISSIONS_ALL;
2422            if (ver.sdkVersion != mSdkVersion) {
2423                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2424                        + mSdkVersion + "; regranting permissions for internal storage");
2425                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2426            }
2427            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2428            ver.sdkVersion = mSdkVersion;
2429
2430            // If this is the first boot or an update from pre-M, and it is a normal
2431            // boot, then we need to initialize the default preferred apps across
2432            // all defined users.
2433            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2434                for (UserInfo user : sUserManager.getUsers(true)) {
2435                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2436                    applyFactoryDefaultBrowserLPw(user.id);
2437                    primeDomainVerificationsLPw(user.id);
2438                }
2439            }
2440
2441            // Prepare storage for system user really early during boot,
2442            // since core system apps like SettingsProvider and SystemUI
2443            // can't wait for user to start
2444            final int storageFlags;
2445            if (StorageManager.isFileBasedEncryptionEnabled()) {
2446                storageFlags = StorageManager.FLAG_STORAGE_DE;
2447            } else {
2448                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2449            }
2450            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2451                    storageFlags);
2452
2453            // If this is first boot after an OTA, and a normal boot, then
2454            // we need to clear code cache directories.
2455            if (mIsUpgrade && !onlyCore) {
2456                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2457                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2458                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2459                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2460                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2461                    }
2462                }
2463                ver.fingerprint = Build.FINGERPRINT;
2464            }
2465
2466            checkDefaultBrowser();
2467
2468            // clear only after permissions and other defaults have been updated
2469            mExistingSystemPackages.clear();
2470            mPromoteSystemApps = false;
2471
2472            // All the changes are done during package scanning.
2473            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2474
2475            // can downgrade to reader
2476            mSettings.writeLPr();
2477
2478            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2479                    SystemClock.uptimeMillis());
2480
2481            if (!mOnlyCore) {
2482                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2483                mRequiredInstallerPackage = getRequiredInstallerLPr();
2484                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2485                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2486                        mIntentFilterVerifierComponent);
2487            } else {
2488                mRequiredVerifierPackage = null;
2489                mRequiredInstallerPackage = null;
2490                mIntentFilterVerifierComponent = null;
2491                mIntentFilterVerifier = null;
2492            }
2493
2494            mInstallerService = new PackageInstallerService(context, this);
2495
2496            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2497            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2498            // both the installer and resolver must be present to enable ephemeral
2499            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2500                if (DEBUG_EPHEMERAL) {
2501                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2502                            + " installer:" + ephemeralInstallerComponent);
2503                }
2504                mEphemeralResolverComponent = ephemeralResolverComponent;
2505                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2506                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2507                mEphemeralResolverConnection =
2508                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2509            } else {
2510                if (DEBUG_EPHEMERAL) {
2511                    final String missingComponent =
2512                            (ephemeralResolverComponent == null)
2513                            ? (ephemeralInstallerComponent == null)
2514                                    ? "resolver and installer"
2515                                    : "resolver"
2516                            : "installer";
2517                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2518                }
2519                mEphemeralResolverComponent = null;
2520                mEphemeralInstallerComponent = null;
2521                mEphemeralResolverConnection = null;
2522            }
2523
2524            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2525        } // synchronized (mPackages)
2526        } // synchronized (mInstallLock)
2527
2528        // Now after opening every single application zip, make sure they
2529        // are all flushed.  Not really needed, but keeps things nice and
2530        // tidy.
2531        Runtime.getRuntime().gc();
2532
2533        // The initial scanning above does many calls into installd while
2534        // holding the mPackages lock, but we're mostly interested in yelling
2535        // once we have a booted system.
2536        mInstaller.setWarnIfHeld(mPackages);
2537
2538        // Expose private service for system components to use.
2539        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2540    }
2541
2542    @Override
2543    public boolean isFirstBoot() {
2544        return !mRestoredSettings;
2545    }
2546
2547    @Override
2548    public boolean isOnlyCoreApps() {
2549        return mOnlyCore;
2550    }
2551
2552    @Override
2553    public boolean isUpgrade() {
2554        return mIsUpgrade;
2555    }
2556
2557    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2558        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2559
2560        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2561                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2562        if (matches.size() == 1) {
2563            return matches.get(0).getComponentInfo().packageName;
2564        } else {
2565            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2566            return null;
2567        }
2568    }
2569
2570    private @NonNull String getRequiredInstallerLPr() {
2571        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2572        intent.addCategory(Intent.CATEGORY_DEFAULT);
2573        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2574
2575        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2576                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2577        if (matches.size() == 1) {
2578            return matches.get(0).getComponentInfo().packageName;
2579        } else {
2580            throw new RuntimeException("There must be exactly one installer; found " + matches);
2581        }
2582    }
2583
2584    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2585        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2586
2587        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2588                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2589        ResolveInfo best = null;
2590        final int N = matches.size();
2591        for (int i = 0; i < N; i++) {
2592            final ResolveInfo cur = matches.get(i);
2593            final String packageName = cur.getComponentInfo().packageName;
2594            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2595                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2596                continue;
2597            }
2598
2599            if (best == null || cur.priority > best.priority) {
2600                best = cur;
2601            }
2602        }
2603
2604        if (best != null) {
2605            return best.getComponentInfo().getComponentName();
2606        } else {
2607            throw new RuntimeException("There must be at least one intent filter verifier");
2608        }
2609    }
2610
2611    private @Nullable ComponentName getEphemeralResolverLPr() {
2612        final String[] packageArray =
2613                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2614        if (packageArray.length == 0) {
2615            if (DEBUG_EPHEMERAL) {
2616                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2617            }
2618            return null;
2619        }
2620
2621        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2622        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2623                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2624
2625        final int N = resolvers.size();
2626        if (N == 0) {
2627            if (DEBUG_EPHEMERAL) {
2628                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2629            }
2630            return null;
2631        }
2632
2633        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2634        for (int i = 0; i < N; i++) {
2635            final ResolveInfo info = resolvers.get(i);
2636
2637            if (info.serviceInfo == null) {
2638                continue;
2639            }
2640
2641            final String packageName = info.serviceInfo.packageName;
2642            if (!possiblePackages.contains(packageName)) {
2643                if (DEBUG_EPHEMERAL) {
2644                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2645                            + " pkg: " + packageName + ", info:" + info);
2646                }
2647                continue;
2648            }
2649
2650            if (DEBUG_EPHEMERAL) {
2651                Slog.v(TAG, "Ephemeral resolver found;"
2652                        + " pkg: " + packageName + ", info:" + info);
2653            }
2654            return new ComponentName(packageName, info.serviceInfo.name);
2655        }
2656        if (DEBUG_EPHEMERAL) {
2657            Slog.v(TAG, "Ephemeral resolver NOT found");
2658        }
2659        return null;
2660    }
2661
2662    private @Nullable ComponentName getEphemeralInstallerLPr() {
2663        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2664        intent.addCategory(Intent.CATEGORY_DEFAULT);
2665        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2666
2667        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2668                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2669        if (matches.size() == 0) {
2670            return null;
2671        } else if (matches.size() == 1) {
2672            return matches.get(0).getComponentInfo().getComponentName();
2673        } else {
2674            throw new RuntimeException(
2675                    "There must be at most one ephemeral installer; found " + matches);
2676        }
2677    }
2678
2679    private void primeDomainVerificationsLPw(int userId) {
2680        if (DEBUG_DOMAIN_VERIFICATION) {
2681            Slog.d(TAG, "Priming domain verifications in user " + userId);
2682        }
2683
2684        SystemConfig systemConfig = SystemConfig.getInstance();
2685        ArraySet<String> packages = systemConfig.getLinkedApps();
2686        ArraySet<String> domains = new ArraySet<String>();
2687
2688        for (String packageName : packages) {
2689            PackageParser.Package pkg = mPackages.get(packageName);
2690            if (pkg != null) {
2691                if (!pkg.isSystemApp()) {
2692                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2693                    continue;
2694                }
2695
2696                domains.clear();
2697                for (PackageParser.Activity a : pkg.activities) {
2698                    for (ActivityIntentInfo filter : a.intents) {
2699                        if (hasValidDomains(filter)) {
2700                            domains.addAll(filter.getHostsList());
2701                        }
2702                    }
2703                }
2704
2705                if (domains.size() > 0) {
2706                    if (DEBUG_DOMAIN_VERIFICATION) {
2707                        Slog.v(TAG, "      + " + packageName);
2708                    }
2709                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2710                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2711                    // and then 'always' in the per-user state actually used for intent resolution.
2712                    final IntentFilterVerificationInfo ivi;
2713                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2714                            new ArrayList<String>(domains));
2715                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2716                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2717                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2718                } else {
2719                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2720                            + "' does not handle web links");
2721                }
2722            } else {
2723                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2724            }
2725        }
2726
2727        scheduleWritePackageRestrictionsLocked(userId);
2728        scheduleWriteSettingsLocked();
2729    }
2730
2731    private void applyFactoryDefaultBrowserLPw(int userId) {
2732        // The default browser app's package name is stored in a string resource,
2733        // with a product-specific overlay used for vendor customization.
2734        String browserPkg = mContext.getResources().getString(
2735                com.android.internal.R.string.default_browser);
2736        if (!TextUtils.isEmpty(browserPkg)) {
2737            // non-empty string => required to be a known package
2738            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2739            if (ps == null) {
2740                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2741                browserPkg = null;
2742            } else {
2743                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2744            }
2745        }
2746
2747        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2748        // default.  If there's more than one, just leave everything alone.
2749        if (browserPkg == null) {
2750            calculateDefaultBrowserLPw(userId);
2751        }
2752    }
2753
2754    private void calculateDefaultBrowserLPw(int userId) {
2755        List<String> allBrowsers = resolveAllBrowserApps(userId);
2756        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2757        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2758    }
2759
2760    private List<String> resolveAllBrowserApps(int userId) {
2761        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2762        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2763                PackageManager.MATCH_ALL, userId);
2764
2765        final int count = list.size();
2766        List<String> result = new ArrayList<String>(count);
2767        for (int i=0; i<count; i++) {
2768            ResolveInfo info = list.get(i);
2769            if (info.activityInfo == null
2770                    || !info.handleAllWebDataURI
2771                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2772                    || result.contains(info.activityInfo.packageName)) {
2773                continue;
2774            }
2775            result.add(info.activityInfo.packageName);
2776        }
2777
2778        return result;
2779    }
2780
2781    private boolean packageIsBrowser(String packageName, int userId) {
2782        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2783                PackageManager.MATCH_ALL, userId);
2784        final int N = list.size();
2785        for (int i = 0; i < N; i++) {
2786            ResolveInfo info = list.get(i);
2787            if (packageName.equals(info.activityInfo.packageName)) {
2788                return true;
2789            }
2790        }
2791        return false;
2792    }
2793
2794    private void checkDefaultBrowser() {
2795        final int myUserId = UserHandle.myUserId();
2796        final String packageName = getDefaultBrowserPackageName(myUserId);
2797        if (packageName != null) {
2798            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2799            if (info == null) {
2800                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2801                synchronized (mPackages) {
2802                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2803                }
2804            }
2805        }
2806    }
2807
2808    @Override
2809    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2810            throws RemoteException {
2811        try {
2812            return super.onTransact(code, data, reply, flags);
2813        } catch (RuntimeException e) {
2814            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2815                Slog.wtf(TAG, "Package Manager Crash", e);
2816            }
2817            throw e;
2818        }
2819    }
2820
2821    void cleanupInstallFailedPackage(PackageSetting ps) {
2822        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2823
2824        removeDataDirsLI(ps.volumeUuid, ps.name);
2825        if (ps.codePath != null) {
2826            removeCodePathLI(ps.codePath);
2827        }
2828        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2829            if (ps.resourcePath.isDirectory()) {
2830                FileUtils.deleteContents(ps.resourcePath);
2831            }
2832            ps.resourcePath.delete();
2833        }
2834        mSettings.removePackageLPw(ps.name);
2835    }
2836
2837    static int[] appendInts(int[] cur, int[] add) {
2838        if (add == null) return cur;
2839        if (cur == null) return add;
2840        final int N = add.length;
2841        for (int i=0; i<N; i++) {
2842            cur = appendInt(cur, add[i]);
2843        }
2844        return cur;
2845    }
2846
2847    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2848        if (!sUserManager.exists(userId)) return null;
2849        final PackageSetting ps = (PackageSetting) p.mExtras;
2850        if (ps == null) {
2851            return null;
2852        }
2853
2854        final PermissionsState permissionsState = ps.getPermissionsState();
2855
2856        final int[] gids = permissionsState.computeGids(userId);
2857        final Set<String> permissions = permissionsState.getPermissions(userId);
2858        final PackageUserState state = ps.readUserState(userId);
2859
2860        return PackageParser.generatePackageInfo(p, gids, flags,
2861                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2862    }
2863
2864    @Override
2865    public void checkPackageStartable(String packageName, int userId) {
2866        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2867
2868        synchronized (mPackages) {
2869            final PackageSetting ps = mSettings.mPackages.get(packageName);
2870            if (ps == null) {
2871                throw new SecurityException("Package " + packageName + " was not found!");
2872            }
2873
2874            if (mSafeMode && !ps.isSystem()) {
2875                throw new SecurityException("Package " + packageName + " not a system app!");
2876            }
2877
2878            if (ps.frozen) {
2879                throw new SecurityException("Package " + packageName + " is currently frozen!");
2880            }
2881
2882            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2883                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2884                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2885            }
2886        }
2887    }
2888
2889    @Override
2890    public boolean isPackageAvailable(String packageName, int userId) {
2891        if (!sUserManager.exists(userId)) return false;
2892        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2893                false /* requireFullPermission */, false /* checkShell */, "is package available");
2894        synchronized (mPackages) {
2895            PackageParser.Package p = mPackages.get(packageName);
2896            if (p != null) {
2897                final PackageSetting ps = (PackageSetting) p.mExtras;
2898                if (ps != null) {
2899                    final PackageUserState state = ps.readUserState(userId);
2900                    if (state != null) {
2901                        return PackageParser.isAvailable(state);
2902                    }
2903                }
2904            }
2905        }
2906        return false;
2907    }
2908
2909    @Override
2910    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2911        if (!sUserManager.exists(userId)) return null;
2912        flags = updateFlagsForPackage(flags, userId, packageName);
2913        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2914                false /* requireFullPermission */, false /* checkShell */, "get package info");
2915        // reader
2916        synchronized (mPackages) {
2917            PackageParser.Package p = mPackages.get(packageName);
2918            if (DEBUG_PACKAGE_INFO)
2919                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2920            if (p != null) {
2921                return generatePackageInfo(p, flags, userId);
2922            }
2923            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2924                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2925            }
2926        }
2927        return null;
2928    }
2929
2930    @Override
2931    public String[] currentToCanonicalPackageNames(String[] names) {
2932        String[] out = new String[names.length];
2933        // reader
2934        synchronized (mPackages) {
2935            for (int i=names.length-1; i>=0; i--) {
2936                PackageSetting ps = mSettings.mPackages.get(names[i]);
2937                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2938            }
2939        }
2940        return out;
2941    }
2942
2943    @Override
2944    public String[] canonicalToCurrentPackageNames(String[] names) {
2945        String[] out = new String[names.length];
2946        // reader
2947        synchronized (mPackages) {
2948            for (int i=names.length-1; i>=0; i--) {
2949                String cur = mSettings.mRenamedPackages.get(names[i]);
2950                out[i] = cur != null ? cur : names[i];
2951            }
2952        }
2953        return out;
2954    }
2955
2956    @Override
2957    public int getPackageUid(String packageName, int flags, int userId) {
2958        if (!sUserManager.exists(userId)) return -1;
2959        flags = updateFlagsForPackage(flags, userId, packageName);
2960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2961                false /* requireFullPermission */, false /* checkShell */, "get package uid");
2962
2963        // reader
2964        synchronized (mPackages) {
2965            final PackageParser.Package p = mPackages.get(packageName);
2966            if (p != null && p.isMatch(flags)) {
2967                return UserHandle.getUid(userId, p.applicationInfo.uid);
2968            }
2969            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2970                final PackageSetting ps = mSettings.mPackages.get(packageName);
2971                if (ps != null && ps.isMatch(flags)) {
2972                    return UserHandle.getUid(userId, ps.appId);
2973                }
2974            }
2975        }
2976
2977        return -1;
2978    }
2979
2980    @Override
2981    public int[] getPackageGids(String packageName, int flags, int userId) {
2982        if (!sUserManager.exists(userId)) return null;
2983        flags = updateFlagsForPackage(flags, userId, packageName);
2984        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2985                false /* requireFullPermission */, false /* checkShell */,
2986                "getPackageGids");
2987
2988        // reader
2989        synchronized (mPackages) {
2990            final PackageParser.Package p = mPackages.get(packageName);
2991            if (p != null && p.isMatch(flags)) {
2992                PackageSetting ps = (PackageSetting) p.mExtras;
2993                return ps.getPermissionsState().computeGids(userId);
2994            }
2995            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2996                final PackageSetting ps = mSettings.mPackages.get(packageName);
2997                if (ps != null && ps.isMatch(flags)) {
2998                    return ps.getPermissionsState().computeGids(userId);
2999                }
3000            }
3001        }
3002
3003        return null;
3004    }
3005
3006    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3007        if (bp.perm != null) {
3008            return PackageParser.generatePermissionInfo(bp.perm, flags);
3009        }
3010        PermissionInfo pi = new PermissionInfo();
3011        pi.name = bp.name;
3012        pi.packageName = bp.sourcePackage;
3013        pi.nonLocalizedLabel = bp.name;
3014        pi.protectionLevel = bp.protectionLevel;
3015        return pi;
3016    }
3017
3018    @Override
3019    public PermissionInfo getPermissionInfo(String name, int flags) {
3020        // reader
3021        synchronized (mPackages) {
3022            final BasePermission p = mSettings.mPermissions.get(name);
3023            if (p != null) {
3024                return generatePermissionInfo(p, flags);
3025            }
3026            return null;
3027        }
3028    }
3029
3030    @Override
3031    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3032        // reader
3033        synchronized (mPackages) {
3034            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3035            for (BasePermission p : mSettings.mPermissions.values()) {
3036                if (group == null) {
3037                    if (p.perm == null || p.perm.info.group == null) {
3038                        out.add(generatePermissionInfo(p, flags));
3039                    }
3040                } else {
3041                    if (p.perm != null && group.equals(p.perm.info.group)) {
3042                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3043                    }
3044                }
3045            }
3046
3047            if (out.size() > 0) {
3048                return out;
3049            }
3050            return mPermissionGroups.containsKey(group) ? out : null;
3051        }
3052    }
3053
3054    @Override
3055    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3056        // reader
3057        synchronized (mPackages) {
3058            return PackageParser.generatePermissionGroupInfo(
3059                    mPermissionGroups.get(name), flags);
3060        }
3061    }
3062
3063    @Override
3064    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3065        // reader
3066        synchronized (mPackages) {
3067            final int N = mPermissionGroups.size();
3068            ArrayList<PermissionGroupInfo> out
3069                    = new ArrayList<PermissionGroupInfo>(N);
3070            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3071                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3072            }
3073            return out;
3074        }
3075    }
3076
3077    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3078            int userId) {
3079        if (!sUserManager.exists(userId)) return null;
3080        PackageSetting ps = mSettings.mPackages.get(packageName);
3081        if (ps != null) {
3082            if (ps.pkg == null) {
3083                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3084                        flags, userId);
3085                if (pInfo != null) {
3086                    return pInfo.applicationInfo;
3087                }
3088                return null;
3089            }
3090            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3091                    ps.readUserState(userId), userId);
3092        }
3093        return null;
3094    }
3095
3096    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3097            int userId) {
3098        if (!sUserManager.exists(userId)) return null;
3099        PackageSetting ps = mSettings.mPackages.get(packageName);
3100        if (ps != null) {
3101            PackageParser.Package pkg = ps.pkg;
3102            if (pkg == null) {
3103                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3104                    return null;
3105                }
3106                // Only data remains, so we aren't worried about code paths
3107                pkg = new PackageParser.Package(packageName);
3108                pkg.applicationInfo.packageName = packageName;
3109                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3110                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3111                pkg.applicationInfo.uid = ps.appId;
3112                pkg.applicationInfo.initForUser(userId);
3113                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3114                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3115            }
3116            return generatePackageInfo(pkg, flags, userId);
3117        }
3118        return null;
3119    }
3120
3121    @Override
3122    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3123        if (!sUserManager.exists(userId)) return null;
3124        flags = updateFlagsForApplication(flags, userId, packageName);
3125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3126                false /* requireFullPermission */, false /* checkShell */, "get application info");
3127        // writer
3128        synchronized (mPackages) {
3129            PackageParser.Package p = mPackages.get(packageName);
3130            if (DEBUG_PACKAGE_INFO) Log.v(
3131                    TAG, "getApplicationInfo " + packageName
3132                    + ": " + p);
3133            if (p != null) {
3134                PackageSetting ps = mSettings.mPackages.get(packageName);
3135                if (ps == null) return null;
3136                // Note: isEnabledLP() does not apply here - always return info
3137                return PackageParser.generateApplicationInfo(
3138                        p, flags, ps.readUserState(userId), userId);
3139            }
3140            if ("android".equals(packageName)||"system".equals(packageName)) {
3141                return mAndroidApplication;
3142            }
3143            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3144                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3145            }
3146        }
3147        return null;
3148    }
3149
3150    @Override
3151    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3152            final IPackageDataObserver observer) {
3153        mContext.enforceCallingOrSelfPermission(
3154                android.Manifest.permission.CLEAR_APP_CACHE, null);
3155        // Queue up an async operation since clearing cache may take a little while.
3156        mHandler.post(new Runnable() {
3157            public void run() {
3158                mHandler.removeCallbacks(this);
3159                boolean success = true;
3160                synchronized (mInstallLock) {
3161                    try {
3162                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3163                    } catch (InstallerException e) {
3164                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3165                        success = false;
3166                    }
3167                }
3168                if (observer != null) {
3169                    try {
3170                        observer.onRemoveCompleted(null, success);
3171                    } catch (RemoteException e) {
3172                        Slog.w(TAG, "RemoveException when invoking call back");
3173                    }
3174                }
3175            }
3176        });
3177    }
3178
3179    @Override
3180    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3181            final IntentSender pi) {
3182        mContext.enforceCallingOrSelfPermission(
3183                android.Manifest.permission.CLEAR_APP_CACHE, null);
3184        // Queue up an async operation since clearing cache may take a little while.
3185        mHandler.post(new Runnable() {
3186            public void run() {
3187                mHandler.removeCallbacks(this);
3188                boolean success = true;
3189                synchronized (mInstallLock) {
3190                    try {
3191                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3192                    } catch (InstallerException e) {
3193                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3194                        success = false;
3195                    }
3196                }
3197                if(pi != null) {
3198                    try {
3199                        // Callback via pending intent
3200                        int code = success ? 1 : 0;
3201                        pi.sendIntent(null, code, null,
3202                                null, null);
3203                    } catch (SendIntentException e1) {
3204                        Slog.i(TAG, "Failed to send pending intent");
3205                    }
3206                }
3207            }
3208        });
3209    }
3210
3211    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3212        synchronized (mInstallLock) {
3213            try {
3214                mInstaller.freeCache(volumeUuid, freeStorageSize);
3215            } catch (InstallerException e) {
3216                throw new IOException("Failed to free enough space", e);
3217            }
3218        }
3219    }
3220
3221    /**
3222     * Return if the user key is currently unlocked.
3223     */
3224    private boolean isUserKeyUnlocked(int userId) {
3225        if (StorageManager.isFileBasedEncryptionEnabled()) {
3226            final IMountService mount = IMountService.Stub
3227                    .asInterface(ServiceManager.getService("mount"));
3228            if (mount == null) {
3229                Slog.w(TAG, "Early during boot, assuming locked");
3230                return false;
3231            }
3232            final long token = Binder.clearCallingIdentity();
3233            try {
3234                return mount.isUserKeyUnlocked(userId);
3235            } catch (RemoteException e) {
3236                throw e.rethrowAsRuntimeException();
3237            } finally {
3238                Binder.restoreCallingIdentity(token);
3239            }
3240        } else {
3241            return true;
3242        }
3243    }
3244
3245    /**
3246     * Update given flags based on encryption status of current user.
3247     */
3248    private int updateFlags(int flags, int userId) {
3249        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3250                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3251            // Caller expressed an explicit opinion about what encryption
3252            // aware/unaware components they want to see, so fall through and
3253            // give them what they want
3254        } else {
3255            // Caller expressed no opinion, so match based on user state
3256            if (isUserKeyUnlocked(userId)) {
3257                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3258            } else {
3259                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3260            }
3261        }
3262        return flags;
3263    }
3264
3265    /**
3266     * Update given flags when being used to request {@link PackageInfo}.
3267     */
3268    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3269        boolean triaged = true;
3270        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3271                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3272            // Caller is asking for component details, so they'd better be
3273            // asking for specific encryption matching behavior, or be triaged
3274            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3275                    | PackageManager.MATCH_ENCRYPTION_AWARE
3276                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3277                triaged = false;
3278            }
3279        }
3280        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3281                | PackageManager.MATCH_SYSTEM_ONLY
3282                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3283            triaged = false;
3284        }
3285        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3286            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3287                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3288        }
3289        return updateFlags(flags, userId);
3290    }
3291
3292    /**
3293     * Update given flags when being used to request {@link ApplicationInfo}.
3294     */
3295    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3296        return updateFlagsForPackage(flags, userId, cookie);
3297    }
3298
3299    /**
3300     * Update given flags when being used to request {@link ComponentInfo}.
3301     */
3302    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3303        if (cookie instanceof Intent) {
3304            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3305                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3306            }
3307        }
3308
3309        boolean triaged = true;
3310        // Caller is asking for component details, so they'd better be
3311        // asking for specific encryption matching behavior, or be triaged
3312        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3313                | PackageManager.MATCH_ENCRYPTION_AWARE
3314                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3315            triaged = false;
3316        }
3317        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3318            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3319                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3320        }
3321
3322        return updateFlags(flags, userId);
3323    }
3324
3325    /**
3326     * Update given flags when being used to request {@link ResolveInfo}.
3327     */
3328    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3329        // Safe mode means we shouldn't match any third-party components
3330        if (mSafeMode) {
3331            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3332        }
3333
3334        return updateFlagsForComponent(flags, userId, cookie);
3335    }
3336
3337    @Override
3338    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3339        if (!sUserManager.exists(userId)) return null;
3340        flags = updateFlagsForComponent(flags, userId, component);
3341        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3342                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3343        synchronized (mPackages) {
3344            PackageParser.Activity a = mActivities.mActivities.get(component);
3345
3346            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3347            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3348                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3349                if (ps == null) return null;
3350                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3351                        userId);
3352            }
3353            if (mResolveComponentName.equals(component)) {
3354                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3355                        new PackageUserState(), userId);
3356            }
3357        }
3358        return null;
3359    }
3360
3361    @Override
3362    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3363            String resolvedType) {
3364        synchronized (mPackages) {
3365            if (component.equals(mResolveComponentName)) {
3366                // The resolver supports EVERYTHING!
3367                return true;
3368            }
3369            PackageParser.Activity a = mActivities.mActivities.get(component);
3370            if (a == null) {
3371                return false;
3372            }
3373            for (int i=0; i<a.intents.size(); i++) {
3374                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3375                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3376                    return true;
3377                }
3378            }
3379            return false;
3380        }
3381    }
3382
3383    @Override
3384    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3385        if (!sUserManager.exists(userId)) return null;
3386        flags = updateFlagsForComponent(flags, userId, component);
3387        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3388                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3389        synchronized (mPackages) {
3390            PackageParser.Activity a = mReceivers.mActivities.get(component);
3391            if (DEBUG_PACKAGE_INFO) Log.v(
3392                TAG, "getReceiverInfo " + component + ": " + a);
3393            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3394                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3395                if (ps == null) return null;
3396                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3397                        userId);
3398            }
3399        }
3400        return null;
3401    }
3402
3403    @Override
3404    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3405        if (!sUserManager.exists(userId)) return null;
3406        flags = updateFlagsForComponent(flags, userId, component);
3407        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3408                false /* requireFullPermission */, false /* checkShell */, "get service info");
3409        synchronized (mPackages) {
3410            PackageParser.Service s = mServices.mServices.get(component);
3411            if (DEBUG_PACKAGE_INFO) Log.v(
3412                TAG, "getServiceInfo " + component + ": " + s);
3413            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3414                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3415                if (ps == null) return null;
3416                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3417                        userId);
3418            }
3419        }
3420        return null;
3421    }
3422
3423    @Override
3424    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3425        if (!sUserManager.exists(userId)) return null;
3426        flags = updateFlagsForComponent(flags, userId, component);
3427        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3428                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3429        synchronized (mPackages) {
3430            PackageParser.Provider p = mProviders.mProviders.get(component);
3431            if (DEBUG_PACKAGE_INFO) Log.v(
3432                TAG, "getProviderInfo " + component + ": " + p);
3433            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3434                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3435                if (ps == null) return null;
3436                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3437                        userId);
3438            }
3439        }
3440        return null;
3441    }
3442
3443    @Override
3444    public String[] getSystemSharedLibraryNames() {
3445        Set<String> libSet;
3446        synchronized (mPackages) {
3447            libSet = mSharedLibraries.keySet();
3448            int size = libSet.size();
3449            if (size > 0) {
3450                String[] libs = new String[size];
3451                libSet.toArray(libs);
3452                return libs;
3453            }
3454        }
3455        return null;
3456    }
3457
3458    @Override
3459    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3460        synchronized (mPackages) {
3461            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3462                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3463            if (libraryEntry != null) {
3464                return libraryEntry.apk;
3465            }
3466        }
3467        return null;
3468    }
3469
3470    @Override
3471    public FeatureInfo[] getSystemAvailableFeatures() {
3472        Collection<FeatureInfo> featSet;
3473        synchronized (mPackages) {
3474            featSet = mAvailableFeatures.values();
3475            int size = featSet.size();
3476            if (size > 0) {
3477                FeatureInfo[] features = new FeatureInfo[size+1];
3478                featSet.toArray(features);
3479                FeatureInfo fi = new FeatureInfo();
3480                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3481                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3482                features[size] = fi;
3483                return features;
3484            }
3485        }
3486        return null;
3487    }
3488
3489    @Override
3490    public boolean hasSystemFeature(String name, int version) {
3491        synchronized (mPackages) {
3492            final FeatureInfo feat = mAvailableFeatures.get(name);
3493            if (feat == null) {
3494                return false;
3495            } else {
3496                return feat.version >= version;
3497            }
3498        }
3499    }
3500
3501    @Override
3502    public int checkPermission(String permName, String pkgName, int userId) {
3503        if (!sUserManager.exists(userId)) {
3504            return PackageManager.PERMISSION_DENIED;
3505        }
3506
3507        synchronized (mPackages) {
3508            final PackageParser.Package p = mPackages.get(pkgName);
3509            if (p != null && p.mExtras != null) {
3510                final PackageSetting ps = (PackageSetting) p.mExtras;
3511                final PermissionsState permissionsState = ps.getPermissionsState();
3512                if (permissionsState.hasPermission(permName, userId)) {
3513                    return PackageManager.PERMISSION_GRANTED;
3514                }
3515                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3516                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3517                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3518                    return PackageManager.PERMISSION_GRANTED;
3519                }
3520            }
3521        }
3522
3523        return PackageManager.PERMISSION_DENIED;
3524    }
3525
3526    @Override
3527    public int checkUidPermission(String permName, int uid) {
3528        final int userId = UserHandle.getUserId(uid);
3529
3530        if (!sUserManager.exists(userId)) {
3531            return PackageManager.PERMISSION_DENIED;
3532        }
3533
3534        synchronized (mPackages) {
3535            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3536            if (obj != null) {
3537                final SettingBase ps = (SettingBase) obj;
3538                final PermissionsState permissionsState = ps.getPermissionsState();
3539                if (permissionsState.hasPermission(permName, userId)) {
3540                    return PackageManager.PERMISSION_GRANTED;
3541                }
3542                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3543                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3544                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3545                    return PackageManager.PERMISSION_GRANTED;
3546                }
3547            } else {
3548                ArraySet<String> perms = mSystemPermissions.get(uid);
3549                if (perms != null) {
3550                    if (perms.contains(permName)) {
3551                        return PackageManager.PERMISSION_GRANTED;
3552                    }
3553                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3554                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3555                        return PackageManager.PERMISSION_GRANTED;
3556                    }
3557                }
3558            }
3559        }
3560
3561        return PackageManager.PERMISSION_DENIED;
3562    }
3563
3564    @Override
3565    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3566        if (UserHandle.getCallingUserId() != userId) {
3567            mContext.enforceCallingPermission(
3568                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3569                    "isPermissionRevokedByPolicy for user " + userId);
3570        }
3571
3572        if (checkPermission(permission, packageName, userId)
3573                == PackageManager.PERMISSION_GRANTED) {
3574            return false;
3575        }
3576
3577        final long identity = Binder.clearCallingIdentity();
3578        try {
3579            final int flags = getPermissionFlags(permission, packageName, userId);
3580            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3581        } finally {
3582            Binder.restoreCallingIdentity(identity);
3583        }
3584    }
3585
3586    @Override
3587    public String getPermissionControllerPackageName() {
3588        synchronized (mPackages) {
3589            return mRequiredInstallerPackage;
3590        }
3591    }
3592
3593    /**
3594     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3595     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3596     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3597     * @param message the message to log on security exception
3598     */
3599    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3600            boolean checkShell, String message) {
3601        if (userId < 0) {
3602            throw new IllegalArgumentException("Invalid userId " + userId);
3603        }
3604        if (checkShell) {
3605            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3606        }
3607        if (userId == UserHandle.getUserId(callingUid)) return;
3608        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3609            if (requireFullPermission) {
3610                mContext.enforceCallingOrSelfPermission(
3611                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3612            } else {
3613                try {
3614                    mContext.enforceCallingOrSelfPermission(
3615                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3616                } catch (SecurityException se) {
3617                    mContext.enforceCallingOrSelfPermission(
3618                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3619                }
3620            }
3621        }
3622    }
3623
3624    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3625        if (callingUid == Process.SHELL_UID) {
3626            if (userHandle >= 0
3627                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3628                throw new SecurityException("Shell does not have permission to access user "
3629                        + userHandle);
3630            } else if (userHandle < 0) {
3631                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3632                        + Debug.getCallers(3));
3633            }
3634        }
3635    }
3636
3637    private BasePermission findPermissionTreeLP(String permName) {
3638        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3639            if (permName.startsWith(bp.name) &&
3640                    permName.length() > bp.name.length() &&
3641                    permName.charAt(bp.name.length()) == '.') {
3642                return bp;
3643            }
3644        }
3645        return null;
3646    }
3647
3648    private BasePermission checkPermissionTreeLP(String permName) {
3649        if (permName != null) {
3650            BasePermission bp = findPermissionTreeLP(permName);
3651            if (bp != null) {
3652                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3653                    return bp;
3654                }
3655                throw new SecurityException("Calling uid "
3656                        + Binder.getCallingUid()
3657                        + " is not allowed to add to permission tree "
3658                        + bp.name + " owned by uid " + bp.uid);
3659            }
3660        }
3661        throw new SecurityException("No permission tree found for " + permName);
3662    }
3663
3664    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3665        if (s1 == null) {
3666            return s2 == null;
3667        }
3668        if (s2 == null) {
3669            return false;
3670        }
3671        if (s1.getClass() != s2.getClass()) {
3672            return false;
3673        }
3674        return s1.equals(s2);
3675    }
3676
3677    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3678        if (pi1.icon != pi2.icon) return false;
3679        if (pi1.logo != pi2.logo) return false;
3680        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3681        if (!compareStrings(pi1.name, pi2.name)) return false;
3682        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3683        // We'll take care of setting this one.
3684        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3685        // These are not currently stored in settings.
3686        //if (!compareStrings(pi1.group, pi2.group)) return false;
3687        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3688        //if (pi1.labelRes != pi2.labelRes) return false;
3689        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3690        return true;
3691    }
3692
3693    int permissionInfoFootprint(PermissionInfo info) {
3694        int size = info.name.length();
3695        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3696        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3697        return size;
3698    }
3699
3700    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3701        int size = 0;
3702        for (BasePermission perm : mSettings.mPermissions.values()) {
3703            if (perm.uid == tree.uid) {
3704                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3705            }
3706        }
3707        return size;
3708    }
3709
3710    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3711        // We calculate the max size of permissions defined by this uid and throw
3712        // if that plus the size of 'info' would exceed our stated maximum.
3713        if (tree.uid != Process.SYSTEM_UID) {
3714            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3715            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3716                throw new SecurityException("Permission tree size cap exceeded");
3717            }
3718        }
3719    }
3720
3721    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3722        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3723            throw new SecurityException("Label must be specified in permission");
3724        }
3725        BasePermission tree = checkPermissionTreeLP(info.name);
3726        BasePermission bp = mSettings.mPermissions.get(info.name);
3727        boolean added = bp == null;
3728        boolean changed = true;
3729        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3730        if (added) {
3731            enforcePermissionCapLocked(info, tree);
3732            bp = new BasePermission(info.name, tree.sourcePackage,
3733                    BasePermission.TYPE_DYNAMIC);
3734        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3735            throw new SecurityException(
3736                    "Not allowed to modify non-dynamic permission "
3737                    + info.name);
3738        } else {
3739            if (bp.protectionLevel == fixedLevel
3740                    && bp.perm.owner.equals(tree.perm.owner)
3741                    && bp.uid == tree.uid
3742                    && comparePermissionInfos(bp.perm.info, info)) {
3743                changed = false;
3744            }
3745        }
3746        bp.protectionLevel = fixedLevel;
3747        info = new PermissionInfo(info);
3748        info.protectionLevel = fixedLevel;
3749        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3750        bp.perm.info.packageName = tree.perm.info.packageName;
3751        bp.uid = tree.uid;
3752        if (added) {
3753            mSettings.mPermissions.put(info.name, bp);
3754        }
3755        if (changed) {
3756            if (!async) {
3757                mSettings.writeLPr();
3758            } else {
3759                scheduleWriteSettingsLocked();
3760            }
3761        }
3762        return added;
3763    }
3764
3765    @Override
3766    public boolean addPermission(PermissionInfo info) {
3767        synchronized (mPackages) {
3768            return addPermissionLocked(info, false);
3769        }
3770    }
3771
3772    @Override
3773    public boolean addPermissionAsync(PermissionInfo info) {
3774        synchronized (mPackages) {
3775            return addPermissionLocked(info, true);
3776        }
3777    }
3778
3779    @Override
3780    public void removePermission(String name) {
3781        synchronized (mPackages) {
3782            checkPermissionTreeLP(name);
3783            BasePermission bp = mSettings.mPermissions.get(name);
3784            if (bp != null) {
3785                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3786                    throw new SecurityException(
3787                            "Not allowed to modify non-dynamic permission "
3788                            + name);
3789                }
3790                mSettings.mPermissions.remove(name);
3791                mSettings.writeLPr();
3792            }
3793        }
3794    }
3795
3796    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3797            BasePermission bp) {
3798        int index = pkg.requestedPermissions.indexOf(bp.name);
3799        if (index == -1) {
3800            throw new SecurityException("Package " + pkg.packageName
3801                    + " has not requested permission " + bp.name);
3802        }
3803        if (!bp.isRuntime() && !bp.isDevelopment()) {
3804            throw new SecurityException("Permission " + bp.name
3805                    + " is not a changeable permission type");
3806        }
3807    }
3808
3809    @Override
3810    public void grantRuntimePermission(String packageName, String name, final int userId) {
3811        if (!sUserManager.exists(userId)) {
3812            Log.e(TAG, "No such user:" + userId);
3813            return;
3814        }
3815
3816        mContext.enforceCallingOrSelfPermission(
3817                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3818                "grantRuntimePermission");
3819
3820        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3821                true /* requireFullPermission */, true /* checkShell */,
3822                "grantRuntimePermission");
3823
3824        final int uid;
3825        final SettingBase sb;
3826
3827        synchronized (mPackages) {
3828            final PackageParser.Package pkg = mPackages.get(packageName);
3829            if (pkg == null) {
3830                throw new IllegalArgumentException("Unknown package: " + packageName);
3831            }
3832
3833            final BasePermission bp = mSettings.mPermissions.get(name);
3834            if (bp == null) {
3835                throw new IllegalArgumentException("Unknown permission: " + name);
3836            }
3837
3838            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3839
3840            // If a permission review is required for legacy apps we represent
3841            // their permissions as always granted runtime ones since we need
3842            // to keep the review required permission flag per user while an
3843            // install permission's state is shared across all users.
3844            if (Build.PERMISSIONS_REVIEW_REQUIRED
3845                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3846                    && bp.isRuntime()) {
3847                return;
3848            }
3849
3850            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3851            sb = (SettingBase) pkg.mExtras;
3852            if (sb == null) {
3853                throw new IllegalArgumentException("Unknown package: " + packageName);
3854            }
3855
3856            final PermissionsState permissionsState = sb.getPermissionsState();
3857
3858            final int flags = permissionsState.getPermissionFlags(name, userId);
3859            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3860                throw new SecurityException("Cannot grant system fixed permission "
3861                        + name + " for package " + packageName);
3862            }
3863
3864            if (bp.isDevelopment()) {
3865                // Development permissions must be handled specially, since they are not
3866                // normal runtime permissions.  For now they apply to all users.
3867                if (permissionsState.grantInstallPermission(bp) !=
3868                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3869                    scheduleWriteSettingsLocked();
3870                }
3871                return;
3872            }
3873
3874            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3875                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3876                return;
3877            }
3878
3879            final int result = permissionsState.grantRuntimePermission(bp, userId);
3880            switch (result) {
3881                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3882                    return;
3883                }
3884
3885                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3886                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3887                    mHandler.post(new Runnable() {
3888                        @Override
3889                        public void run() {
3890                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3891                        }
3892                    });
3893                }
3894                break;
3895            }
3896
3897            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3898
3899            // Not critical if that is lost - app has to request again.
3900            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3901        }
3902
3903        // Only need to do this if user is initialized. Otherwise it's a new user
3904        // and there are no processes running as the user yet and there's no need
3905        // to make an expensive call to remount processes for the changed permissions.
3906        if (READ_EXTERNAL_STORAGE.equals(name)
3907                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3908            final long token = Binder.clearCallingIdentity();
3909            try {
3910                if (sUserManager.isInitialized(userId)) {
3911                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3912                            MountServiceInternal.class);
3913                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3914                }
3915            } finally {
3916                Binder.restoreCallingIdentity(token);
3917            }
3918        }
3919    }
3920
3921    @Override
3922    public void revokeRuntimePermission(String packageName, String name, int userId) {
3923        if (!sUserManager.exists(userId)) {
3924            Log.e(TAG, "No such user:" + userId);
3925            return;
3926        }
3927
3928        mContext.enforceCallingOrSelfPermission(
3929                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3930                "revokeRuntimePermission");
3931
3932        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3933                true /* requireFullPermission */, true /* checkShell */,
3934                "revokeRuntimePermission");
3935
3936        final int appId;
3937
3938        synchronized (mPackages) {
3939            final PackageParser.Package pkg = mPackages.get(packageName);
3940            if (pkg == null) {
3941                throw new IllegalArgumentException("Unknown package: " + packageName);
3942            }
3943
3944            final BasePermission bp = mSettings.mPermissions.get(name);
3945            if (bp == null) {
3946                throw new IllegalArgumentException("Unknown permission: " + name);
3947            }
3948
3949            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3950
3951            // If a permission review is required for legacy apps we represent
3952            // their permissions as always granted runtime ones since we need
3953            // to keep the review required permission flag per user while an
3954            // install permission's state is shared across all users.
3955            if (Build.PERMISSIONS_REVIEW_REQUIRED
3956                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3957                    && bp.isRuntime()) {
3958                return;
3959            }
3960
3961            SettingBase sb = (SettingBase) pkg.mExtras;
3962            if (sb == null) {
3963                throw new IllegalArgumentException("Unknown package: " + packageName);
3964            }
3965
3966            final PermissionsState permissionsState = sb.getPermissionsState();
3967
3968            final int flags = permissionsState.getPermissionFlags(name, userId);
3969            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3970                throw new SecurityException("Cannot revoke system fixed permission "
3971                        + name + " for package " + packageName);
3972            }
3973
3974            if (bp.isDevelopment()) {
3975                // Development permissions must be handled specially, since they are not
3976                // normal runtime permissions.  For now they apply to all users.
3977                if (permissionsState.revokeInstallPermission(bp) !=
3978                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3979                    scheduleWriteSettingsLocked();
3980                }
3981                return;
3982            }
3983
3984            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3985                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3986                return;
3987            }
3988
3989            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3990
3991            // Critical, after this call app should never have the permission.
3992            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3993
3994            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3995        }
3996
3997        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3998    }
3999
4000    @Override
4001    public void resetRuntimePermissions() {
4002        mContext.enforceCallingOrSelfPermission(
4003                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4004                "revokeRuntimePermission");
4005
4006        int callingUid = Binder.getCallingUid();
4007        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4008            mContext.enforceCallingOrSelfPermission(
4009                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4010                    "resetRuntimePermissions");
4011        }
4012
4013        synchronized (mPackages) {
4014            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4015            for (int userId : UserManagerService.getInstance().getUserIds()) {
4016                final int packageCount = mPackages.size();
4017                for (int i = 0; i < packageCount; i++) {
4018                    PackageParser.Package pkg = mPackages.valueAt(i);
4019                    if (!(pkg.mExtras instanceof PackageSetting)) {
4020                        continue;
4021                    }
4022                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4023                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4024                }
4025            }
4026        }
4027    }
4028
4029    @Override
4030    public int getPermissionFlags(String name, String packageName, int userId) {
4031        if (!sUserManager.exists(userId)) {
4032            return 0;
4033        }
4034
4035        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4036
4037        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4038                true /* requireFullPermission */, false /* checkShell */,
4039                "getPermissionFlags");
4040
4041        synchronized (mPackages) {
4042            final PackageParser.Package pkg = mPackages.get(packageName);
4043            if (pkg == null) {
4044                throw new IllegalArgumentException("Unknown package: " + packageName);
4045            }
4046
4047            final BasePermission bp = mSettings.mPermissions.get(name);
4048            if (bp == null) {
4049                throw new IllegalArgumentException("Unknown permission: " + name);
4050            }
4051
4052            SettingBase sb = (SettingBase) pkg.mExtras;
4053            if (sb == null) {
4054                throw new IllegalArgumentException("Unknown package: " + packageName);
4055            }
4056
4057            PermissionsState permissionsState = sb.getPermissionsState();
4058            return permissionsState.getPermissionFlags(name, userId);
4059        }
4060    }
4061
4062    @Override
4063    public void updatePermissionFlags(String name, String packageName, int flagMask,
4064            int flagValues, int userId) {
4065        if (!sUserManager.exists(userId)) {
4066            return;
4067        }
4068
4069        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4070
4071        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4072                true /* requireFullPermission */, true /* checkShell */,
4073                "updatePermissionFlags");
4074
4075        // Only the system can change these flags and nothing else.
4076        if (getCallingUid() != Process.SYSTEM_UID) {
4077            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4078            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4079            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4080            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4081            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4082        }
4083
4084        synchronized (mPackages) {
4085            final PackageParser.Package pkg = mPackages.get(packageName);
4086            if (pkg == null) {
4087                throw new IllegalArgumentException("Unknown package: " + packageName);
4088            }
4089
4090            final BasePermission bp = mSettings.mPermissions.get(name);
4091            if (bp == null) {
4092                throw new IllegalArgumentException("Unknown permission: " + name);
4093            }
4094
4095            SettingBase sb = (SettingBase) pkg.mExtras;
4096            if (sb == null) {
4097                throw new IllegalArgumentException("Unknown package: " + packageName);
4098            }
4099
4100            PermissionsState permissionsState = sb.getPermissionsState();
4101
4102            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4103
4104            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4105                // Install and runtime permissions are stored in different places,
4106                // so figure out what permission changed and persist the change.
4107                if (permissionsState.getInstallPermissionState(name) != null) {
4108                    scheduleWriteSettingsLocked();
4109                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4110                        || hadState) {
4111                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4112                }
4113            }
4114        }
4115    }
4116
4117    /**
4118     * Update the permission flags for all packages and runtime permissions of a user in order
4119     * to allow device or profile owner to remove POLICY_FIXED.
4120     */
4121    @Override
4122    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4123        if (!sUserManager.exists(userId)) {
4124            return;
4125        }
4126
4127        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4128
4129        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4130                true /* requireFullPermission */, true /* checkShell */,
4131                "updatePermissionFlagsForAllApps");
4132
4133        // Only the system can change system fixed flags.
4134        if (getCallingUid() != Process.SYSTEM_UID) {
4135            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4136            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4137        }
4138
4139        synchronized (mPackages) {
4140            boolean changed = false;
4141            final int packageCount = mPackages.size();
4142            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4143                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4144                SettingBase sb = (SettingBase) pkg.mExtras;
4145                if (sb == null) {
4146                    continue;
4147                }
4148                PermissionsState permissionsState = sb.getPermissionsState();
4149                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4150                        userId, flagMask, flagValues);
4151            }
4152            if (changed) {
4153                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4154            }
4155        }
4156    }
4157
4158    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4159        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4160                != PackageManager.PERMISSION_GRANTED
4161            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4162                != PackageManager.PERMISSION_GRANTED) {
4163            throw new SecurityException(message + " requires "
4164                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4165                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4166        }
4167    }
4168
4169    @Override
4170    public boolean shouldShowRequestPermissionRationale(String permissionName,
4171            String packageName, int userId) {
4172        if (UserHandle.getCallingUserId() != userId) {
4173            mContext.enforceCallingPermission(
4174                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4175                    "canShowRequestPermissionRationale for user " + userId);
4176        }
4177
4178        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4179        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4180            return false;
4181        }
4182
4183        if (checkPermission(permissionName, packageName, userId)
4184                == PackageManager.PERMISSION_GRANTED) {
4185            return false;
4186        }
4187
4188        final int flags;
4189
4190        final long identity = Binder.clearCallingIdentity();
4191        try {
4192            flags = getPermissionFlags(permissionName,
4193                    packageName, userId);
4194        } finally {
4195            Binder.restoreCallingIdentity(identity);
4196        }
4197
4198        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4199                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4200                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4201
4202        if ((flags & fixedFlags) != 0) {
4203            return false;
4204        }
4205
4206        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4207    }
4208
4209    @Override
4210    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4211        mContext.enforceCallingOrSelfPermission(
4212                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4213                "addOnPermissionsChangeListener");
4214
4215        synchronized (mPackages) {
4216            mOnPermissionChangeListeners.addListenerLocked(listener);
4217        }
4218    }
4219
4220    @Override
4221    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4222        synchronized (mPackages) {
4223            mOnPermissionChangeListeners.removeListenerLocked(listener);
4224        }
4225    }
4226
4227    @Override
4228    public boolean isProtectedBroadcast(String actionName) {
4229        synchronized (mPackages) {
4230            if (mProtectedBroadcasts.contains(actionName)) {
4231                return true;
4232            } else if (actionName != null) {
4233                // TODO: remove these terrible hacks
4234                if (actionName.startsWith("android.net.netmon.lingerExpired")
4235                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4236                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4237                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4238                    return true;
4239                }
4240            }
4241        }
4242        return false;
4243    }
4244
4245    @Override
4246    public int checkSignatures(String pkg1, String pkg2) {
4247        synchronized (mPackages) {
4248            final PackageParser.Package p1 = mPackages.get(pkg1);
4249            final PackageParser.Package p2 = mPackages.get(pkg2);
4250            if (p1 == null || p1.mExtras == null
4251                    || p2 == null || p2.mExtras == null) {
4252                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4253            }
4254            return compareSignatures(p1.mSignatures, p2.mSignatures);
4255        }
4256    }
4257
4258    @Override
4259    public int checkUidSignatures(int uid1, int uid2) {
4260        // Map to base uids.
4261        uid1 = UserHandle.getAppId(uid1);
4262        uid2 = UserHandle.getAppId(uid2);
4263        // reader
4264        synchronized (mPackages) {
4265            Signature[] s1;
4266            Signature[] s2;
4267            Object obj = mSettings.getUserIdLPr(uid1);
4268            if (obj != null) {
4269                if (obj instanceof SharedUserSetting) {
4270                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4271                } else if (obj instanceof PackageSetting) {
4272                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4273                } else {
4274                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4275                }
4276            } else {
4277                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4278            }
4279            obj = mSettings.getUserIdLPr(uid2);
4280            if (obj != null) {
4281                if (obj instanceof SharedUserSetting) {
4282                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4283                } else if (obj instanceof PackageSetting) {
4284                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4285                } else {
4286                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4287                }
4288            } else {
4289                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4290            }
4291            return compareSignatures(s1, s2);
4292        }
4293    }
4294
4295    private void killUid(int appId, int userId, String reason) {
4296        final long identity = Binder.clearCallingIdentity();
4297        try {
4298            IActivityManager am = ActivityManagerNative.getDefault();
4299            if (am != null) {
4300                try {
4301                    am.killUid(appId, userId, reason);
4302                } catch (RemoteException e) {
4303                    /* ignore - same process */
4304                }
4305            }
4306        } finally {
4307            Binder.restoreCallingIdentity(identity);
4308        }
4309    }
4310
4311    /**
4312     * Compares two sets of signatures. Returns:
4313     * <br />
4314     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4315     * <br />
4316     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4317     * <br />
4318     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4319     * <br />
4320     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4321     * <br />
4322     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4323     */
4324    static int compareSignatures(Signature[] s1, Signature[] s2) {
4325        if (s1 == null) {
4326            return s2 == null
4327                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4328                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4329        }
4330
4331        if (s2 == null) {
4332            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4333        }
4334
4335        if (s1.length != s2.length) {
4336            return PackageManager.SIGNATURE_NO_MATCH;
4337        }
4338
4339        // Since both signature sets are of size 1, we can compare without HashSets.
4340        if (s1.length == 1) {
4341            return s1[0].equals(s2[0]) ?
4342                    PackageManager.SIGNATURE_MATCH :
4343                    PackageManager.SIGNATURE_NO_MATCH;
4344        }
4345
4346        ArraySet<Signature> set1 = new ArraySet<Signature>();
4347        for (Signature sig : s1) {
4348            set1.add(sig);
4349        }
4350        ArraySet<Signature> set2 = new ArraySet<Signature>();
4351        for (Signature sig : s2) {
4352            set2.add(sig);
4353        }
4354        // Make sure s2 contains all signatures in s1.
4355        if (set1.equals(set2)) {
4356            return PackageManager.SIGNATURE_MATCH;
4357        }
4358        return PackageManager.SIGNATURE_NO_MATCH;
4359    }
4360
4361    /**
4362     * If the database version for this type of package (internal storage or
4363     * external storage) is less than the version where package signatures
4364     * were updated, return true.
4365     */
4366    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4367        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4368        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4369    }
4370
4371    /**
4372     * Used for backward compatibility to make sure any packages with
4373     * certificate chains get upgraded to the new style. {@code existingSigs}
4374     * will be in the old format (since they were stored on disk from before the
4375     * system upgrade) and {@code scannedSigs} will be in the newer format.
4376     */
4377    private int compareSignaturesCompat(PackageSignatures existingSigs,
4378            PackageParser.Package scannedPkg) {
4379        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4380            return PackageManager.SIGNATURE_NO_MATCH;
4381        }
4382
4383        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4384        for (Signature sig : existingSigs.mSignatures) {
4385            existingSet.add(sig);
4386        }
4387        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4388        for (Signature sig : scannedPkg.mSignatures) {
4389            try {
4390                Signature[] chainSignatures = sig.getChainSignatures();
4391                for (Signature chainSig : chainSignatures) {
4392                    scannedCompatSet.add(chainSig);
4393                }
4394            } catch (CertificateEncodingException e) {
4395                scannedCompatSet.add(sig);
4396            }
4397        }
4398        /*
4399         * Make sure the expanded scanned set contains all signatures in the
4400         * existing one.
4401         */
4402        if (scannedCompatSet.equals(existingSet)) {
4403            // Migrate the old signatures to the new scheme.
4404            existingSigs.assignSignatures(scannedPkg.mSignatures);
4405            // The new KeySets will be re-added later in the scanning process.
4406            synchronized (mPackages) {
4407                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4408            }
4409            return PackageManager.SIGNATURE_MATCH;
4410        }
4411        return PackageManager.SIGNATURE_NO_MATCH;
4412    }
4413
4414    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4415        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4416        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4417    }
4418
4419    private int compareSignaturesRecover(PackageSignatures existingSigs,
4420            PackageParser.Package scannedPkg) {
4421        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4422            return PackageManager.SIGNATURE_NO_MATCH;
4423        }
4424
4425        String msg = null;
4426        try {
4427            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4428                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4429                        + scannedPkg.packageName);
4430                return PackageManager.SIGNATURE_MATCH;
4431            }
4432        } catch (CertificateException e) {
4433            msg = e.getMessage();
4434        }
4435
4436        logCriticalInfo(Log.INFO,
4437                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4438        return PackageManager.SIGNATURE_NO_MATCH;
4439    }
4440
4441    @Override
4442    public String[] getPackagesForUid(int uid) {
4443        uid = UserHandle.getAppId(uid);
4444        // reader
4445        synchronized (mPackages) {
4446            Object obj = mSettings.getUserIdLPr(uid);
4447            if (obj instanceof SharedUserSetting) {
4448                final SharedUserSetting sus = (SharedUserSetting) obj;
4449                final int N = sus.packages.size();
4450                final String[] res = new String[N];
4451                final Iterator<PackageSetting> it = sus.packages.iterator();
4452                int i = 0;
4453                while (it.hasNext()) {
4454                    res[i++] = it.next().name;
4455                }
4456                return res;
4457            } else if (obj instanceof PackageSetting) {
4458                final PackageSetting ps = (PackageSetting) obj;
4459                return new String[] { ps.name };
4460            }
4461        }
4462        return null;
4463    }
4464
4465    @Override
4466    public String getNameForUid(int uid) {
4467        // reader
4468        synchronized (mPackages) {
4469            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4470            if (obj instanceof SharedUserSetting) {
4471                final SharedUserSetting sus = (SharedUserSetting) obj;
4472                return sus.name + ":" + sus.userId;
4473            } else if (obj instanceof PackageSetting) {
4474                final PackageSetting ps = (PackageSetting) obj;
4475                return ps.name;
4476            }
4477        }
4478        return null;
4479    }
4480
4481    @Override
4482    public int getUidForSharedUser(String sharedUserName) {
4483        if(sharedUserName == null) {
4484            return -1;
4485        }
4486        // reader
4487        synchronized (mPackages) {
4488            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4489            if (suid == null) {
4490                return -1;
4491            }
4492            return suid.userId;
4493        }
4494    }
4495
4496    @Override
4497    public int getFlagsForUid(int uid) {
4498        synchronized (mPackages) {
4499            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4500            if (obj instanceof SharedUserSetting) {
4501                final SharedUserSetting sus = (SharedUserSetting) obj;
4502                return sus.pkgFlags;
4503            } else if (obj instanceof PackageSetting) {
4504                final PackageSetting ps = (PackageSetting) obj;
4505                return ps.pkgFlags;
4506            }
4507        }
4508        return 0;
4509    }
4510
4511    @Override
4512    public int getPrivateFlagsForUid(int uid) {
4513        synchronized (mPackages) {
4514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4515            if (obj instanceof SharedUserSetting) {
4516                final SharedUserSetting sus = (SharedUserSetting) obj;
4517                return sus.pkgPrivateFlags;
4518            } else if (obj instanceof PackageSetting) {
4519                final PackageSetting ps = (PackageSetting) obj;
4520                return ps.pkgPrivateFlags;
4521            }
4522        }
4523        return 0;
4524    }
4525
4526    @Override
4527    public boolean isUidPrivileged(int uid) {
4528        uid = UserHandle.getAppId(uid);
4529        // reader
4530        synchronized (mPackages) {
4531            Object obj = mSettings.getUserIdLPr(uid);
4532            if (obj instanceof SharedUserSetting) {
4533                final SharedUserSetting sus = (SharedUserSetting) obj;
4534                final Iterator<PackageSetting> it = sus.packages.iterator();
4535                while (it.hasNext()) {
4536                    if (it.next().isPrivileged()) {
4537                        return true;
4538                    }
4539                }
4540            } else if (obj instanceof PackageSetting) {
4541                final PackageSetting ps = (PackageSetting) obj;
4542                return ps.isPrivileged();
4543            }
4544        }
4545        return false;
4546    }
4547
4548    @Override
4549    public String[] getAppOpPermissionPackages(String permissionName) {
4550        synchronized (mPackages) {
4551            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4552            if (pkgs == null) {
4553                return null;
4554            }
4555            return pkgs.toArray(new String[pkgs.size()]);
4556        }
4557    }
4558
4559    @Override
4560    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4561            int flags, int userId) {
4562        if (!sUserManager.exists(userId)) return null;
4563        flags = updateFlagsForResolve(flags, userId, intent);
4564        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4565                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4566        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4567        final ResolveInfo bestChoice =
4568                chooseBestActivity(intent, resolvedType, flags, query, userId);
4569
4570        if (isEphemeralAllowed(intent, query, userId)) {
4571            final EphemeralResolveInfo ai =
4572                    getEphemeralResolveInfo(intent, resolvedType, userId);
4573            if (ai != null) {
4574                if (DEBUG_EPHEMERAL) {
4575                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4576                }
4577                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4578                bestChoice.ephemeralResolveInfo = ai;
4579            }
4580        }
4581        return bestChoice;
4582    }
4583
4584    @Override
4585    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4586            IntentFilter filter, int match, ComponentName activity) {
4587        final int userId = UserHandle.getCallingUserId();
4588        if (DEBUG_PREFERRED) {
4589            Log.v(TAG, "setLastChosenActivity intent=" + intent
4590                + " resolvedType=" + resolvedType
4591                + " flags=" + flags
4592                + " filter=" + filter
4593                + " match=" + match
4594                + " activity=" + activity);
4595            filter.dump(new PrintStreamPrinter(System.out), "    ");
4596        }
4597        intent.setComponent(null);
4598        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4599        // Find any earlier preferred or last chosen entries and nuke them
4600        findPreferredActivity(intent, resolvedType,
4601                flags, query, 0, false, true, false, userId);
4602        // Add the new activity as the last chosen for this filter
4603        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4604                "Setting last chosen");
4605    }
4606
4607    @Override
4608    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4609        final int userId = UserHandle.getCallingUserId();
4610        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4611        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4612        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4613                false, false, false, userId);
4614    }
4615
4616
4617    private boolean isEphemeralAllowed(
4618            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4619        // Short circuit and return early if possible.
4620        if (DISABLE_EPHEMERAL_APPS) {
4621            return false;
4622        }
4623        final int callingUser = UserHandle.getCallingUserId();
4624        if (callingUser != UserHandle.USER_SYSTEM) {
4625            return false;
4626        }
4627        if (mEphemeralResolverConnection == null) {
4628            return false;
4629        }
4630        if (intent.getComponent() != null) {
4631            return false;
4632        }
4633        if (intent.getPackage() != null) {
4634            return false;
4635        }
4636        final boolean isWebUri = hasWebURI(intent);
4637        if (!isWebUri) {
4638            return false;
4639        }
4640        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4641        synchronized (mPackages) {
4642            final int count = resolvedActivites.size();
4643            for (int n = 0; n < count; n++) {
4644                ResolveInfo info = resolvedActivites.get(n);
4645                String packageName = info.activityInfo.packageName;
4646                PackageSetting ps = mSettings.mPackages.get(packageName);
4647                if (ps != null) {
4648                    // Try to get the status from User settings first
4649                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4650                    int status = (int) (packedStatus >> 32);
4651                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4652                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4653                        if (DEBUG_EPHEMERAL) {
4654                            Slog.v(TAG, "DENY ephemeral apps;"
4655                                + " pkg: " + packageName + ", status: " + status);
4656                        }
4657                        return false;
4658                    }
4659                }
4660            }
4661        }
4662        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4663        return true;
4664    }
4665
4666    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4667            int userId) {
4668        MessageDigest digest = null;
4669        try {
4670            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4671        } catch (NoSuchAlgorithmException e) {
4672            // If we can't create a digest, ignore ephemeral apps.
4673            return null;
4674        }
4675
4676        final byte[] hostBytes = intent.getData().getHost().getBytes();
4677        final byte[] digestBytes = digest.digest(hostBytes);
4678        int shaPrefix =
4679                digestBytes[0] << 24
4680                | digestBytes[1] << 16
4681                | digestBytes[2] << 8
4682                | digestBytes[3] << 0;
4683        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4684                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4685        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4686            // No hash prefix match; there are no ephemeral apps for this domain.
4687            return null;
4688        }
4689        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4690            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4691            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4692                continue;
4693            }
4694            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4695            // No filters; this should never happen.
4696            if (filters.isEmpty()) {
4697                continue;
4698            }
4699            // We have a domain match; resolve the filters to see if anything matches.
4700            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4701            for (int j = filters.size() - 1; j >= 0; --j) {
4702                final EphemeralResolveIntentInfo intentInfo =
4703                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4704                ephemeralResolver.addFilter(intentInfo);
4705            }
4706            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4707                    intent, resolvedType, false /*defaultOnly*/, userId);
4708            if (!matchedResolveInfoList.isEmpty()) {
4709                return matchedResolveInfoList.get(0);
4710            }
4711        }
4712        // Hash or filter mis-match; no ephemeral apps for this domain.
4713        return null;
4714    }
4715
4716    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4717            int flags, List<ResolveInfo> query, int userId) {
4718        if (query != null) {
4719            final int N = query.size();
4720            if (N == 1) {
4721                return query.get(0);
4722            } else if (N > 1) {
4723                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4724                // If there is more than one activity with the same priority,
4725                // then let the user decide between them.
4726                ResolveInfo r0 = query.get(0);
4727                ResolveInfo r1 = query.get(1);
4728                if (DEBUG_INTENT_MATCHING || debug) {
4729                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4730                            + r1.activityInfo.name + "=" + r1.priority);
4731                }
4732                // If the first activity has a higher priority, or a different
4733                // default, then it is always desirable to pick it.
4734                if (r0.priority != r1.priority
4735                        || r0.preferredOrder != r1.preferredOrder
4736                        || r0.isDefault != r1.isDefault) {
4737                    return query.get(0);
4738                }
4739                // If we have saved a preference for a preferred activity for
4740                // this Intent, use that.
4741                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4742                        flags, query, r0.priority, true, false, debug, userId);
4743                if (ri != null) {
4744                    return ri;
4745                }
4746                ri = new ResolveInfo(mResolveInfo);
4747                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4748                ri.activityInfo.applicationInfo = new ApplicationInfo(
4749                        ri.activityInfo.applicationInfo);
4750                if (userId != 0) {
4751                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4752                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4753                }
4754                // Make sure that the resolver is displayable in car mode
4755                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4756                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4757                return ri;
4758            }
4759        }
4760        return null;
4761    }
4762
4763    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4764            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4765        final int N = query.size();
4766        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4767                .get(userId);
4768        // Get the list of persistent preferred activities that handle the intent
4769        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4770        List<PersistentPreferredActivity> pprefs = ppir != null
4771                ? ppir.queryIntent(intent, resolvedType,
4772                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4773                : null;
4774        if (pprefs != null && pprefs.size() > 0) {
4775            final int M = pprefs.size();
4776            for (int i=0; i<M; i++) {
4777                final PersistentPreferredActivity ppa = pprefs.get(i);
4778                if (DEBUG_PREFERRED || debug) {
4779                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4780                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4781                            + "\n  component=" + ppa.mComponent);
4782                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4783                }
4784                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4785                        flags | MATCH_DISABLED_COMPONENTS, userId);
4786                if (DEBUG_PREFERRED || debug) {
4787                    Slog.v(TAG, "Found persistent preferred activity:");
4788                    if (ai != null) {
4789                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4790                    } else {
4791                        Slog.v(TAG, "  null");
4792                    }
4793                }
4794                if (ai == null) {
4795                    // This previously registered persistent preferred activity
4796                    // component is no longer known. Ignore it and do NOT remove it.
4797                    continue;
4798                }
4799                for (int j=0; j<N; j++) {
4800                    final ResolveInfo ri = query.get(j);
4801                    if (!ri.activityInfo.applicationInfo.packageName
4802                            .equals(ai.applicationInfo.packageName)) {
4803                        continue;
4804                    }
4805                    if (!ri.activityInfo.name.equals(ai.name)) {
4806                        continue;
4807                    }
4808                    //  Found a persistent preference that can handle the intent.
4809                    if (DEBUG_PREFERRED || debug) {
4810                        Slog.v(TAG, "Returning persistent preferred activity: " +
4811                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4812                    }
4813                    return ri;
4814                }
4815            }
4816        }
4817        return null;
4818    }
4819
4820    // TODO: handle preferred activities missing while user has amnesia
4821    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4822            List<ResolveInfo> query, int priority, boolean always,
4823            boolean removeMatches, boolean debug, int userId) {
4824        if (!sUserManager.exists(userId)) return null;
4825        flags = updateFlagsForResolve(flags, userId, intent);
4826        // writer
4827        synchronized (mPackages) {
4828            if (intent.getSelector() != null) {
4829                intent = intent.getSelector();
4830            }
4831            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4832
4833            // Try to find a matching persistent preferred activity.
4834            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4835                    debug, userId);
4836
4837            // If a persistent preferred activity matched, use it.
4838            if (pri != null) {
4839                return pri;
4840            }
4841
4842            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4843            // Get the list of preferred activities that handle the intent
4844            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4845            List<PreferredActivity> prefs = pir != null
4846                    ? pir.queryIntent(intent, resolvedType,
4847                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4848                    : null;
4849            if (prefs != null && prefs.size() > 0) {
4850                boolean changed = false;
4851                try {
4852                    // First figure out how good the original match set is.
4853                    // We will only allow preferred activities that came
4854                    // from the same match quality.
4855                    int match = 0;
4856
4857                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4858
4859                    final int N = query.size();
4860                    for (int j=0; j<N; j++) {
4861                        final ResolveInfo ri = query.get(j);
4862                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4863                                + ": 0x" + Integer.toHexString(match));
4864                        if (ri.match > match) {
4865                            match = ri.match;
4866                        }
4867                    }
4868
4869                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4870                            + Integer.toHexString(match));
4871
4872                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4873                    final int M = prefs.size();
4874                    for (int i=0; i<M; i++) {
4875                        final PreferredActivity pa = prefs.get(i);
4876                        if (DEBUG_PREFERRED || debug) {
4877                            Slog.v(TAG, "Checking PreferredActivity ds="
4878                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4879                                    + "\n  component=" + pa.mPref.mComponent);
4880                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4881                        }
4882                        if (pa.mPref.mMatch != match) {
4883                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4884                                    + Integer.toHexString(pa.mPref.mMatch));
4885                            continue;
4886                        }
4887                        // If it's not an "always" type preferred activity and that's what we're
4888                        // looking for, skip it.
4889                        if (always && !pa.mPref.mAlways) {
4890                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4891                            continue;
4892                        }
4893                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4894                                flags | MATCH_DISABLED_COMPONENTS, userId);
4895                        if (DEBUG_PREFERRED || debug) {
4896                            Slog.v(TAG, "Found preferred activity:");
4897                            if (ai != null) {
4898                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4899                            } else {
4900                                Slog.v(TAG, "  null");
4901                            }
4902                        }
4903                        if (ai == null) {
4904                            // This previously registered preferred activity
4905                            // component is no longer known.  Most likely an update
4906                            // to the app was installed and in the new version this
4907                            // component no longer exists.  Clean it up by removing
4908                            // it from the preferred activities list, and skip it.
4909                            Slog.w(TAG, "Removing dangling preferred activity: "
4910                                    + pa.mPref.mComponent);
4911                            pir.removeFilter(pa);
4912                            changed = true;
4913                            continue;
4914                        }
4915                        for (int j=0; j<N; j++) {
4916                            final ResolveInfo ri = query.get(j);
4917                            if (!ri.activityInfo.applicationInfo.packageName
4918                                    .equals(ai.applicationInfo.packageName)) {
4919                                continue;
4920                            }
4921                            if (!ri.activityInfo.name.equals(ai.name)) {
4922                                continue;
4923                            }
4924
4925                            if (removeMatches) {
4926                                pir.removeFilter(pa);
4927                                changed = true;
4928                                if (DEBUG_PREFERRED) {
4929                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4930                                }
4931                                break;
4932                            }
4933
4934                            // Okay we found a previously set preferred or last chosen app.
4935                            // If the result set is different from when this
4936                            // was created, we need to clear it and re-ask the
4937                            // user their preference, if we're looking for an "always" type entry.
4938                            if (always && !pa.mPref.sameSet(query)) {
4939                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4940                                        + intent + " type " + resolvedType);
4941                                if (DEBUG_PREFERRED) {
4942                                    Slog.v(TAG, "Removing preferred activity since set changed "
4943                                            + pa.mPref.mComponent);
4944                                }
4945                                pir.removeFilter(pa);
4946                                // Re-add the filter as a "last chosen" entry (!always)
4947                                PreferredActivity lastChosen = new PreferredActivity(
4948                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4949                                pir.addFilter(lastChosen);
4950                                changed = true;
4951                                return null;
4952                            }
4953
4954                            // Yay! Either the set matched or we're looking for the last chosen
4955                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4956                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4957                            return ri;
4958                        }
4959                    }
4960                } finally {
4961                    if (changed) {
4962                        if (DEBUG_PREFERRED) {
4963                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4964                        }
4965                        scheduleWritePackageRestrictionsLocked(userId);
4966                    }
4967                }
4968            }
4969        }
4970        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4971        return null;
4972    }
4973
4974    /*
4975     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4976     */
4977    @Override
4978    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4979            int targetUserId) {
4980        mContext.enforceCallingOrSelfPermission(
4981                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4982        List<CrossProfileIntentFilter> matches =
4983                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4984        if (matches != null) {
4985            int size = matches.size();
4986            for (int i = 0; i < size; i++) {
4987                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4988            }
4989        }
4990        if (hasWebURI(intent)) {
4991            // cross-profile app linking works only towards the parent.
4992            final UserInfo parent = getProfileParent(sourceUserId);
4993            synchronized(mPackages) {
4994                int flags = updateFlagsForResolve(0, parent.id, intent);
4995                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4996                        intent, resolvedType, flags, sourceUserId, parent.id);
4997                return xpDomainInfo != null;
4998            }
4999        }
5000        return false;
5001    }
5002
5003    private UserInfo getProfileParent(int userId) {
5004        final long identity = Binder.clearCallingIdentity();
5005        try {
5006            return sUserManager.getProfileParent(userId);
5007        } finally {
5008            Binder.restoreCallingIdentity(identity);
5009        }
5010    }
5011
5012    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5013            String resolvedType, int userId) {
5014        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5015        if (resolver != null) {
5016            return resolver.queryIntent(intent, resolvedType, false, userId);
5017        }
5018        return null;
5019    }
5020
5021    @Override
5022    public List<ResolveInfo> queryIntentActivities(Intent intent,
5023            String resolvedType, int flags, int userId) {
5024        if (!sUserManager.exists(userId)) return Collections.emptyList();
5025        flags = updateFlagsForResolve(flags, userId, intent);
5026        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5027                false /* requireFullPermission */, false /* checkShell */,
5028                "query intent activities");
5029        ComponentName comp = intent.getComponent();
5030        if (comp == null) {
5031            if (intent.getSelector() != null) {
5032                intent = intent.getSelector();
5033                comp = intent.getComponent();
5034            }
5035        }
5036
5037        if (comp != null) {
5038            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5039            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5040            if (ai != null) {
5041                final ResolveInfo ri = new ResolveInfo();
5042                ri.activityInfo = ai;
5043                list.add(ri);
5044            }
5045            return list;
5046        }
5047
5048        // reader
5049        synchronized (mPackages) {
5050            final String pkgName = intent.getPackage();
5051            if (pkgName == null) {
5052                List<CrossProfileIntentFilter> matchingFilters =
5053                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5054                // Check for results that need to skip the current profile.
5055                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5056                        resolvedType, flags, userId);
5057                if (xpResolveInfo != null) {
5058                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5059                    result.add(xpResolveInfo);
5060                    return filterIfNotSystemUser(result, userId);
5061                }
5062
5063                // Check for results in the current profile.
5064                List<ResolveInfo> result = mActivities.queryIntent(
5065                        intent, resolvedType, flags, userId);
5066                result = filterIfNotSystemUser(result, userId);
5067
5068                // Check for cross profile results.
5069                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5070                xpResolveInfo = queryCrossProfileIntents(
5071                        matchingFilters, intent, resolvedType, flags, userId,
5072                        hasNonNegativePriorityResult);
5073                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5074                    boolean isVisibleToUser = filterIfNotSystemUser(
5075                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5076                    if (isVisibleToUser) {
5077                        result.add(xpResolveInfo);
5078                        Collections.sort(result, mResolvePrioritySorter);
5079                    }
5080                }
5081                if (hasWebURI(intent)) {
5082                    CrossProfileDomainInfo xpDomainInfo = null;
5083                    final UserInfo parent = getProfileParent(userId);
5084                    if (parent != null) {
5085                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5086                                flags, userId, parent.id);
5087                    }
5088                    if (xpDomainInfo != null) {
5089                        if (xpResolveInfo != null) {
5090                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5091                            // in the result.
5092                            result.remove(xpResolveInfo);
5093                        }
5094                        if (result.size() == 0) {
5095                            result.add(xpDomainInfo.resolveInfo);
5096                            return result;
5097                        }
5098                    } else if (result.size() <= 1) {
5099                        return result;
5100                    }
5101                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5102                            xpDomainInfo, userId);
5103                    Collections.sort(result, mResolvePrioritySorter);
5104                }
5105                return result;
5106            }
5107            final PackageParser.Package pkg = mPackages.get(pkgName);
5108            if (pkg != null) {
5109                return filterIfNotSystemUser(
5110                        mActivities.queryIntentForPackage(
5111                                intent, resolvedType, flags, pkg.activities, userId),
5112                        userId);
5113            }
5114            return new ArrayList<ResolveInfo>();
5115        }
5116    }
5117
5118    private static class CrossProfileDomainInfo {
5119        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5120        ResolveInfo resolveInfo;
5121        /* Best domain verification status of the activities found in the other profile */
5122        int bestDomainVerificationStatus;
5123    }
5124
5125    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5126            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5127        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5128                sourceUserId)) {
5129            return null;
5130        }
5131        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5132                resolvedType, flags, parentUserId);
5133
5134        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5135            return null;
5136        }
5137        CrossProfileDomainInfo result = null;
5138        int size = resultTargetUser.size();
5139        for (int i = 0; i < size; i++) {
5140            ResolveInfo riTargetUser = resultTargetUser.get(i);
5141            // Intent filter verification is only for filters that specify a host. So don't return
5142            // those that handle all web uris.
5143            if (riTargetUser.handleAllWebDataURI) {
5144                continue;
5145            }
5146            String packageName = riTargetUser.activityInfo.packageName;
5147            PackageSetting ps = mSettings.mPackages.get(packageName);
5148            if (ps == null) {
5149                continue;
5150            }
5151            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5152            int status = (int)(verificationState >> 32);
5153            if (result == null) {
5154                result = new CrossProfileDomainInfo();
5155                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5156                        sourceUserId, parentUserId);
5157                result.bestDomainVerificationStatus = status;
5158            } else {
5159                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5160                        result.bestDomainVerificationStatus);
5161            }
5162        }
5163        // Don't consider matches with status NEVER across profiles.
5164        if (result != null && result.bestDomainVerificationStatus
5165                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5166            return null;
5167        }
5168        return result;
5169    }
5170
5171    /**
5172     * Verification statuses are ordered from the worse to the best, except for
5173     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5174     */
5175    private int bestDomainVerificationStatus(int status1, int status2) {
5176        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5177            return status2;
5178        }
5179        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5180            return status1;
5181        }
5182        return (int) MathUtils.max(status1, status2);
5183    }
5184
5185    private boolean isUserEnabled(int userId) {
5186        long callingId = Binder.clearCallingIdentity();
5187        try {
5188            UserInfo userInfo = sUserManager.getUserInfo(userId);
5189            return userInfo != null && userInfo.isEnabled();
5190        } finally {
5191            Binder.restoreCallingIdentity(callingId);
5192        }
5193    }
5194
5195    /**
5196     * Filter out activities with systemUserOnly flag set, when current user is not System.
5197     *
5198     * @return filtered list
5199     */
5200    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5201        if (userId == UserHandle.USER_SYSTEM) {
5202            return resolveInfos;
5203        }
5204        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5205            ResolveInfo info = resolveInfos.get(i);
5206            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5207                resolveInfos.remove(i);
5208            }
5209        }
5210        return resolveInfos;
5211    }
5212
5213    /**
5214     * @param resolveInfos list of resolve infos in descending priority order
5215     * @return if the list contains a resolve info with non-negative priority
5216     */
5217    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5218        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5219    }
5220
5221    private static boolean hasWebURI(Intent intent) {
5222        if (intent.getData() == null) {
5223            return false;
5224        }
5225        final String scheme = intent.getScheme();
5226        if (TextUtils.isEmpty(scheme)) {
5227            return false;
5228        }
5229        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5230    }
5231
5232    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5233            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5234            int userId) {
5235        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5236
5237        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5238            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5239                    candidates.size());
5240        }
5241
5242        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5243        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5244        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5245        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5246        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5247        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5248
5249        synchronized (mPackages) {
5250            final int count = candidates.size();
5251            // First, try to use linked apps. Partition the candidates into four lists:
5252            // one for the final results, one for the "do not use ever", one for "undefined status"
5253            // and finally one for "browser app type".
5254            for (int n=0; n<count; n++) {
5255                ResolveInfo info = candidates.get(n);
5256                String packageName = info.activityInfo.packageName;
5257                PackageSetting ps = mSettings.mPackages.get(packageName);
5258                if (ps != null) {
5259                    // Add to the special match all list (Browser use case)
5260                    if (info.handleAllWebDataURI) {
5261                        matchAllList.add(info);
5262                        continue;
5263                    }
5264                    // Try to get the status from User settings first
5265                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5266                    int status = (int)(packedStatus >> 32);
5267                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5268                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5269                        if (DEBUG_DOMAIN_VERIFICATION) {
5270                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5271                                    + " : linkgen=" + linkGeneration);
5272                        }
5273                        // Use link-enabled generation as preferredOrder, i.e.
5274                        // prefer newly-enabled over earlier-enabled.
5275                        info.preferredOrder = linkGeneration;
5276                        alwaysList.add(info);
5277                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5278                        if (DEBUG_DOMAIN_VERIFICATION) {
5279                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5280                        }
5281                        neverList.add(info);
5282                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5283                        if (DEBUG_DOMAIN_VERIFICATION) {
5284                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5285                        }
5286                        alwaysAskList.add(info);
5287                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5288                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5289                        if (DEBUG_DOMAIN_VERIFICATION) {
5290                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5291                        }
5292                        undefinedList.add(info);
5293                    }
5294                }
5295            }
5296
5297            // We'll want to include browser possibilities in a few cases
5298            boolean includeBrowser = false;
5299
5300            // First try to add the "always" resolution(s) for the current user, if any
5301            if (alwaysList.size() > 0) {
5302                result.addAll(alwaysList);
5303            } else {
5304                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5305                result.addAll(undefinedList);
5306                // Maybe add one for the other profile.
5307                if (xpDomainInfo != null && (
5308                        xpDomainInfo.bestDomainVerificationStatus
5309                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5310                    result.add(xpDomainInfo.resolveInfo);
5311                }
5312                includeBrowser = true;
5313            }
5314
5315            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5316            // If there were 'always' entries their preferred order has been set, so we also
5317            // back that off to make the alternatives equivalent
5318            if (alwaysAskList.size() > 0) {
5319                for (ResolveInfo i : result) {
5320                    i.preferredOrder = 0;
5321                }
5322                result.addAll(alwaysAskList);
5323                includeBrowser = true;
5324            }
5325
5326            if (includeBrowser) {
5327                // Also add browsers (all of them or only the default one)
5328                if (DEBUG_DOMAIN_VERIFICATION) {
5329                    Slog.v(TAG, "   ...including browsers in candidate set");
5330                }
5331                if ((matchFlags & MATCH_ALL) != 0) {
5332                    result.addAll(matchAllList);
5333                } else {
5334                    // Browser/generic handling case.  If there's a default browser, go straight
5335                    // to that (but only if there is no other higher-priority match).
5336                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5337                    int maxMatchPrio = 0;
5338                    ResolveInfo defaultBrowserMatch = null;
5339                    final int numCandidates = matchAllList.size();
5340                    for (int n = 0; n < numCandidates; n++) {
5341                        ResolveInfo info = matchAllList.get(n);
5342                        // track the highest overall match priority...
5343                        if (info.priority > maxMatchPrio) {
5344                            maxMatchPrio = info.priority;
5345                        }
5346                        // ...and the highest-priority default browser match
5347                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5348                            if (defaultBrowserMatch == null
5349                                    || (defaultBrowserMatch.priority < info.priority)) {
5350                                if (debug) {
5351                                    Slog.v(TAG, "Considering default browser match " + info);
5352                                }
5353                                defaultBrowserMatch = info;
5354                            }
5355                        }
5356                    }
5357                    if (defaultBrowserMatch != null
5358                            && defaultBrowserMatch.priority >= maxMatchPrio
5359                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5360                    {
5361                        if (debug) {
5362                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5363                        }
5364                        result.add(defaultBrowserMatch);
5365                    } else {
5366                        result.addAll(matchAllList);
5367                    }
5368                }
5369
5370                // If there is nothing selected, add all candidates and remove the ones that the user
5371                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5372                if (result.size() == 0) {
5373                    result.addAll(candidates);
5374                    result.removeAll(neverList);
5375                }
5376            }
5377        }
5378        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5379            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5380                    result.size());
5381            for (ResolveInfo info : result) {
5382                Slog.v(TAG, "  + " + info.activityInfo);
5383            }
5384        }
5385        return result;
5386    }
5387
5388    // Returns a packed value as a long:
5389    //
5390    // high 'int'-sized word: link status: undefined/ask/never/always.
5391    // low 'int'-sized word: relative priority among 'always' results.
5392    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5393        long result = ps.getDomainVerificationStatusForUser(userId);
5394        // if none available, get the master status
5395        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5396            if (ps.getIntentFilterVerificationInfo() != null) {
5397                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5398            }
5399        }
5400        return result;
5401    }
5402
5403    private ResolveInfo querySkipCurrentProfileIntents(
5404            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5405            int flags, int sourceUserId) {
5406        if (matchingFilters != null) {
5407            int size = matchingFilters.size();
5408            for (int i = 0; i < size; i ++) {
5409                CrossProfileIntentFilter filter = matchingFilters.get(i);
5410                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5411                    // Checking if there are activities in the target user that can handle the
5412                    // intent.
5413                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5414                            resolvedType, flags, sourceUserId);
5415                    if (resolveInfo != null) {
5416                        return resolveInfo;
5417                    }
5418                }
5419            }
5420        }
5421        return null;
5422    }
5423
5424    // Return matching ResolveInfo in target user if any.
5425    private ResolveInfo queryCrossProfileIntents(
5426            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5427            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5428        if (matchingFilters != null) {
5429            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5430            // match the same intent. For performance reasons, it is better not to
5431            // run queryIntent twice for the same userId
5432            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5433            int size = matchingFilters.size();
5434            for (int i = 0; i < size; i++) {
5435                CrossProfileIntentFilter filter = matchingFilters.get(i);
5436                int targetUserId = filter.getTargetUserId();
5437                boolean skipCurrentProfile =
5438                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5439                boolean skipCurrentProfileIfNoMatchFound =
5440                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5441                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5442                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5443                    // Checking if there are activities in the target user that can handle the
5444                    // intent.
5445                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5446                            resolvedType, flags, sourceUserId);
5447                    if (resolveInfo != null) return resolveInfo;
5448                    alreadyTriedUserIds.put(targetUserId, true);
5449                }
5450            }
5451        }
5452        return null;
5453    }
5454
5455    /**
5456     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5457     * will forward the intent to the filter's target user.
5458     * Otherwise, returns null.
5459     */
5460    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5461            String resolvedType, int flags, int sourceUserId) {
5462        int targetUserId = filter.getTargetUserId();
5463        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5464                resolvedType, flags, targetUserId);
5465        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5466            // If all the matches in the target profile are suspended, return null.
5467            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5468                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5469                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5470                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5471                            targetUserId);
5472                }
5473            }
5474        }
5475        return null;
5476    }
5477
5478    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5479            int sourceUserId, int targetUserId) {
5480        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5481        long ident = Binder.clearCallingIdentity();
5482        boolean targetIsProfile;
5483        try {
5484            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5485        } finally {
5486            Binder.restoreCallingIdentity(ident);
5487        }
5488        String className;
5489        if (targetIsProfile) {
5490            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5491        } else {
5492            className = FORWARD_INTENT_TO_PARENT;
5493        }
5494        ComponentName forwardingActivityComponentName = new ComponentName(
5495                mAndroidApplication.packageName, className);
5496        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5497                sourceUserId);
5498        if (!targetIsProfile) {
5499            forwardingActivityInfo.showUserIcon = targetUserId;
5500            forwardingResolveInfo.noResourceId = true;
5501        }
5502        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5503        forwardingResolveInfo.priority = 0;
5504        forwardingResolveInfo.preferredOrder = 0;
5505        forwardingResolveInfo.match = 0;
5506        forwardingResolveInfo.isDefault = true;
5507        forwardingResolveInfo.filter = filter;
5508        forwardingResolveInfo.targetUserId = targetUserId;
5509        return forwardingResolveInfo;
5510    }
5511
5512    @Override
5513    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5514            Intent[] specifics, String[] specificTypes, Intent intent,
5515            String resolvedType, int flags, int userId) {
5516        if (!sUserManager.exists(userId)) return Collections.emptyList();
5517        flags = updateFlagsForResolve(flags, userId, intent);
5518        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5519                false /* requireFullPermission */, false /* checkShell */,
5520                "query intent activity options");
5521        final String resultsAction = intent.getAction();
5522
5523        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5524                | PackageManager.GET_RESOLVED_FILTER, userId);
5525
5526        if (DEBUG_INTENT_MATCHING) {
5527            Log.v(TAG, "Query " + intent + ": " + results);
5528        }
5529
5530        int specificsPos = 0;
5531        int N;
5532
5533        // todo: note that the algorithm used here is O(N^2).  This
5534        // isn't a problem in our current environment, but if we start running
5535        // into situations where we have more than 5 or 10 matches then this
5536        // should probably be changed to something smarter...
5537
5538        // First we go through and resolve each of the specific items
5539        // that were supplied, taking care of removing any corresponding
5540        // duplicate items in the generic resolve list.
5541        if (specifics != null) {
5542            for (int i=0; i<specifics.length; i++) {
5543                final Intent sintent = specifics[i];
5544                if (sintent == null) {
5545                    continue;
5546                }
5547
5548                if (DEBUG_INTENT_MATCHING) {
5549                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5550                }
5551
5552                String action = sintent.getAction();
5553                if (resultsAction != null && resultsAction.equals(action)) {
5554                    // If this action was explicitly requested, then don't
5555                    // remove things that have it.
5556                    action = null;
5557                }
5558
5559                ResolveInfo ri = null;
5560                ActivityInfo ai = null;
5561
5562                ComponentName comp = sintent.getComponent();
5563                if (comp == null) {
5564                    ri = resolveIntent(
5565                        sintent,
5566                        specificTypes != null ? specificTypes[i] : null,
5567                            flags, userId);
5568                    if (ri == null) {
5569                        continue;
5570                    }
5571                    if (ri == mResolveInfo) {
5572                        // ACK!  Must do something better with this.
5573                    }
5574                    ai = ri.activityInfo;
5575                    comp = new ComponentName(ai.applicationInfo.packageName,
5576                            ai.name);
5577                } else {
5578                    ai = getActivityInfo(comp, flags, userId);
5579                    if (ai == null) {
5580                        continue;
5581                    }
5582                }
5583
5584                // Look for any generic query activities that are duplicates
5585                // of this specific one, and remove them from the results.
5586                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5587                N = results.size();
5588                int j;
5589                for (j=specificsPos; j<N; j++) {
5590                    ResolveInfo sri = results.get(j);
5591                    if ((sri.activityInfo.name.equals(comp.getClassName())
5592                            && sri.activityInfo.applicationInfo.packageName.equals(
5593                                    comp.getPackageName()))
5594                        || (action != null && sri.filter.matchAction(action))) {
5595                        results.remove(j);
5596                        if (DEBUG_INTENT_MATCHING) Log.v(
5597                            TAG, "Removing duplicate item from " + j
5598                            + " due to specific " + specificsPos);
5599                        if (ri == null) {
5600                            ri = sri;
5601                        }
5602                        j--;
5603                        N--;
5604                    }
5605                }
5606
5607                // Add this specific item to its proper place.
5608                if (ri == null) {
5609                    ri = new ResolveInfo();
5610                    ri.activityInfo = ai;
5611                }
5612                results.add(specificsPos, ri);
5613                ri.specificIndex = i;
5614                specificsPos++;
5615            }
5616        }
5617
5618        // Now we go through the remaining generic results and remove any
5619        // duplicate actions that are found here.
5620        N = results.size();
5621        for (int i=specificsPos; i<N-1; i++) {
5622            final ResolveInfo rii = results.get(i);
5623            if (rii.filter == null) {
5624                continue;
5625            }
5626
5627            // Iterate over all of the actions of this result's intent
5628            // filter...  typically this should be just one.
5629            final Iterator<String> it = rii.filter.actionsIterator();
5630            if (it == null) {
5631                continue;
5632            }
5633            while (it.hasNext()) {
5634                final String action = it.next();
5635                if (resultsAction != null && resultsAction.equals(action)) {
5636                    // If this action was explicitly requested, then don't
5637                    // remove things that have it.
5638                    continue;
5639                }
5640                for (int j=i+1; j<N; j++) {
5641                    final ResolveInfo rij = results.get(j);
5642                    if (rij.filter != null && rij.filter.hasAction(action)) {
5643                        results.remove(j);
5644                        if (DEBUG_INTENT_MATCHING) Log.v(
5645                            TAG, "Removing duplicate item from " + j
5646                            + " due to action " + action + " at " + i);
5647                        j--;
5648                        N--;
5649                    }
5650                }
5651            }
5652
5653            // If the caller didn't request filter information, drop it now
5654            // so we don't have to marshall/unmarshall it.
5655            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5656                rii.filter = null;
5657            }
5658        }
5659
5660        // Filter out the caller activity if so requested.
5661        if (caller != null) {
5662            N = results.size();
5663            for (int i=0; i<N; i++) {
5664                ActivityInfo ainfo = results.get(i).activityInfo;
5665                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5666                        && caller.getClassName().equals(ainfo.name)) {
5667                    results.remove(i);
5668                    break;
5669                }
5670            }
5671        }
5672
5673        // If the caller didn't request filter information,
5674        // drop them now so we don't have to
5675        // marshall/unmarshall it.
5676        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5677            N = results.size();
5678            for (int i=0; i<N; i++) {
5679                results.get(i).filter = null;
5680            }
5681        }
5682
5683        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5684        return results;
5685    }
5686
5687    @Override
5688    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5689            int userId) {
5690        if (!sUserManager.exists(userId)) return Collections.emptyList();
5691        flags = updateFlagsForResolve(flags, userId, intent);
5692        ComponentName comp = intent.getComponent();
5693        if (comp == null) {
5694            if (intent.getSelector() != null) {
5695                intent = intent.getSelector();
5696                comp = intent.getComponent();
5697            }
5698        }
5699        if (comp != null) {
5700            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5701            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5702            if (ai != null) {
5703                ResolveInfo ri = new ResolveInfo();
5704                ri.activityInfo = ai;
5705                list.add(ri);
5706            }
5707            return list;
5708        }
5709
5710        // reader
5711        synchronized (mPackages) {
5712            String pkgName = intent.getPackage();
5713            if (pkgName == null) {
5714                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5715            }
5716            final PackageParser.Package pkg = mPackages.get(pkgName);
5717            if (pkg != null) {
5718                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5719                        userId);
5720            }
5721            return null;
5722        }
5723    }
5724
5725    @Override
5726    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5727        if (!sUserManager.exists(userId)) return null;
5728        flags = updateFlagsForResolve(flags, userId, intent);
5729        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5730        if (query != null) {
5731            if (query.size() >= 1) {
5732                // If there is more than one service with the same priority,
5733                // just arbitrarily pick the first one.
5734                return query.get(0);
5735            }
5736        }
5737        return null;
5738    }
5739
5740    @Override
5741    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5742            int userId) {
5743        if (!sUserManager.exists(userId)) return Collections.emptyList();
5744        flags = updateFlagsForResolve(flags, userId, intent);
5745        ComponentName comp = intent.getComponent();
5746        if (comp == null) {
5747            if (intent.getSelector() != null) {
5748                intent = intent.getSelector();
5749                comp = intent.getComponent();
5750            }
5751        }
5752        if (comp != null) {
5753            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5754            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5755            if (si != null) {
5756                final ResolveInfo ri = new ResolveInfo();
5757                ri.serviceInfo = si;
5758                list.add(ri);
5759            }
5760            return list;
5761        }
5762
5763        // reader
5764        synchronized (mPackages) {
5765            String pkgName = intent.getPackage();
5766            if (pkgName == null) {
5767                return mServices.queryIntent(intent, resolvedType, flags, userId);
5768            }
5769            final PackageParser.Package pkg = mPackages.get(pkgName);
5770            if (pkg != null) {
5771                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5772                        userId);
5773            }
5774            return null;
5775        }
5776    }
5777
5778    @Override
5779    public List<ResolveInfo> queryIntentContentProviders(
5780            Intent intent, String resolvedType, int flags, int userId) {
5781        if (!sUserManager.exists(userId)) return Collections.emptyList();
5782        flags = updateFlagsForResolve(flags, userId, intent);
5783        ComponentName comp = intent.getComponent();
5784        if (comp == null) {
5785            if (intent.getSelector() != null) {
5786                intent = intent.getSelector();
5787                comp = intent.getComponent();
5788            }
5789        }
5790        if (comp != null) {
5791            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5792            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5793            if (pi != null) {
5794                final ResolveInfo ri = new ResolveInfo();
5795                ri.providerInfo = pi;
5796                list.add(ri);
5797            }
5798            return list;
5799        }
5800
5801        // reader
5802        synchronized (mPackages) {
5803            String pkgName = intent.getPackage();
5804            if (pkgName == null) {
5805                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5806            }
5807            final PackageParser.Package pkg = mPackages.get(pkgName);
5808            if (pkg != null) {
5809                return mProviders.queryIntentForPackage(
5810                        intent, resolvedType, flags, pkg.providers, userId);
5811            }
5812            return null;
5813        }
5814    }
5815
5816    @Override
5817    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5818        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5819        flags = updateFlagsForPackage(flags, userId, null);
5820        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5821        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5822                true /* requireFullPermission */, false /* checkShell */,
5823                "get installed packages");
5824
5825        // writer
5826        synchronized (mPackages) {
5827            ArrayList<PackageInfo> list;
5828            if (listUninstalled) {
5829                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5830                for (PackageSetting ps : mSettings.mPackages.values()) {
5831                    PackageInfo pi;
5832                    if (ps.pkg != null) {
5833                        pi = generatePackageInfo(ps.pkg, flags, userId);
5834                    } else {
5835                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5836                    }
5837                    if (pi != null) {
5838                        list.add(pi);
5839                    }
5840                }
5841            } else {
5842                list = new ArrayList<PackageInfo>(mPackages.size());
5843                for (PackageParser.Package p : mPackages.values()) {
5844                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5845                    if (pi != null) {
5846                        list.add(pi);
5847                    }
5848                }
5849            }
5850
5851            return new ParceledListSlice<PackageInfo>(list);
5852        }
5853    }
5854
5855    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5856            String[] permissions, boolean[] tmp, int flags, int userId) {
5857        int numMatch = 0;
5858        final PermissionsState permissionsState = ps.getPermissionsState();
5859        for (int i=0; i<permissions.length; i++) {
5860            final String permission = permissions[i];
5861            if (permissionsState.hasPermission(permission, userId)) {
5862                tmp[i] = true;
5863                numMatch++;
5864            } else {
5865                tmp[i] = false;
5866            }
5867        }
5868        if (numMatch == 0) {
5869            return;
5870        }
5871        PackageInfo pi;
5872        if (ps.pkg != null) {
5873            pi = generatePackageInfo(ps.pkg, flags, userId);
5874        } else {
5875            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5876        }
5877        // The above might return null in cases of uninstalled apps or install-state
5878        // skew across users/profiles.
5879        if (pi != null) {
5880            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5881                if (numMatch == permissions.length) {
5882                    pi.requestedPermissions = permissions;
5883                } else {
5884                    pi.requestedPermissions = new String[numMatch];
5885                    numMatch = 0;
5886                    for (int i=0; i<permissions.length; i++) {
5887                        if (tmp[i]) {
5888                            pi.requestedPermissions[numMatch] = permissions[i];
5889                            numMatch++;
5890                        }
5891                    }
5892                }
5893            }
5894            list.add(pi);
5895        }
5896    }
5897
5898    @Override
5899    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5900            String[] permissions, int flags, int userId) {
5901        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5902        flags = updateFlagsForPackage(flags, userId, permissions);
5903        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5904
5905        // writer
5906        synchronized (mPackages) {
5907            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5908            boolean[] tmpBools = new boolean[permissions.length];
5909            if (listUninstalled) {
5910                for (PackageSetting ps : mSettings.mPackages.values()) {
5911                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5912                }
5913            } else {
5914                for (PackageParser.Package pkg : mPackages.values()) {
5915                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5916                    if (ps != null) {
5917                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5918                                userId);
5919                    }
5920                }
5921            }
5922
5923            return new ParceledListSlice<PackageInfo>(list);
5924        }
5925    }
5926
5927    @Override
5928    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5929        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5930        flags = updateFlagsForApplication(flags, userId, null);
5931        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5932
5933        // writer
5934        synchronized (mPackages) {
5935            ArrayList<ApplicationInfo> list;
5936            if (listUninstalled) {
5937                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5938                for (PackageSetting ps : mSettings.mPackages.values()) {
5939                    ApplicationInfo ai;
5940                    if (ps.pkg != null) {
5941                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5942                                ps.readUserState(userId), userId);
5943                    } else {
5944                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5945                    }
5946                    if (ai != null) {
5947                        list.add(ai);
5948                    }
5949                }
5950            } else {
5951                list = new ArrayList<ApplicationInfo>(mPackages.size());
5952                for (PackageParser.Package p : mPackages.values()) {
5953                    if (p.mExtras != null) {
5954                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5955                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5956                        if (ai != null) {
5957                            list.add(ai);
5958                        }
5959                    }
5960                }
5961            }
5962
5963            return new ParceledListSlice<ApplicationInfo>(list);
5964        }
5965    }
5966
5967    @Override
5968    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5969        if (DISABLE_EPHEMERAL_APPS) {
5970            return null;
5971        }
5972
5973        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5974                "getEphemeralApplications");
5975        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5976                true /* requireFullPermission */, false /* checkShell */,
5977                "getEphemeralApplications");
5978        synchronized (mPackages) {
5979            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5980                    .getEphemeralApplicationsLPw(userId);
5981            if (ephemeralApps != null) {
5982                return new ParceledListSlice<>(ephemeralApps);
5983            }
5984        }
5985        return null;
5986    }
5987
5988    @Override
5989    public boolean isEphemeralApplication(String packageName, int userId) {
5990        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5991                true /* requireFullPermission */, false /* checkShell */,
5992                "isEphemeral");
5993        if (DISABLE_EPHEMERAL_APPS) {
5994            return false;
5995        }
5996
5997        if (!isCallerSameApp(packageName)) {
5998            return false;
5999        }
6000        synchronized (mPackages) {
6001            PackageParser.Package pkg = mPackages.get(packageName);
6002            if (pkg != null) {
6003                return pkg.applicationInfo.isEphemeralApp();
6004            }
6005        }
6006        return false;
6007    }
6008
6009    @Override
6010    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6011        if (DISABLE_EPHEMERAL_APPS) {
6012            return null;
6013        }
6014
6015        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6016                true /* requireFullPermission */, false /* checkShell */,
6017                "getCookie");
6018        if (!isCallerSameApp(packageName)) {
6019            return null;
6020        }
6021        synchronized (mPackages) {
6022            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6023                    packageName, userId);
6024        }
6025    }
6026
6027    @Override
6028    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6029        if (DISABLE_EPHEMERAL_APPS) {
6030            return true;
6031        }
6032
6033        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6034                true /* requireFullPermission */, true /* checkShell */,
6035                "setCookie");
6036        if (!isCallerSameApp(packageName)) {
6037            return false;
6038        }
6039        synchronized (mPackages) {
6040            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6041                    packageName, cookie, userId);
6042        }
6043    }
6044
6045    @Override
6046    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6047        if (DISABLE_EPHEMERAL_APPS) {
6048            return null;
6049        }
6050
6051        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6052                "getEphemeralApplicationIcon");
6053        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6054                true /* requireFullPermission */, false /* checkShell */,
6055                "getEphemeralApplicationIcon");
6056        synchronized (mPackages) {
6057            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6058                    packageName, userId);
6059        }
6060    }
6061
6062    private boolean isCallerSameApp(String packageName) {
6063        PackageParser.Package pkg = mPackages.get(packageName);
6064        return pkg != null
6065                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6066    }
6067
6068    public List<ApplicationInfo> getPersistentApplications(int flags) {
6069        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6070
6071        // reader
6072        synchronized (mPackages) {
6073            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6074            final int userId = UserHandle.getCallingUserId();
6075            while (i.hasNext()) {
6076                final PackageParser.Package p = i.next();
6077                if (p.applicationInfo == null) continue;
6078
6079                final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0)
6080                        && !p.applicationInfo.isEncryptionAware();
6081                final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0)
6082                        && p.applicationInfo.isEncryptionAware();
6083
6084                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6085                        && (!mSafeMode || isSystemApp(p))
6086                        && (matchesUnaware || matchesAware)) {
6087                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6088                    if (ps != null) {
6089                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6090                                ps.readUserState(userId), userId);
6091                        if (ai != null) {
6092                            finalList.add(ai);
6093                        }
6094                    }
6095                }
6096            }
6097        }
6098
6099        return finalList;
6100    }
6101
6102    @Override
6103    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6104        if (!sUserManager.exists(userId)) return null;
6105        flags = updateFlagsForComponent(flags, userId, name);
6106        // reader
6107        synchronized (mPackages) {
6108            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6109            PackageSetting ps = provider != null
6110                    ? mSettings.mPackages.get(provider.owner.packageName)
6111                    : null;
6112            return ps != null
6113                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6114                    ? PackageParser.generateProviderInfo(provider, flags,
6115                            ps.readUserState(userId), userId)
6116                    : null;
6117        }
6118    }
6119
6120    /**
6121     * @deprecated
6122     */
6123    @Deprecated
6124    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6125        // reader
6126        synchronized (mPackages) {
6127            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6128                    .entrySet().iterator();
6129            final int userId = UserHandle.getCallingUserId();
6130            while (i.hasNext()) {
6131                Map.Entry<String, PackageParser.Provider> entry = i.next();
6132                PackageParser.Provider p = entry.getValue();
6133                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6134
6135                if (ps != null && p.syncable
6136                        && (!mSafeMode || (p.info.applicationInfo.flags
6137                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6138                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6139                            ps.readUserState(userId), userId);
6140                    if (info != null) {
6141                        outNames.add(entry.getKey());
6142                        outInfo.add(info);
6143                    }
6144                }
6145            }
6146        }
6147    }
6148
6149    @Override
6150    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6151            int uid, int flags) {
6152        final int userId = processName != null ? UserHandle.getUserId(uid)
6153                : UserHandle.getCallingUserId();
6154        if (!sUserManager.exists(userId)) return null;
6155        flags = updateFlagsForComponent(flags, userId, processName);
6156
6157        ArrayList<ProviderInfo> finalList = null;
6158        // reader
6159        synchronized (mPackages) {
6160            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6161            while (i.hasNext()) {
6162                final PackageParser.Provider p = i.next();
6163                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6164                if (ps != null && p.info.authority != null
6165                        && (processName == null
6166                                || (p.info.processName.equals(processName)
6167                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6168                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6169                    if (finalList == null) {
6170                        finalList = new ArrayList<ProviderInfo>(3);
6171                    }
6172                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6173                            ps.readUserState(userId), userId);
6174                    if (info != null) {
6175                        finalList.add(info);
6176                    }
6177                }
6178            }
6179        }
6180
6181        if (finalList != null) {
6182            Collections.sort(finalList, mProviderInitOrderSorter);
6183            return new ParceledListSlice<ProviderInfo>(finalList);
6184        }
6185
6186        return null;
6187    }
6188
6189    @Override
6190    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6191        // reader
6192        synchronized (mPackages) {
6193            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6194            return PackageParser.generateInstrumentationInfo(i, flags);
6195        }
6196    }
6197
6198    @Override
6199    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6200            int flags) {
6201        ArrayList<InstrumentationInfo> finalList =
6202            new ArrayList<InstrumentationInfo>();
6203
6204        // reader
6205        synchronized (mPackages) {
6206            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6207            while (i.hasNext()) {
6208                final PackageParser.Instrumentation p = i.next();
6209                if (targetPackage == null
6210                        || targetPackage.equals(p.info.targetPackage)) {
6211                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6212                            flags);
6213                    if (ii != null) {
6214                        finalList.add(ii);
6215                    }
6216                }
6217            }
6218        }
6219
6220        return finalList;
6221    }
6222
6223    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6224        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6225        if (overlays == null) {
6226            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6227            return;
6228        }
6229        for (PackageParser.Package opkg : overlays.values()) {
6230            // Not much to do if idmap fails: we already logged the error
6231            // and we certainly don't want to abort installation of pkg simply
6232            // because an overlay didn't fit properly. For these reasons,
6233            // ignore the return value of createIdmapForPackagePairLI.
6234            createIdmapForPackagePairLI(pkg, opkg);
6235        }
6236    }
6237
6238    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6239            PackageParser.Package opkg) {
6240        if (!opkg.mTrustedOverlay) {
6241            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6242                    opkg.baseCodePath + ": overlay not trusted");
6243            return false;
6244        }
6245        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6246        if (overlaySet == null) {
6247            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6248                    opkg.baseCodePath + " but target package has no known overlays");
6249            return false;
6250        }
6251        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6252        // TODO: generate idmap for split APKs
6253        try {
6254            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6255        } catch (InstallerException e) {
6256            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6257                    + opkg.baseCodePath);
6258            return false;
6259        }
6260        PackageParser.Package[] overlayArray =
6261            overlaySet.values().toArray(new PackageParser.Package[0]);
6262        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6263            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6264                return p1.mOverlayPriority - p2.mOverlayPriority;
6265            }
6266        };
6267        Arrays.sort(overlayArray, cmp);
6268
6269        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6270        int i = 0;
6271        for (PackageParser.Package p : overlayArray) {
6272            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6273        }
6274        return true;
6275    }
6276
6277    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6279        try {
6280            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6281        } finally {
6282            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6283        }
6284    }
6285
6286    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6287        final File[] files = dir.listFiles();
6288        if (ArrayUtils.isEmpty(files)) {
6289            Log.d(TAG, "No files in app dir " + dir);
6290            return;
6291        }
6292
6293        if (DEBUG_PACKAGE_SCANNING) {
6294            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6295                    + " flags=0x" + Integer.toHexString(parseFlags));
6296        }
6297
6298        for (File file : files) {
6299            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6300                    && !PackageInstallerService.isStageName(file.getName());
6301            if (!isPackage) {
6302                // Ignore entries which are not packages
6303                continue;
6304            }
6305            try {
6306                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6307                        scanFlags, currentTime, null);
6308            } catch (PackageManagerException e) {
6309                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6310
6311                // Delete invalid userdata apps
6312                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6313                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6314                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6315                    removeCodePathLI(file);
6316                }
6317            }
6318        }
6319    }
6320
6321    private static File getSettingsProblemFile() {
6322        File dataDir = Environment.getDataDirectory();
6323        File systemDir = new File(dataDir, "system");
6324        File fname = new File(systemDir, "uiderrors.txt");
6325        return fname;
6326    }
6327
6328    static void reportSettingsProblem(int priority, String msg) {
6329        logCriticalInfo(priority, msg);
6330    }
6331
6332    static void logCriticalInfo(int priority, String msg) {
6333        Slog.println(priority, TAG, msg);
6334        EventLogTags.writePmCriticalInfo(msg);
6335        try {
6336            File fname = getSettingsProblemFile();
6337            FileOutputStream out = new FileOutputStream(fname, true);
6338            PrintWriter pw = new FastPrintWriter(out);
6339            SimpleDateFormat formatter = new SimpleDateFormat();
6340            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6341            pw.println(dateString + ": " + msg);
6342            pw.close();
6343            FileUtils.setPermissions(
6344                    fname.toString(),
6345                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6346                    -1, -1);
6347        } catch (java.io.IOException e) {
6348        }
6349    }
6350
6351    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6352            int parseFlags) throws PackageManagerException {
6353        if (ps != null
6354                && ps.codePath.equals(srcFile)
6355                && ps.timeStamp == srcFile.lastModified()
6356                && !isCompatSignatureUpdateNeeded(pkg)
6357                && !isRecoverSignatureUpdateNeeded(pkg)) {
6358            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6359            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6360            ArraySet<PublicKey> signingKs;
6361            synchronized (mPackages) {
6362                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6363            }
6364            if (ps.signatures.mSignatures != null
6365                    && ps.signatures.mSignatures.length != 0
6366                    && signingKs != null) {
6367                // Optimization: reuse the existing cached certificates
6368                // if the package appears to be unchanged.
6369                pkg.mSignatures = ps.signatures.mSignatures;
6370                pkg.mSigningKeys = signingKs;
6371                return;
6372            }
6373
6374            Slog.w(TAG, "PackageSetting for " + ps.name
6375                    + " is missing signatures.  Collecting certs again to recover them.");
6376        } else {
6377            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6378        }
6379
6380        try {
6381            PackageParser.collectCertificates(pkg, parseFlags);
6382        } catch (PackageParserException e) {
6383            throw PackageManagerException.from(e);
6384        }
6385    }
6386
6387    /**
6388     *  Traces a package scan.
6389     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6390     */
6391    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6392            long currentTime, UserHandle user) throws PackageManagerException {
6393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6394        try {
6395            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6396        } finally {
6397            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6398        }
6399    }
6400
6401    /**
6402     *  Scans a package and returns the newly parsed package.
6403     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6404     */
6405    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6406            long currentTime, UserHandle user) throws PackageManagerException {
6407        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6408        parseFlags |= mDefParseFlags;
6409        PackageParser pp = new PackageParser();
6410        pp.setSeparateProcesses(mSeparateProcesses);
6411        pp.setOnlyCoreApps(mOnlyCore);
6412        pp.setDisplayMetrics(mMetrics);
6413
6414        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6415            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6416        }
6417
6418        final PackageParser.Package pkg;
6419        try {
6420            pkg = pp.parsePackage(scanFile, parseFlags);
6421        } catch (PackageParserException e) {
6422            throw PackageManagerException.from(e);
6423        }
6424
6425        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6426    }
6427
6428    /**
6429     *  Scans a package and returns the newly parsed package.
6430     *  @throws PackageManagerException on a parse error.
6431     */
6432    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6433            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6434            throws PackageManagerException {
6435        // If the package has children and this is the first dive in the function
6436        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6437        // packages (parent and children) would be successfully scanned before the
6438        // actual scan since scanning mutates internal state and we want to atomically
6439        // install the package and its children.
6440        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6441            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6442                scanFlags |= SCAN_CHECK_ONLY;
6443            }
6444        } else {
6445            scanFlags &= ~SCAN_CHECK_ONLY;
6446        }
6447
6448        // Scan the parent
6449        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6450                scanFlags, currentTime, user);
6451
6452        // Scan the children
6453        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6454        for (int i = 0; i < childCount; i++) {
6455            PackageParser.Package childPackage = pkg.childPackages.get(i);
6456            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6457                    currentTime, user);
6458        }
6459
6460
6461        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6462            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6463        }
6464
6465        return scannedPkg;
6466    }
6467
6468    /**
6469     *  Scans a package and returns the newly parsed package.
6470     *  @throws PackageManagerException on a parse error.
6471     */
6472    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6473            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6474            throws PackageManagerException {
6475        PackageSetting ps = null;
6476        PackageSetting updatedPkg;
6477        // reader
6478        synchronized (mPackages) {
6479            // Look to see if we already know about this package.
6480            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6481            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6482                // This package has been renamed to its original name.  Let's
6483                // use that.
6484                ps = mSettings.peekPackageLPr(oldName);
6485            }
6486            // If there was no original package, see one for the real package name.
6487            if (ps == null) {
6488                ps = mSettings.peekPackageLPr(pkg.packageName);
6489            }
6490            // Check to see if this package could be hiding/updating a system
6491            // package.  Must look for it either under the original or real
6492            // package name depending on our state.
6493            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6494            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6495
6496            // If this is a package we don't know about on the system partition, we
6497            // may need to remove disabled child packages on the system partition
6498            // or may need to not add child packages if the parent apk is updated
6499            // on the data partition and no longer defines this child package.
6500            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6501                // If this is a parent package for an updated system app and this system
6502                // app got an OTA update which no longer defines some of the child packages
6503                // we have to prune them from the disabled system packages.
6504                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6505                if (disabledPs != null) {
6506                    final int scannedChildCount = (pkg.childPackages != null)
6507                            ? pkg.childPackages.size() : 0;
6508                    final int disabledChildCount = disabledPs.childPackageNames != null
6509                            ? disabledPs.childPackageNames.size() : 0;
6510                    for (int i = 0; i < disabledChildCount; i++) {
6511                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6512                        boolean disabledPackageAvailable = false;
6513                        for (int j = 0; j < scannedChildCount; j++) {
6514                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6515                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6516                                disabledPackageAvailable = true;
6517                                break;
6518                            }
6519                         }
6520                         if (!disabledPackageAvailable) {
6521                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6522                         }
6523                    }
6524                }
6525            }
6526        }
6527
6528        boolean updatedPkgBetter = false;
6529        // First check if this is a system package that may involve an update
6530        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6531            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6532            // it needs to drop FLAG_PRIVILEGED.
6533            if (locationIsPrivileged(scanFile)) {
6534                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6535            } else {
6536                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6537            }
6538
6539            if (ps != null && !ps.codePath.equals(scanFile)) {
6540                // The path has changed from what was last scanned...  check the
6541                // version of the new path against what we have stored to determine
6542                // what to do.
6543                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6544                if (pkg.mVersionCode <= ps.versionCode) {
6545                    // The system package has been updated and the code path does not match
6546                    // Ignore entry. Skip it.
6547                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6548                            + " ignored: updated version " + ps.versionCode
6549                            + " better than this " + pkg.mVersionCode);
6550                    if (!updatedPkg.codePath.equals(scanFile)) {
6551                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6552                                + ps.name + " changing from " + updatedPkg.codePathString
6553                                + " to " + scanFile);
6554                        updatedPkg.codePath = scanFile;
6555                        updatedPkg.codePathString = scanFile.toString();
6556                        updatedPkg.resourcePath = scanFile;
6557                        updatedPkg.resourcePathString = scanFile.toString();
6558                    }
6559                    updatedPkg.pkg = pkg;
6560                    updatedPkg.versionCode = pkg.mVersionCode;
6561
6562                    // Update the disabled system child packages to point to the package too.
6563                    final int childCount = updatedPkg.childPackageNames != null
6564                            ? updatedPkg.childPackageNames.size() : 0;
6565                    for (int i = 0; i < childCount; i++) {
6566                        String childPackageName = updatedPkg.childPackageNames.get(i);
6567                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6568                                childPackageName);
6569                        if (updatedChildPkg != null) {
6570                            updatedChildPkg.pkg = pkg;
6571                            updatedChildPkg.versionCode = pkg.mVersionCode;
6572                        }
6573                    }
6574
6575                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6576                            + scanFile + " ignored: updated version " + ps.versionCode
6577                            + " better than this " + pkg.mVersionCode);
6578                } else {
6579                    // The current app on the system partition is better than
6580                    // what we have updated to on the data partition; switch
6581                    // back to the system partition version.
6582                    // At this point, its safely assumed that package installation for
6583                    // apps in system partition will go through. If not there won't be a working
6584                    // version of the app
6585                    // writer
6586                    synchronized (mPackages) {
6587                        // Just remove the loaded entries from package lists.
6588                        mPackages.remove(ps.name);
6589                    }
6590
6591                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6592                            + " reverting from " + ps.codePathString
6593                            + ": new version " + pkg.mVersionCode
6594                            + " better than installed " + ps.versionCode);
6595
6596                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6597                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6598                    synchronized (mInstallLock) {
6599                        args.cleanUpResourcesLI();
6600                    }
6601                    synchronized (mPackages) {
6602                        mSettings.enableSystemPackageLPw(ps.name);
6603                    }
6604                    updatedPkgBetter = true;
6605                }
6606            }
6607        }
6608
6609        if (updatedPkg != null) {
6610            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6611            // initially
6612            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6613
6614            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6615            // flag set initially
6616            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6617                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6618            }
6619        }
6620
6621        // Verify certificates against what was last scanned
6622        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6623
6624        /*
6625         * A new system app appeared, but we already had a non-system one of the
6626         * same name installed earlier.
6627         */
6628        boolean shouldHideSystemApp = false;
6629        if (updatedPkg == null && ps != null
6630                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6631            /*
6632             * Check to make sure the signatures match first. If they don't,
6633             * wipe the installed application and its data.
6634             */
6635            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6636                    != PackageManager.SIGNATURE_MATCH) {
6637                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6638                        + " signatures don't match existing userdata copy; removing");
6639                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6640                ps = null;
6641            } else {
6642                /*
6643                 * If the newly-added system app is an older version than the
6644                 * already installed version, hide it. It will be scanned later
6645                 * and re-added like an update.
6646                 */
6647                if (pkg.mVersionCode <= ps.versionCode) {
6648                    shouldHideSystemApp = true;
6649                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6650                            + " but new version " + pkg.mVersionCode + " better than installed "
6651                            + ps.versionCode + "; hiding system");
6652                } else {
6653                    /*
6654                     * The newly found system app is a newer version that the
6655                     * one previously installed. Simply remove the
6656                     * already-installed application and replace it with our own
6657                     * while keeping the application data.
6658                     */
6659                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6660                            + " reverting from " + ps.codePathString + ": new version "
6661                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6662                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6663                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6664                    synchronized (mInstallLock) {
6665                        args.cleanUpResourcesLI();
6666                    }
6667                }
6668            }
6669        }
6670
6671        // The apk is forward locked (not public) if its code and resources
6672        // are kept in different files. (except for app in either system or
6673        // vendor path).
6674        // TODO grab this value from PackageSettings
6675        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6676            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6677                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6678            }
6679        }
6680
6681        // TODO: extend to support forward-locked splits
6682        String resourcePath = null;
6683        String baseResourcePath = null;
6684        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6685            if (ps != null && ps.resourcePathString != null) {
6686                resourcePath = ps.resourcePathString;
6687                baseResourcePath = ps.resourcePathString;
6688            } else {
6689                // Should not happen at all. Just log an error.
6690                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6691            }
6692        } else {
6693            resourcePath = pkg.codePath;
6694            baseResourcePath = pkg.baseCodePath;
6695        }
6696
6697        // Set application objects path explicitly.
6698        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6699        pkg.setApplicationInfoCodePath(pkg.codePath);
6700        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6701        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6702        pkg.setApplicationInfoResourcePath(resourcePath);
6703        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6704        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6705
6706        // Note that we invoke the following method only if we are about to unpack an application
6707        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6708                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6709
6710        /*
6711         * If the system app should be overridden by a previously installed
6712         * data, hide the system app now and let the /data/app scan pick it up
6713         * again.
6714         */
6715        if (shouldHideSystemApp) {
6716            synchronized (mPackages) {
6717                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6718            }
6719        }
6720
6721        return scannedPkg;
6722    }
6723
6724    private static String fixProcessName(String defProcessName,
6725            String processName, int uid) {
6726        if (processName == null) {
6727            return defProcessName;
6728        }
6729        return processName;
6730    }
6731
6732    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6733            throws PackageManagerException {
6734        if (pkgSetting.signatures.mSignatures != null) {
6735            // Already existing package. Make sure signatures match
6736            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6737                    == PackageManager.SIGNATURE_MATCH;
6738            if (!match) {
6739                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6740                        == PackageManager.SIGNATURE_MATCH;
6741            }
6742            if (!match) {
6743                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6744                        == PackageManager.SIGNATURE_MATCH;
6745            }
6746            if (!match) {
6747                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6748                        + pkg.packageName + " signatures do not match the "
6749                        + "previously installed version; ignoring!");
6750            }
6751        }
6752
6753        // Check for shared user signatures
6754        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6755            // Already existing package. Make sure signatures match
6756            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6757                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6758            if (!match) {
6759                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6760                        == PackageManager.SIGNATURE_MATCH;
6761            }
6762            if (!match) {
6763                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6764                        == PackageManager.SIGNATURE_MATCH;
6765            }
6766            if (!match) {
6767                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6768                        "Package " + pkg.packageName
6769                        + " has no signatures that match those in shared user "
6770                        + pkgSetting.sharedUser.name + "; ignoring!");
6771            }
6772        }
6773    }
6774
6775    /**
6776     * Enforces that only the system UID or root's UID can call a method exposed
6777     * via Binder.
6778     *
6779     * @param message used as message if SecurityException is thrown
6780     * @throws SecurityException if the caller is not system or root
6781     */
6782    private static final void enforceSystemOrRoot(String message) {
6783        final int uid = Binder.getCallingUid();
6784        if (uid != Process.SYSTEM_UID && uid != 0) {
6785            throw new SecurityException(message);
6786        }
6787    }
6788
6789    @Override
6790    public void performFstrimIfNeeded() {
6791        enforceSystemOrRoot("Only the system can request fstrim");
6792
6793        // Before everything else, see whether we need to fstrim.
6794        try {
6795            IMountService ms = PackageHelper.getMountService();
6796            if (ms != null) {
6797                final boolean isUpgrade = isUpgrade();
6798                boolean doTrim = isUpgrade;
6799                if (doTrim) {
6800                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6801                } else {
6802                    final long interval = android.provider.Settings.Global.getLong(
6803                            mContext.getContentResolver(),
6804                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6805                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6806                    if (interval > 0) {
6807                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6808                        if (timeSinceLast > interval) {
6809                            doTrim = true;
6810                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6811                                    + "; running immediately");
6812                        }
6813                    }
6814                }
6815                if (doTrim) {
6816                    if (!isFirstBoot()) {
6817                        try {
6818                            ActivityManagerNative.getDefault().showBootMessage(
6819                                    mContext.getResources().getString(
6820                                            R.string.android_upgrading_fstrim), true);
6821                        } catch (RemoteException e) {
6822                        }
6823                    }
6824                    ms.runMaintenance();
6825                }
6826            } else {
6827                Slog.e(TAG, "Mount service unavailable!");
6828            }
6829        } catch (RemoteException e) {
6830            // Can't happen; MountService is local
6831        }
6832    }
6833
6834    @Override
6835    public void extractPackagesIfNeeded() {
6836        enforceSystemOrRoot("Only the system can request package extraction");
6837
6838        // Extract pacakges only if profile-guided compilation is enabled because
6839        // otherwise BackgroundDexOptService will not dexopt them later.
6840        if (!isUpgrade()) {
6841            return;
6842        }
6843
6844        List<PackageParser.Package> pkgs;
6845        synchronized (mPackages) {
6846            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6847        }
6848
6849        int curr = 0;
6850        int total = pkgs.size();
6851        for (PackageParser.Package pkg : pkgs) {
6852            curr++;
6853
6854            if (DEBUG_DEXOPT) {
6855                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6856            }
6857
6858            if (!isFirstBoot()) {
6859                try {
6860                    ActivityManagerNative.getDefault().showBootMessage(
6861                            mContext.getResources().getString(R.string.android_upgrading_apk,
6862                                    curr, total), true);
6863                } catch (RemoteException e) {
6864                }
6865            }
6866
6867            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6868                performDexOpt(pkg.packageName, null /* instructionSet */,
6869                         false /* useProfiles */, true /* extractOnly */, false /* force */);
6870            }
6871        }
6872    }
6873
6874    @Override
6875    public void notifyPackageUse(String packageName) {
6876        synchronized (mPackages) {
6877            PackageParser.Package p = mPackages.get(packageName);
6878            if (p == null) {
6879                return;
6880            }
6881            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6882        }
6883    }
6884
6885    // TODO: this is not used nor needed. Delete it.
6886    @Override
6887    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6888        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6889                false /* extractOnly */, false /* force */);
6890    }
6891
6892    @Override
6893    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6894            boolean extractOnly, boolean force) {
6895        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6896    }
6897
6898    private boolean performDexOptTraced(String packageName, String instructionSet,
6899                boolean useProfiles, boolean extractOnly, boolean force) {
6900        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6901        try {
6902            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6903                    force);
6904        } finally {
6905            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6906        }
6907    }
6908
6909    private boolean performDexOptInternal(String packageName, String instructionSet,
6910                boolean useProfiles, boolean extractOnly, boolean force) {
6911        PackageParser.Package p;
6912        final String targetInstructionSet;
6913        synchronized (mPackages) {
6914            p = mPackages.get(packageName);
6915            if (p == null) {
6916                return false;
6917            }
6918            mPackageUsage.write(false);
6919
6920            targetInstructionSet = instructionSet != null ? instructionSet :
6921                    getPrimaryInstructionSet(p.applicationInfo);
6922        }
6923        long callingId = Binder.clearCallingIdentity();
6924        try {
6925            synchronized (mInstallLock) {
6926                final String[] instructionSets = new String[] { targetInstructionSet };
6927                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6928                        useProfiles, extractOnly, force);
6929                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6930            }
6931        } finally {
6932            Binder.restoreCallingIdentity(callingId);
6933        }
6934    }
6935
6936    public ArraySet<String> getOptimizablePackages() {
6937        ArraySet<String> pkgs = new ArraySet<String>();
6938        synchronized (mPackages) {
6939            for (PackageParser.Package p : mPackages.values()) {
6940                if (PackageDexOptimizer.canOptimizePackage(p)) {
6941                    pkgs.add(p.packageName);
6942                }
6943            }
6944        }
6945        return pkgs;
6946    }
6947
6948    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6949            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6950        // Select the dex optimizer based on the force parameter.
6951        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6952        //       allocate an object here.
6953        PackageDexOptimizer pdo = force
6954                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6955                : mPackageDexOptimizer;
6956
6957        // Optimize all dependencies first. Note: we ignore the return value and march on
6958        // on errors.
6959        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6960        if (!deps.isEmpty()) {
6961            for (PackageParser.Package depPackage : deps) {
6962                // TODO: Analyze and investigate if we (should) profile libraries.
6963                // Currently this will do a full compilation of the library.
6964                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6965                        false /* extractOnly */);
6966            }
6967        }
6968
6969        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6970    }
6971
6972    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6973        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6974            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6975            Set<String> collectedNames = new HashSet<>();
6976            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6977
6978            retValue.remove(p);
6979
6980            return retValue;
6981        } else {
6982            return Collections.emptyList();
6983        }
6984    }
6985
6986    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6987            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6988        if (!collectedNames.contains(p.packageName)) {
6989            collectedNames.add(p.packageName);
6990            collected.add(p);
6991
6992            if (p.usesLibraries != null) {
6993                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6994            }
6995            if (p.usesOptionalLibraries != null) {
6996                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6997                        collectedNames);
6998            }
6999        }
7000    }
7001
7002    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7003            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7004        for (String libName : libs) {
7005            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7006            if (libPkg != null) {
7007                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7008            }
7009        }
7010    }
7011
7012    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7013        synchronized (mPackages) {
7014            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7015            if (lib != null && lib.apk != null) {
7016                return mPackages.get(lib.apk);
7017            }
7018        }
7019        return null;
7020    }
7021
7022    public void shutdown() {
7023        mPackageUsage.write(true);
7024    }
7025
7026    @Override
7027    public void forceDexOpt(String packageName) {
7028        enforceSystemOrRoot("forceDexOpt");
7029
7030        PackageParser.Package pkg;
7031        synchronized (mPackages) {
7032            pkg = mPackages.get(packageName);
7033            if (pkg == null) {
7034                throw new IllegalArgumentException("Unknown package: " + packageName);
7035            }
7036        }
7037
7038        synchronized (mInstallLock) {
7039            final String[] instructionSets = new String[] {
7040                    getPrimaryInstructionSet(pkg.applicationInfo) };
7041
7042            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7043
7044            // Whoever is calling forceDexOpt wants a fully compiled package.
7045            // Don't use profiles since that may cause compilation to be skipped.
7046            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7047                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7048
7049            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7050            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7051                throw new IllegalStateException("Failed to dexopt: " + res);
7052            }
7053        }
7054    }
7055
7056    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7057        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7058            Slog.w(TAG, "Unable to update from " + oldPkg.name
7059                    + " to " + newPkg.packageName
7060                    + ": old package not in system partition");
7061            return false;
7062        } else if (mPackages.get(oldPkg.name) != null) {
7063            Slog.w(TAG, "Unable to update from " + oldPkg.name
7064                    + " to " + newPkg.packageName
7065                    + ": old package still exists");
7066            return false;
7067        }
7068        return true;
7069    }
7070
7071    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7072        // TODO: triage flags as part of 26466827
7073        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7074
7075        boolean res = true;
7076        final int[] users = sUserManager.getUserIds();
7077        for (int user : users) {
7078            try {
7079                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7080            } catch (InstallerException e) {
7081                Slog.w(TAG, "Failed to delete data directory", e);
7082                res = false;
7083            }
7084        }
7085        return res;
7086    }
7087
7088    void removeCodePathLI(File codePath) {
7089        if (codePath.isDirectory()) {
7090            try {
7091                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7092            } catch (InstallerException e) {
7093                Slog.w(TAG, "Failed to remove code path", e);
7094            }
7095        } else {
7096            codePath.delete();
7097        }
7098    }
7099
7100    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7101        try {
7102            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7103        } catch (InstallerException e) {
7104            Slog.w(TAG, "Failed to destroy app data", e);
7105        }
7106    }
7107
7108    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7109            int appId, String seinfo) {
7110        try {
7111            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7112        } catch (InstallerException e) {
7113            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7114        }
7115    }
7116
7117    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7118        final PackageParser.Package pkg;
7119        synchronized (mPackages) {
7120            pkg = mPackages.get(packageName);
7121        }
7122        if (pkg == null) {
7123            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7124            return;
7125        }
7126        deleteCodeCacheDirsLI(pkg);
7127    }
7128
7129    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7130        // TODO: triage flags as part of 26466827
7131        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7132
7133        int[] users = sUserManager.getUserIds();
7134        int res = 0;
7135        for (int user : users) {
7136            // Remove the parent code cache
7137            try {
7138                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7139                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7140            } catch (InstallerException e) {
7141                Slog.w(TAG, "Failed to delete code cache directory", e);
7142            }
7143            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7144            for (int i = 0; i < childCount; i++) {
7145                PackageParser.Package childPkg = pkg.childPackages.get(i);
7146                // Remove the child code cache
7147                try {
7148                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7149                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7150                } catch (InstallerException e) {
7151                    Slog.w(TAG, "Failed to delete code cache directory", e);
7152                }
7153            }
7154        }
7155    }
7156
7157    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7158            long lastUpdateTime) {
7159        // Set parent install/update time
7160        PackageSetting ps = (PackageSetting) pkg.mExtras;
7161        if (ps != null) {
7162            ps.firstInstallTime = firstInstallTime;
7163            ps.lastUpdateTime = lastUpdateTime;
7164        }
7165        // Set children install/update time
7166        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7167        for (int i = 0; i < childCount; i++) {
7168            PackageParser.Package childPkg = pkg.childPackages.get(i);
7169            ps = (PackageSetting) childPkg.mExtras;
7170            if (ps != null) {
7171                ps.firstInstallTime = firstInstallTime;
7172                ps.lastUpdateTime = lastUpdateTime;
7173            }
7174        }
7175    }
7176
7177    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7178            PackageParser.Package changingLib) {
7179        if (file.path != null) {
7180            usesLibraryFiles.add(file.path);
7181            return;
7182        }
7183        PackageParser.Package p = mPackages.get(file.apk);
7184        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7185            // If we are doing this while in the middle of updating a library apk,
7186            // then we need to make sure to use that new apk for determining the
7187            // dependencies here.  (We haven't yet finished committing the new apk
7188            // to the package manager state.)
7189            if (p == null || p.packageName.equals(changingLib.packageName)) {
7190                p = changingLib;
7191            }
7192        }
7193        if (p != null) {
7194            usesLibraryFiles.addAll(p.getAllCodePaths());
7195        }
7196    }
7197
7198    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7199            PackageParser.Package changingLib) throws PackageManagerException {
7200        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7201            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7202            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7203            for (int i=0; i<N; i++) {
7204                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7205                if (file == null) {
7206                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7207                            "Package " + pkg.packageName + " requires unavailable shared library "
7208                            + pkg.usesLibraries.get(i) + "; failing!");
7209                }
7210                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7211            }
7212            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7213            for (int i=0; i<N; i++) {
7214                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7215                if (file == null) {
7216                    Slog.w(TAG, "Package " + pkg.packageName
7217                            + " desires unavailable shared library "
7218                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7219                } else {
7220                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7221                }
7222            }
7223            N = usesLibraryFiles.size();
7224            if (N > 0) {
7225                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7226            } else {
7227                pkg.usesLibraryFiles = null;
7228            }
7229        }
7230    }
7231
7232    private static boolean hasString(List<String> list, List<String> which) {
7233        if (list == null) {
7234            return false;
7235        }
7236        for (int i=list.size()-1; i>=0; i--) {
7237            for (int j=which.size()-1; j>=0; j--) {
7238                if (which.get(j).equals(list.get(i))) {
7239                    return true;
7240                }
7241            }
7242        }
7243        return false;
7244    }
7245
7246    private void updateAllSharedLibrariesLPw() {
7247        for (PackageParser.Package pkg : mPackages.values()) {
7248            try {
7249                updateSharedLibrariesLPw(pkg, null);
7250            } catch (PackageManagerException e) {
7251                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7252            }
7253        }
7254    }
7255
7256    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7257            PackageParser.Package changingPkg) {
7258        ArrayList<PackageParser.Package> res = null;
7259        for (PackageParser.Package pkg : mPackages.values()) {
7260            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7261                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7262                if (res == null) {
7263                    res = new ArrayList<PackageParser.Package>();
7264                }
7265                res.add(pkg);
7266                try {
7267                    updateSharedLibrariesLPw(pkg, changingPkg);
7268                } catch (PackageManagerException e) {
7269                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7270                }
7271            }
7272        }
7273        return res;
7274    }
7275
7276    /**
7277     * Derive the value of the {@code cpuAbiOverride} based on the provided
7278     * value and an optional stored value from the package settings.
7279     */
7280    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7281        String cpuAbiOverride = null;
7282
7283        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7284            cpuAbiOverride = null;
7285        } else if (abiOverride != null) {
7286            cpuAbiOverride = abiOverride;
7287        } else if (settings != null) {
7288            cpuAbiOverride = settings.cpuAbiOverrideString;
7289        }
7290
7291        return cpuAbiOverride;
7292    }
7293
7294    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7295            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7296        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7297        // If the package has children and this is the first dive in the function
7298        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7299        // whether all packages (parent and children) would be successfully scanned
7300        // before the actual scan since scanning mutates internal state and we want
7301        // to atomically install the package and its children.
7302        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7303            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7304                scanFlags |= SCAN_CHECK_ONLY;
7305            }
7306        } else {
7307            scanFlags &= ~SCAN_CHECK_ONLY;
7308        }
7309
7310        final PackageParser.Package scannedPkg;
7311        try {
7312            // Scan the parent
7313            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7314            // Scan the children
7315            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7316            for (int i = 0; i < childCount; i++) {
7317                PackageParser.Package childPkg = pkg.childPackages.get(i);
7318                scanPackageLI(childPkg, parseFlags,
7319                        scanFlags, currentTime, user);
7320            }
7321        } finally {
7322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7323        }
7324
7325        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7326            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7327        }
7328
7329        return scannedPkg;
7330    }
7331
7332    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7333            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7334        boolean success = false;
7335        try {
7336            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7337                    currentTime, user);
7338            success = true;
7339            return res;
7340        } finally {
7341            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7342                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7343            }
7344        }
7345    }
7346
7347    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7348            int scanFlags, long currentTime, UserHandle user)
7349            throws PackageManagerException {
7350        final File scanFile = new File(pkg.codePath);
7351        if (pkg.applicationInfo.getCodePath() == null ||
7352                pkg.applicationInfo.getResourcePath() == null) {
7353            // Bail out. The resource and code paths haven't been set.
7354            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7355                    "Code and resource paths haven't been set correctly");
7356        }
7357
7358        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7359            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7360        } else {
7361            // Only allow system apps to be flagged as core apps.
7362            pkg.coreApp = false;
7363        }
7364
7365        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7366            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7367        }
7368
7369        if (mCustomResolverComponentName != null &&
7370                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7371            setUpCustomResolverActivity(pkg);
7372        }
7373
7374        if (pkg.packageName.equals("android")) {
7375            synchronized (mPackages) {
7376                if (mAndroidApplication != null) {
7377                    Slog.w(TAG, "*************************************************");
7378                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7379                    Slog.w(TAG, " file=" + scanFile);
7380                    Slog.w(TAG, "*************************************************");
7381                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7382                            "Core android package being redefined.  Skipping.");
7383                }
7384
7385                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7386                    // Set up information for our fall-back user intent resolution activity.
7387                    mPlatformPackage = pkg;
7388                    pkg.mVersionCode = mSdkVersion;
7389                    mAndroidApplication = pkg.applicationInfo;
7390
7391                    if (!mResolverReplaced) {
7392                        mResolveActivity.applicationInfo = mAndroidApplication;
7393                        mResolveActivity.name = ResolverActivity.class.getName();
7394                        mResolveActivity.packageName = mAndroidApplication.packageName;
7395                        mResolveActivity.processName = "system:ui";
7396                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7397                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7398                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7399                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7400                        mResolveActivity.exported = true;
7401                        mResolveActivity.enabled = true;
7402                        mResolveInfo.activityInfo = mResolveActivity;
7403                        mResolveInfo.priority = 0;
7404                        mResolveInfo.preferredOrder = 0;
7405                        mResolveInfo.match = 0;
7406                        mResolveComponentName = new ComponentName(
7407                                mAndroidApplication.packageName, mResolveActivity.name);
7408                    }
7409                }
7410            }
7411        }
7412
7413        if (DEBUG_PACKAGE_SCANNING) {
7414            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7415                Log.d(TAG, "Scanning package " + pkg.packageName);
7416        }
7417
7418        synchronized (mPackages) {
7419            if (mPackages.containsKey(pkg.packageName)
7420                    || mSharedLibraries.containsKey(pkg.packageName)) {
7421                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7422                        "Application package " + pkg.packageName
7423                                + " already installed.  Skipping duplicate.");
7424            }
7425
7426            // If we're only installing presumed-existing packages, require that the
7427            // scanned APK is both already known and at the path previously established
7428            // for it.  Previously unknown packages we pick up normally, but if we have an
7429            // a priori expectation about this package's install presence, enforce it.
7430            // With a singular exception for new system packages. When an OTA contains
7431            // a new system package, we allow the codepath to change from a system location
7432            // to the user-installed location. If we don't allow this change, any newer,
7433            // user-installed version of the application will be ignored.
7434            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7435                if (mExpectingBetter.containsKey(pkg.packageName)) {
7436                    logCriticalInfo(Log.WARN,
7437                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7438                } else {
7439                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7440                    if (known != null) {
7441                        if (DEBUG_PACKAGE_SCANNING) {
7442                            Log.d(TAG, "Examining " + pkg.codePath
7443                                    + " and requiring known paths " + known.codePathString
7444                                    + " & " + known.resourcePathString);
7445                        }
7446                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7447                                || !pkg.applicationInfo.getResourcePath().equals(
7448                                known.resourcePathString)) {
7449                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7450                                    "Application package " + pkg.packageName
7451                                            + " found at " + pkg.applicationInfo.getCodePath()
7452                                            + " but expected at " + known.codePathString
7453                                            + "; ignoring.");
7454                        }
7455                    }
7456                }
7457            }
7458        }
7459
7460        // Initialize package source and resource directories
7461        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7462        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7463
7464        SharedUserSetting suid = null;
7465        PackageSetting pkgSetting = null;
7466
7467        if (!isSystemApp(pkg)) {
7468            // Only system apps can use these features.
7469            pkg.mOriginalPackages = null;
7470            pkg.mRealPackage = null;
7471            pkg.mAdoptPermissions = null;
7472        }
7473
7474        // Getting the package setting may have a side-effect, so if we
7475        // are only checking if scan would succeed, stash a copy of the
7476        // old setting to restore at the end.
7477        PackageSetting nonMutatedPs = null;
7478
7479        // writer
7480        synchronized (mPackages) {
7481            if (pkg.mSharedUserId != null) {
7482                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7483                if (suid == null) {
7484                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7485                            "Creating application package " + pkg.packageName
7486                            + " for shared user failed");
7487                }
7488                if (DEBUG_PACKAGE_SCANNING) {
7489                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7490                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7491                                + "): packages=" + suid.packages);
7492                }
7493            }
7494
7495            // Check if we are renaming from an original package name.
7496            PackageSetting origPackage = null;
7497            String realName = null;
7498            if (pkg.mOriginalPackages != null) {
7499                // This package may need to be renamed to a previously
7500                // installed name.  Let's check on that...
7501                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7502                if (pkg.mOriginalPackages.contains(renamed)) {
7503                    // This package had originally been installed as the
7504                    // original name, and we have already taken care of
7505                    // transitioning to the new one.  Just update the new
7506                    // one to continue using the old name.
7507                    realName = pkg.mRealPackage;
7508                    if (!pkg.packageName.equals(renamed)) {
7509                        // Callers into this function may have already taken
7510                        // care of renaming the package; only do it here if
7511                        // it is not already done.
7512                        pkg.setPackageName(renamed);
7513                    }
7514
7515                } else {
7516                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7517                        if ((origPackage = mSettings.peekPackageLPr(
7518                                pkg.mOriginalPackages.get(i))) != null) {
7519                            // We do have the package already installed under its
7520                            // original name...  should we use it?
7521                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7522                                // New package is not compatible with original.
7523                                origPackage = null;
7524                                continue;
7525                            } else if (origPackage.sharedUser != null) {
7526                                // Make sure uid is compatible between packages.
7527                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7528                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7529                                            + " to " + pkg.packageName + ": old uid "
7530                                            + origPackage.sharedUser.name
7531                                            + " differs from " + pkg.mSharedUserId);
7532                                    origPackage = null;
7533                                    continue;
7534                                }
7535                            } else {
7536                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7537                                        + pkg.packageName + " to old name " + origPackage.name);
7538                            }
7539                            break;
7540                        }
7541                    }
7542                }
7543            }
7544
7545            if (mTransferedPackages.contains(pkg.packageName)) {
7546                Slog.w(TAG, "Package " + pkg.packageName
7547                        + " was transferred to another, but its .apk remains");
7548            }
7549
7550            // See comments in nonMutatedPs declaration
7551            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7552                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7553                if (foundPs != null) {
7554                    nonMutatedPs = new PackageSetting(foundPs);
7555                }
7556            }
7557
7558            // Just create the setting, don't add it yet. For already existing packages
7559            // the PkgSetting exists already and doesn't have to be created.
7560            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7561                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7562                    pkg.applicationInfo.primaryCpuAbi,
7563                    pkg.applicationInfo.secondaryCpuAbi,
7564                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7565                    user, false);
7566            if (pkgSetting == null) {
7567                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7568                        "Creating application package " + pkg.packageName + " failed");
7569            }
7570
7571            if (pkgSetting.origPackage != null) {
7572                // If we are first transitioning from an original package,
7573                // fix up the new package's name now.  We need to do this after
7574                // looking up the package under its new name, so getPackageLP
7575                // can take care of fiddling things correctly.
7576                pkg.setPackageName(origPackage.name);
7577
7578                // File a report about this.
7579                String msg = "New package " + pkgSetting.realName
7580                        + " renamed to replace old package " + pkgSetting.name;
7581                reportSettingsProblem(Log.WARN, msg);
7582
7583                // Make a note of it.
7584                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7585                    mTransferedPackages.add(origPackage.name);
7586                }
7587
7588                // No longer need to retain this.
7589                pkgSetting.origPackage = null;
7590            }
7591
7592            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7593                // Make a note of it.
7594                mTransferedPackages.add(pkg.packageName);
7595            }
7596
7597            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7598                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7599            }
7600
7601            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7602                // Check all shared libraries and map to their actual file path.
7603                // We only do this here for apps not on a system dir, because those
7604                // are the only ones that can fail an install due to this.  We
7605                // will take care of the system apps by updating all of their
7606                // library paths after the scan is done.
7607                updateSharedLibrariesLPw(pkg, null);
7608            }
7609
7610            if (mFoundPolicyFile) {
7611                SELinuxMMAC.assignSeinfoValue(pkg);
7612            }
7613
7614            pkg.applicationInfo.uid = pkgSetting.appId;
7615            pkg.mExtras = pkgSetting;
7616            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7617                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7618                    // We just determined the app is signed correctly, so bring
7619                    // over the latest parsed certs.
7620                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7621                } else {
7622                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7623                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7624                                "Package " + pkg.packageName + " upgrade keys do not match the "
7625                                + "previously installed version");
7626                    } else {
7627                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7628                        String msg = "System package " + pkg.packageName
7629                            + " signature changed; retaining data.";
7630                        reportSettingsProblem(Log.WARN, msg);
7631                    }
7632                }
7633            } else {
7634                try {
7635                    verifySignaturesLP(pkgSetting, pkg);
7636                    // We just determined the app is signed correctly, so bring
7637                    // over the latest parsed certs.
7638                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7639                } catch (PackageManagerException e) {
7640                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7641                        throw e;
7642                    }
7643                    // The signature has changed, but this package is in the system
7644                    // image...  let's recover!
7645                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7646                    // However...  if this package is part of a shared user, but it
7647                    // doesn't match the signature of the shared user, let's fail.
7648                    // What this means is that you can't change the signatures
7649                    // associated with an overall shared user, which doesn't seem all
7650                    // that unreasonable.
7651                    if (pkgSetting.sharedUser != null) {
7652                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7653                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7654                            throw new PackageManagerException(
7655                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7656                                            "Signature mismatch for shared user: "
7657                                            + pkgSetting.sharedUser);
7658                        }
7659                    }
7660                    // File a report about this.
7661                    String msg = "System package " + pkg.packageName
7662                        + " signature changed; retaining data.";
7663                    reportSettingsProblem(Log.WARN, msg);
7664                }
7665            }
7666            // Verify that this new package doesn't have any content providers
7667            // that conflict with existing packages.  Only do this if the
7668            // package isn't already installed, since we don't want to break
7669            // things that are installed.
7670            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7671                final int N = pkg.providers.size();
7672                int i;
7673                for (i=0; i<N; i++) {
7674                    PackageParser.Provider p = pkg.providers.get(i);
7675                    if (p.info.authority != null) {
7676                        String names[] = p.info.authority.split(";");
7677                        for (int j = 0; j < names.length; j++) {
7678                            if (mProvidersByAuthority.containsKey(names[j])) {
7679                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7680                                final String otherPackageName =
7681                                        ((other != null && other.getComponentName() != null) ?
7682                                                other.getComponentName().getPackageName() : "?");
7683                                throw new PackageManagerException(
7684                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7685                                                "Can't install because provider name " + names[j]
7686                                                + " (in package " + pkg.applicationInfo.packageName
7687                                                + ") is already used by " + otherPackageName);
7688                            }
7689                        }
7690                    }
7691                }
7692            }
7693
7694            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7695                // This package wants to adopt ownership of permissions from
7696                // another package.
7697                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7698                    final String origName = pkg.mAdoptPermissions.get(i);
7699                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7700                    if (orig != null) {
7701                        if (verifyPackageUpdateLPr(orig, pkg)) {
7702                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7703                                    + pkg.packageName);
7704                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7705                        }
7706                    }
7707                }
7708            }
7709        }
7710
7711        final String pkgName = pkg.packageName;
7712
7713        final long scanFileTime = scanFile.lastModified();
7714        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7715        pkg.applicationInfo.processName = fixProcessName(
7716                pkg.applicationInfo.packageName,
7717                pkg.applicationInfo.processName,
7718                pkg.applicationInfo.uid);
7719
7720        if (pkg != mPlatformPackage) {
7721            // Get all of our default paths setup
7722            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7723        }
7724
7725        final String path = scanFile.getPath();
7726        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7727
7728        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7729            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7730
7731            // Some system apps still use directory structure for native libraries
7732            // in which case we might end up not detecting abi solely based on apk
7733            // structure. Try to detect abi based on directory structure.
7734            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7735                    pkg.applicationInfo.primaryCpuAbi == null) {
7736                setBundledAppAbisAndRoots(pkg, pkgSetting);
7737                setNativeLibraryPaths(pkg);
7738            }
7739
7740        } else {
7741            if ((scanFlags & SCAN_MOVE) != 0) {
7742                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7743                // but we already have this packages package info in the PackageSetting. We just
7744                // use that and derive the native library path based on the new codepath.
7745                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7746                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7747            }
7748
7749            // Set native library paths again. For moves, the path will be updated based on the
7750            // ABIs we've determined above. For non-moves, the path will be updated based on the
7751            // ABIs we determined during compilation, but the path will depend on the final
7752            // package path (after the rename away from the stage path).
7753            setNativeLibraryPaths(pkg);
7754        }
7755
7756        // This is a special case for the "system" package, where the ABI is
7757        // dictated by the zygote configuration (and init.rc). We should keep track
7758        // of this ABI so that we can deal with "normal" applications that run under
7759        // the same UID correctly.
7760        if (mPlatformPackage == pkg) {
7761            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7762                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7763        }
7764
7765        // If there's a mismatch between the abi-override in the package setting
7766        // and the abiOverride specified for the install. Warn about this because we
7767        // would've already compiled the app without taking the package setting into
7768        // account.
7769        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7770            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7771                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7772                        " for package " + pkg.packageName);
7773            }
7774        }
7775
7776        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7777        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7778        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7779
7780        // Copy the derived override back to the parsed package, so that we can
7781        // update the package settings accordingly.
7782        pkg.cpuAbiOverride = cpuAbiOverride;
7783
7784        if (DEBUG_ABI_SELECTION) {
7785            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7786                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7787                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7788        }
7789
7790        // Push the derived path down into PackageSettings so we know what to
7791        // clean up at uninstall time.
7792        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7793
7794        if (DEBUG_ABI_SELECTION) {
7795            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7796                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7797                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7798        }
7799
7800        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7801            // We don't do this here during boot because we can do it all
7802            // at once after scanning all existing packages.
7803            //
7804            // We also do this *before* we perform dexopt on this package, so that
7805            // we can avoid redundant dexopts, and also to make sure we've got the
7806            // code and package path correct.
7807            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7808                    pkg, true /* boot complete */);
7809        }
7810
7811        if (mFactoryTest && pkg.requestedPermissions.contains(
7812                android.Manifest.permission.FACTORY_TEST)) {
7813            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7814        }
7815
7816        ArrayList<PackageParser.Package> clientLibPkgs = null;
7817
7818        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7819            if (nonMutatedPs != null) {
7820                synchronized (mPackages) {
7821                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7822                }
7823            }
7824            return pkg;
7825        }
7826
7827        // Only privileged apps and updated privileged apps can add child packages.
7828        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7829            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7830                throw new PackageManagerException("Only privileged apps and updated "
7831                        + "privileged apps can add child packages. Ignoring package "
7832                        + pkg.packageName);
7833            }
7834            final int childCount = pkg.childPackages.size();
7835            for (int i = 0; i < childCount; i++) {
7836                PackageParser.Package childPkg = pkg.childPackages.get(i);
7837                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7838                        childPkg.packageName)) {
7839                    throw new PackageManagerException("Cannot override a child package of "
7840                            + "another disabled system app. Ignoring package " + pkg.packageName);
7841                }
7842            }
7843        }
7844
7845        // writer
7846        synchronized (mPackages) {
7847            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7848                // Only system apps can add new shared libraries.
7849                if (pkg.libraryNames != null) {
7850                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7851                        String name = pkg.libraryNames.get(i);
7852                        boolean allowed = false;
7853                        if (pkg.isUpdatedSystemApp()) {
7854                            // New library entries can only be added through the
7855                            // system image.  This is important to get rid of a lot
7856                            // of nasty edge cases: for example if we allowed a non-
7857                            // system update of the app to add a library, then uninstalling
7858                            // the update would make the library go away, and assumptions
7859                            // we made such as through app install filtering would now
7860                            // have allowed apps on the device which aren't compatible
7861                            // with it.  Better to just have the restriction here, be
7862                            // conservative, and create many fewer cases that can negatively
7863                            // impact the user experience.
7864                            final PackageSetting sysPs = mSettings
7865                                    .getDisabledSystemPkgLPr(pkg.packageName);
7866                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7867                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7868                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7869                                        allowed = true;
7870                                        break;
7871                                    }
7872                                }
7873                            }
7874                        } else {
7875                            allowed = true;
7876                        }
7877                        if (allowed) {
7878                            if (!mSharedLibraries.containsKey(name)) {
7879                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7880                            } else if (!name.equals(pkg.packageName)) {
7881                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7882                                        + name + " already exists; skipping");
7883                            }
7884                        } else {
7885                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7886                                    + name + " that is not declared on system image; skipping");
7887                        }
7888                    }
7889                    if ((scanFlags & SCAN_BOOTING) == 0) {
7890                        // If we are not booting, we need to update any applications
7891                        // that are clients of our shared library.  If we are booting,
7892                        // this will all be done once the scan is complete.
7893                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7894                    }
7895                }
7896            }
7897        }
7898
7899        // Request the ActivityManager to kill the process(only for existing packages)
7900        // so that we do not end up in a confused state while the user is still using the older
7901        // version of the application while the new one gets installed.
7902        if ((scanFlags & SCAN_REPLACING) != 0) {
7903            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7904
7905            killApplication(pkg.applicationInfo.packageName,
7906                        pkg.applicationInfo.uid, "replace pkg");
7907
7908            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7909        }
7910
7911        // Also need to kill any apps that are dependent on the library.
7912        if (clientLibPkgs != null) {
7913            for (int i=0; i<clientLibPkgs.size(); i++) {
7914                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7915                killApplication(clientPkg.applicationInfo.packageName,
7916                        clientPkg.applicationInfo.uid, "update lib");
7917            }
7918        }
7919
7920        // Make sure we're not adding any bogus keyset info
7921        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7922        ksms.assertScannedPackageValid(pkg);
7923
7924        // writer
7925        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7926
7927        boolean createIdmapFailed = false;
7928        synchronized (mPackages) {
7929            // We don't expect installation to fail beyond this point
7930
7931            // Add the new setting to mSettings
7932            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7933            // Add the new setting to mPackages
7934            mPackages.put(pkg.applicationInfo.packageName, pkg);
7935            // Make sure we don't accidentally delete its data.
7936            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7937            while (iter.hasNext()) {
7938                PackageCleanItem item = iter.next();
7939                if (pkgName.equals(item.packageName)) {
7940                    iter.remove();
7941                }
7942            }
7943
7944            // Take care of first install / last update times.
7945            if (currentTime != 0) {
7946                if (pkgSetting.firstInstallTime == 0) {
7947                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7948                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7949                    pkgSetting.lastUpdateTime = currentTime;
7950                }
7951            } else if (pkgSetting.firstInstallTime == 0) {
7952                // We need *something*.  Take time time stamp of the file.
7953                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7954            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7955                if (scanFileTime != pkgSetting.timeStamp) {
7956                    // A package on the system image has changed; consider this
7957                    // to be an update.
7958                    pkgSetting.lastUpdateTime = scanFileTime;
7959                }
7960            }
7961
7962            // Add the package's KeySets to the global KeySetManagerService
7963            ksms.addScannedPackageLPw(pkg);
7964
7965            int N = pkg.providers.size();
7966            StringBuilder r = null;
7967            int i;
7968            for (i=0; i<N; i++) {
7969                PackageParser.Provider p = pkg.providers.get(i);
7970                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7971                        p.info.processName, pkg.applicationInfo.uid);
7972                mProviders.addProvider(p);
7973                p.syncable = p.info.isSyncable;
7974                if (p.info.authority != null) {
7975                    String names[] = p.info.authority.split(";");
7976                    p.info.authority = null;
7977                    for (int j = 0; j < names.length; j++) {
7978                        if (j == 1 && p.syncable) {
7979                            // We only want the first authority for a provider to possibly be
7980                            // syncable, so if we already added this provider using a different
7981                            // authority clear the syncable flag. We copy the provider before
7982                            // changing it because the mProviders object contains a reference
7983                            // to a provider that we don't want to change.
7984                            // Only do this for the second authority since the resulting provider
7985                            // object can be the same for all future authorities for this provider.
7986                            p = new PackageParser.Provider(p);
7987                            p.syncable = false;
7988                        }
7989                        if (!mProvidersByAuthority.containsKey(names[j])) {
7990                            mProvidersByAuthority.put(names[j], p);
7991                            if (p.info.authority == null) {
7992                                p.info.authority = names[j];
7993                            } else {
7994                                p.info.authority = p.info.authority + ";" + names[j];
7995                            }
7996                            if (DEBUG_PACKAGE_SCANNING) {
7997                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7998                                    Log.d(TAG, "Registered content provider: " + names[j]
7999                                            + ", className = " + p.info.name + ", isSyncable = "
8000                                            + p.info.isSyncable);
8001                            }
8002                        } else {
8003                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8004                            Slog.w(TAG, "Skipping provider name " + names[j] +
8005                                    " (in package " + pkg.applicationInfo.packageName +
8006                                    "): name already used by "
8007                                    + ((other != null && other.getComponentName() != null)
8008                                            ? other.getComponentName().getPackageName() : "?"));
8009                        }
8010                    }
8011                }
8012                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8013                    if (r == null) {
8014                        r = new StringBuilder(256);
8015                    } else {
8016                        r.append(' ');
8017                    }
8018                    r.append(p.info.name);
8019                }
8020            }
8021            if (r != null) {
8022                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8023            }
8024
8025            N = pkg.services.size();
8026            r = null;
8027            for (i=0; i<N; i++) {
8028                PackageParser.Service s = pkg.services.get(i);
8029                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8030                        s.info.processName, pkg.applicationInfo.uid);
8031                mServices.addService(s);
8032                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8033                    if (r == null) {
8034                        r = new StringBuilder(256);
8035                    } else {
8036                        r.append(' ');
8037                    }
8038                    r.append(s.info.name);
8039                }
8040            }
8041            if (r != null) {
8042                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8043            }
8044
8045            N = pkg.receivers.size();
8046            r = null;
8047            for (i=0; i<N; i++) {
8048                PackageParser.Activity a = pkg.receivers.get(i);
8049                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8050                        a.info.processName, pkg.applicationInfo.uid);
8051                mReceivers.addActivity(a, "receiver");
8052                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8053                    if (r == null) {
8054                        r = new StringBuilder(256);
8055                    } else {
8056                        r.append(' ');
8057                    }
8058                    r.append(a.info.name);
8059                }
8060            }
8061            if (r != null) {
8062                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8063            }
8064
8065            N = pkg.activities.size();
8066            r = null;
8067            for (i=0; i<N; i++) {
8068                PackageParser.Activity a = pkg.activities.get(i);
8069                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8070                        a.info.processName, pkg.applicationInfo.uid);
8071                mActivities.addActivity(a, "activity");
8072                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8073                    if (r == null) {
8074                        r = new StringBuilder(256);
8075                    } else {
8076                        r.append(' ');
8077                    }
8078                    r.append(a.info.name);
8079                }
8080            }
8081            if (r != null) {
8082                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8083            }
8084
8085            N = pkg.permissionGroups.size();
8086            r = null;
8087            for (i=0; i<N; i++) {
8088                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8089                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8090                if (cur == null) {
8091                    mPermissionGroups.put(pg.info.name, pg);
8092                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8093                        if (r == null) {
8094                            r = new StringBuilder(256);
8095                        } else {
8096                            r.append(' ');
8097                        }
8098                        r.append(pg.info.name);
8099                    }
8100                } else {
8101                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8102                            + pg.info.packageName + " ignored: original from "
8103                            + cur.info.packageName);
8104                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8105                        if (r == null) {
8106                            r = new StringBuilder(256);
8107                        } else {
8108                            r.append(' ');
8109                        }
8110                        r.append("DUP:");
8111                        r.append(pg.info.name);
8112                    }
8113                }
8114            }
8115            if (r != null) {
8116                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8117            }
8118
8119            N = pkg.permissions.size();
8120            r = null;
8121            for (i=0; i<N; i++) {
8122                PackageParser.Permission p = pkg.permissions.get(i);
8123
8124                // Assume by default that we did not install this permission into the system.
8125                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8126
8127                // Now that permission groups have a special meaning, we ignore permission
8128                // groups for legacy apps to prevent unexpected behavior. In particular,
8129                // permissions for one app being granted to someone just becase they happen
8130                // to be in a group defined by another app (before this had no implications).
8131                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8132                    p.group = mPermissionGroups.get(p.info.group);
8133                    // Warn for a permission in an unknown group.
8134                    if (p.info.group != null && p.group == null) {
8135                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8136                                + p.info.packageName + " in an unknown group " + p.info.group);
8137                    }
8138                }
8139
8140                ArrayMap<String, BasePermission> permissionMap =
8141                        p.tree ? mSettings.mPermissionTrees
8142                                : mSettings.mPermissions;
8143                BasePermission bp = permissionMap.get(p.info.name);
8144
8145                // Allow system apps to redefine non-system permissions
8146                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8147                    final boolean currentOwnerIsSystem = (bp.perm != null
8148                            && isSystemApp(bp.perm.owner));
8149                    if (isSystemApp(p.owner)) {
8150                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8151                            // It's a built-in permission and no owner, take ownership now
8152                            bp.packageSetting = pkgSetting;
8153                            bp.perm = p;
8154                            bp.uid = pkg.applicationInfo.uid;
8155                            bp.sourcePackage = p.info.packageName;
8156                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8157                        } else if (!currentOwnerIsSystem) {
8158                            String msg = "New decl " + p.owner + " of permission  "
8159                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8160                            reportSettingsProblem(Log.WARN, msg);
8161                            bp = null;
8162                        }
8163                    }
8164                }
8165
8166                if (bp == null) {
8167                    bp = new BasePermission(p.info.name, p.info.packageName,
8168                            BasePermission.TYPE_NORMAL);
8169                    permissionMap.put(p.info.name, bp);
8170                }
8171
8172                if (bp.perm == null) {
8173                    if (bp.sourcePackage == null
8174                            || bp.sourcePackage.equals(p.info.packageName)) {
8175                        BasePermission tree = findPermissionTreeLP(p.info.name);
8176                        if (tree == null
8177                                || tree.sourcePackage.equals(p.info.packageName)) {
8178                            bp.packageSetting = pkgSetting;
8179                            bp.perm = p;
8180                            bp.uid = pkg.applicationInfo.uid;
8181                            bp.sourcePackage = p.info.packageName;
8182                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8183                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8184                                if (r == null) {
8185                                    r = new StringBuilder(256);
8186                                } else {
8187                                    r.append(' ');
8188                                }
8189                                r.append(p.info.name);
8190                            }
8191                        } else {
8192                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8193                                    + p.info.packageName + " ignored: base tree "
8194                                    + tree.name + " is from package "
8195                                    + tree.sourcePackage);
8196                        }
8197                    } else {
8198                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8199                                + p.info.packageName + " ignored: original from "
8200                                + bp.sourcePackage);
8201                    }
8202                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8203                    if (r == null) {
8204                        r = new StringBuilder(256);
8205                    } else {
8206                        r.append(' ');
8207                    }
8208                    r.append("DUP:");
8209                    r.append(p.info.name);
8210                }
8211                if (bp.perm == p) {
8212                    bp.protectionLevel = p.info.protectionLevel;
8213                }
8214            }
8215
8216            if (r != null) {
8217                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8218            }
8219
8220            N = pkg.instrumentation.size();
8221            r = null;
8222            for (i=0; i<N; i++) {
8223                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8224                a.info.packageName = pkg.applicationInfo.packageName;
8225                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8226                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8227                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8228                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8229                a.info.dataDir = pkg.applicationInfo.dataDir;
8230                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8231                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8232
8233                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8234                // need other information about the application, like the ABI and what not ?
8235                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8236                mInstrumentation.put(a.getComponentName(), a);
8237                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8238                    if (r == null) {
8239                        r = new StringBuilder(256);
8240                    } else {
8241                        r.append(' ');
8242                    }
8243                    r.append(a.info.name);
8244                }
8245            }
8246            if (r != null) {
8247                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8248            }
8249
8250            if (pkg.protectedBroadcasts != null) {
8251                N = pkg.protectedBroadcasts.size();
8252                for (i=0; i<N; i++) {
8253                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8254                }
8255            }
8256
8257            pkgSetting.setTimeStamp(scanFileTime);
8258
8259            // Create idmap files for pairs of (packages, overlay packages).
8260            // Note: "android", ie framework-res.apk, is handled by native layers.
8261            if (pkg.mOverlayTarget != null) {
8262                // This is an overlay package.
8263                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8264                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8265                        mOverlays.put(pkg.mOverlayTarget,
8266                                new ArrayMap<String, PackageParser.Package>());
8267                    }
8268                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8269                    map.put(pkg.packageName, pkg);
8270                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8271                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8272                        createIdmapFailed = true;
8273                    }
8274                }
8275            } else if (mOverlays.containsKey(pkg.packageName) &&
8276                    !pkg.packageName.equals("android")) {
8277                // This is a regular package, with one or more known overlay packages.
8278                createIdmapsForPackageLI(pkg);
8279            }
8280        }
8281
8282        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8283
8284        if (createIdmapFailed) {
8285            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8286                    "scanPackageLI failed to createIdmap");
8287        }
8288        return pkg;
8289    }
8290
8291    /**
8292     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8293     * is derived purely on the basis of the contents of {@code scanFile} and
8294     * {@code cpuAbiOverride}.
8295     *
8296     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8297     */
8298    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8299                                 String cpuAbiOverride, boolean extractLibs)
8300            throws PackageManagerException {
8301        // TODO: We can probably be smarter about this stuff. For installed apps,
8302        // we can calculate this information at install time once and for all. For
8303        // system apps, we can probably assume that this information doesn't change
8304        // after the first boot scan. As things stand, we do lots of unnecessary work.
8305
8306        // Give ourselves some initial paths; we'll come back for another
8307        // pass once we've determined ABI below.
8308        setNativeLibraryPaths(pkg);
8309
8310        // We would never need to extract libs for forward-locked and external packages,
8311        // since the container service will do it for us. We shouldn't attempt to
8312        // extract libs from system app when it was not updated.
8313        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8314                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8315            extractLibs = false;
8316        }
8317
8318        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8319        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8320
8321        NativeLibraryHelper.Handle handle = null;
8322        try {
8323            handle = NativeLibraryHelper.Handle.create(pkg);
8324            // TODO(multiArch): This can be null for apps that didn't go through the
8325            // usual installation process. We can calculate it again, like we
8326            // do during install time.
8327            //
8328            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8329            // unnecessary.
8330            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8331
8332            // Null out the abis so that they can be recalculated.
8333            pkg.applicationInfo.primaryCpuAbi = null;
8334            pkg.applicationInfo.secondaryCpuAbi = null;
8335            if (isMultiArch(pkg.applicationInfo)) {
8336                // Warn if we've set an abiOverride for multi-lib packages..
8337                // By definition, we need to copy both 32 and 64 bit libraries for
8338                // such packages.
8339                if (pkg.cpuAbiOverride != null
8340                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8341                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8342                }
8343
8344                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8345                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8346                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8347                    if (extractLibs) {
8348                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8349                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8350                                useIsaSpecificSubdirs);
8351                    } else {
8352                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8353                    }
8354                }
8355
8356                maybeThrowExceptionForMultiArchCopy(
8357                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8358
8359                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8360                    if (extractLibs) {
8361                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8362                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8363                                useIsaSpecificSubdirs);
8364                    } else {
8365                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8366                    }
8367                }
8368
8369                maybeThrowExceptionForMultiArchCopy(
8370                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8371
8372                if (abi64 >= 0) {
8373                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8374                }
8375
8376                if (abi32 >= 0) {
8377                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8378                    if (abi64 >= 0) {
8379                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8380                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8381                            pkg.applicationInfo.primaryCpuAbi = abi;
8382                        } else {
8383                            pkg.applicationInfo.secondaryCpuAbi = abi;
8384                        }
8385                    } else {
8386                        pkg.applicationInfo.primaryCpuAbi = abi;
8387                    }
8388                }
8389
8390            } else {
8391                String[] abiList = (cpuAbiOverride != null) ?
8392                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8393
8394                // Enable gross and lame hacks for apps that are built with old
8395                // SDK tools. We must scan their APKs for renderscript bitcode and
8396                // not launch them if it's present. Don't bother checking on devices
8397                // that don't have 64 bit support.
8398                boolean needsRenderScriptOverride = false;
8399                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8400                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8401                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8402                    needsRenderScriptOverride = true;
8403                }
8404
8405                final int copyRet;
8406                if (extractLibs) {
8407                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8408                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8409                } else {
8410                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8411                }
8412
8413                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8414                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8415                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8416                }
8417
8418                if (copyRet >= 0) {
8419                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8420                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8421                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8422                } else if (needsRenderScriptOverride) {
8423                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8424                }
8425            }
8426        } catch (IOException ioe) {
8427            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8428        } finally {
8429            IoUtils.closeQuietly(handle);
8430        }
8431
8432        // Now that we've calculated the ABIs and determined if it's an internal app,
8433        // we will go ahead and populate the nativeLibraryPath.
8434        setNativeLibraryPaths(pkg);
8435    }
8436
8437    /**
8438     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8439     * i.e, so that all packages can be run inside a single process if required.
8440     *
8441     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8442     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8443     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8444     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8445     * updating a package that belongs to a shared user.
8446     *
8447     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8448     * adds unnecessary complexity.
8449     */
8450    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8451            PackageParser.Package scannedPackage, boolean bootComplete) {
8452        String requiredInstructionSet = null;
8453        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8454            requiredInstructionSet = VMRuntime.getInstructionSet(
8455                     scannedPackage.applicationInfo.primaryCpuAbi);
8456        }
8457
8458        PackageSetting requirer = null;
8459        for (PackageSetting ps : packagesForUser) {
8460            // If packagesForUser contains scannedPackage, we skip it. This will happen
8461            // when scannedPackage is an update of an existing package. Without this check,
8462            // we will never be able to change the ABI of any package belonging to a shared
8463            // user, even if it's compatible with other packages.
8464            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8465                if (ps.primaryCpuAbiString == null) {
8466                    continue;
8467                }
8468
8469                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8470                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8471                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8472                    // this but there's not much we can do.
8473                    String errorMessage = "Instruction set mismatch, "
8474                            + ((requirer == null) ? "[caller]" : requirer)
8475                            + " requires " + requiredInstructionSet + " whereas " + ps
8476                            + " requires " + instructionSet;
8477                    Slog.w(TAG, errorMessage);
8478                }
8479
8480                if (requiredInstructionSet == null) {
8481                    requiredInstructionSet = instructionSet;
8482                    requirer = ps;
8483                }
8484            }
8485        }
8486
8487        if (requiredInstructionSet != null) {
8488            String adjustedAbi;
8489            if (requirer != null) {
8490                // requirer != null implies that either scannedPackage was null or that scannedPackage
8491                // did not require an ABI, in which case we have to adjust scannedPackage to match
8492                // the ABI of the set (which is the same as requirer's ABI)
8493                adjustedAbi = requirer.primaryCpuAbiString;
8494                if (scannedPackage != null) {
8495                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8496                }
8497            } else {
8498                // requirer == null implies that we're updating all ABIs in the set to
8499                // match scannedPackage.
8500                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8501            }
8502
8503            for (PackageSetting ps : packagesForUser) {
8504                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8505                    if (ps.primaryCpuAbiString != null) {
8506                        continue;
8507                    }
8508
8509                    ps.primaryCpuAbiString = adjustedAbi;
8510                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8511                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8512                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8513                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8514                                + " (requirer="
8515                                + (requirer == null ? "null" : requirer.pkg.packageName)
8516                                + ", scannedPackage="
8517                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8518                                + ")");
8519                        try {
8520                            mInstaller.rmdex(ps.codePathString,
8521                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8522                        } catch (InstallerException ignored) {
8523                        }
8524                    }
8525                }
8526            }
8527        }
8528    }
8529
8530    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8531        synchronized (mPackages) {
8532            mResolverReplaced = true;
8533            // Set up information for custom user intent resolution activity.
8534            mResolveActivity.applicationInfo = pkg.applicationInfo;
8535            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8536            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8537            mResolveActivity.processName = pkg.applicationInfo.packageName;
8538            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8539            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8540                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8541            mResolveActivity.theme = 0;
8542            mResolveActivity.exported = true;
8543            mResolveActivity.enabled = true;
8544            mResolveInfo.activityInfo = mResolveActivity;
8545            mResolveInfo.priority = 0;
8546            mResolveInfo.preferredOrder = 0;
8547            mResolveInfo.match = 0;
8548            mResolveComponentName = mCustomResolverComponentName;
8549            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8550                    mResolveComponentName);
8551        }
8552    }
8553
8554    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8555        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8556
8557        // Set up information for ephemeral installer activity
8558        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8559        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8560        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8561        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8562        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8563        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8564                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8565        mEphemeralInstallerActivity.theme = 0;
8566        mEphemeralInstallerActivity.exported = true;
8567        mEphemeralInstallerActivity.enabled = true;
8568        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8569        mEphemeralInstallerInfo.priority = 0;
8570        mEphemeralInstallerInfo.preferredOrder = 0;
8571        mEphemeralInstallerInfo.match = 0;
8572
8573        if (DEBUG_EPHEMERAL) {
8574            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8575        }
8576    }
8577
8578    private static String calculateBundledApkRoot(final String codePathString) {
8579        final File codePath = new File(codePathString);
8580        final File codeRoot;
8581        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8582            codeRoot = Environment.getRootDirectory();
8583        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8584            codeRoot = Environment.getOemDirectory();
8585        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8586            codeRoot = Environment.getVendorDirectory();
8587        } else {
8588            // Unrecognized code path; take its top real segment as the apk root:
8589            // e.g. /something/app/blah.apk => /something
8590            try {
8591                File f = codePath.getCanonicalFile();
8592                File parent = f.getParentFile();    // non-null because codePath is a file
8593                File tmp;
8594                while ((tmp = parent.getParentFile()) != null) {
8595                    f = parent;
8596                    parent = tmp;
8597                }
8598                codeRoot = f;
8599                Slog.w(TAG, "Unrecognized code path "
8600                        + codePath + " - using " + codeRoot);
8601            } catch (IOException e) {
8602                // Can't canonicalize the code path -- shenanigans?
8603                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8604                return Environment.getRootDirectory().getPath();
8605            }
8606        }
8607        return codeRoot.getPath();
8608    }
8609
8610    /**
8611     * Derive and set the location of native libraries for the given package,
8612     * which varies depending on where and how the package was installed.
8613     */
8614    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8615        final ApplicationInfo info = pkg.applicationInfo;
8616        final String codePath = pkg.codePath;
8617        final File codeFile = new File(codePath);
8618        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8619        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8620
8621        info.nativeLibraryRootDir = null;
8622        info.nativeLibraryRootRequiresIsa = false;
8623        info.nativeLibraryDir = null;
8624        info.secondaryNativeLibraryDir = null;
8625
8626        if (isApkFile(codeFile)) {
8627            // Monolithic install
8628            if (bundledApp) {
8629                // If "/system/lib64/apkname" exists, assume that is the per-package
8630                // native library directory to use; otherwise use "/system/lib/apkname".
8631                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8632                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8633                        getPrimaryInstructionSet(info));
8634
8635                // This is a bundled system app so choose the path based on the ABI.
8636                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8637                // is just the default path.
8638                final String apkName = deriveCodePathName(codePath);
8639                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8640                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8641                        apkName).getAbsolutePath();
8642
8643                if (info.secondaryCpuAbi != null) {
8644                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8645                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8646                            secondaryLibDir, apkName).getAbsolutePath();
8647                }
8648            } else if (asecApp) {
8649                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8650                        .getAbsolutePath();
8651            } else {
8652                final String apkName = deriveCodePathName(codePath);
8653                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8654                        .getAbsolutePath();
8655            }
8656
8657            info.nativeLibraryRootRequiresIsa = false;
8658            info.nativeLibraryDir = info.nativeLibraryRootDir;
8659        } else {
8660            // Cluster install
8661            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8662            info.nativeLibraryRootRequiresIsa = true;
8663
8664            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8665                    getPrimaryInstructionSet(info)).getAbsolutePath();
8666
8667            if (info.secondaryCpuAbi != null) {
8668                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8669                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8670            }
8671        }
8672    }
8673
8674    /**
8675     * Calculate the abis and roots for a bundled app. These can uniquely
8676     * be determined from the contents of the system partition, i.e whether
8677     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8678     * of this information, and instead assume that the system was built
8679     * sensibly.
8680     */
8681    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8682                                           PackageSetting pkgSetting) {
8683        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8684
8685        // If "/system/lib64/apkname" exists, assume that is the per-package
8686        // native library directory to use; otherwise use "/system/lib/apkname".
8687        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8688        setBundledAppAbi(pkg, apkRoot, apkName);
8689        // pkgSetting might be null during rescan following uninstall of updates
8690        // to a bundled app, so accommodate that possibility.  The settings in
8691        // that case will be established later from the parsed package.
8692        //
8693        // If the settings aren't null, sync them up with what we've just derived.
8694        // note that apkRoot isn't stored in the package settings.
8695        if (pkgSetting != null) {
8696            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8697            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8698        }
8699    }
8700
8701    /**
8702     * Deduces the ABI of a bundled app and sets the relevant fields on the
8703     * parsed pkg object.
8704     *
8705     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8706     *        under which system libraries are installed.
8707     * @param apkName the name of the installed package.
8708     */
8709    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8710        final File codeFile = new File(pkg.codePath);
8711
8712        final boolean has64BitLibs;
8713        final boolean has32BitLibs;
8714        if (isApkFile(codeFile)) {
8715            // Monolithic install
8716            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8717            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8718        } else {
8719            // Cluster install
8720            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8721            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8722                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8723                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8724                has64BitLibs = (new File(rootDir, isa)).exists();
8725            } else {
8726                has64BitLibs = false;
8727            }
8728            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8729                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8730                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8731                has32BitLibs = (new File(rootDir, isa)).exists();
8732            } else {
8733                has32BitLibs = false;
8734            }
8735        }
8736
8737        if (has64BitLibs && !has32BitLibs) {
8738            // The package has 64 bit libs, but not 32 bit libs. Its primary
8739            // ABI should be 64 bit. We can safely assume here that the bundled
8740            // native libraries correspond to the most preferred ABI in the list.
8741
8742            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8743            pkg.applicationInfo.secondaryCpuAbi = null;
8744        } else if (has32BitLibs && !has64BitLibs) {
8745            // The package has 32 bit libs but not 64 bit libs. Its primary
8746            // ABI should be 32 bit.
8747
8748            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8749            pkg.applicationInfo.secondaryCpuAbi = null;
8750        } else if (has32BitLibs && has64BitLibs) {
8751            // The application has both 64 and 32 bit bundled libraries. We check
8752            // here that the app declares multiArch support, and warn if it doesn't.
8753            //
8754            // We will be lenient here and record both ABIs. The primary will be the
8755            // ABI that's higher on the list, i.e, a device that's configured to prefer
8756            // 64 bit apps will see a 64 bit primary ABI,
8757
8758            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8759                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8760            }
8761
8762            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8763                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8764                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8765            } else {
8766                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8767                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8768            }
8769        } else {
8770            pkg.applicationInfo.primaryCpuAbi = null;
8771            pkg.applicationInfo.secondaryCpuAbi = null;
8772        }
8773    }
8774
8775    private void killPackage(PackageParser.Package pkg, String reason) {
8776        // Kill the parent package
8777        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8778        // Kill the child packages
8779        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8780        for (int i = 0; i < childCount; i++) {
8781            PackageParser.Package childPkg = pkg.childPackages.get(i);
8782            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8783        }
8784    }
8785
8786    private void killApplication(String pkgName, int appId, String reason) {
8787        // Request the ActivityManager to kill the process(only for existing packages)
8788        // so that we do not end up in a confused state while the user is still using the older
8789        // version of the application while the new one gets installed.
8790        IActivityManager am = ActivityManagerNative.getDefault();
8791        if (am != null) {
8792            try {
8793                am.killApplicationWithAppId(pkgName, appId, reason);
8794            } catch (RemoteException e) {
8795            }
8796        }
8797    }
8798
8799    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8800        // Remove the parent package setting
8801        PackageSetting ps = (PackageSetting) pkg.mExtras;
8802        if (ps != null) {
8803            removePackageLI(ps, chatty);
8804        }
8805        // Remove the child package setting
8806        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8807        for (int i = 0; i < childCount; i++) {
8808            PackageParser.Package childPkg = pkg.childPackages.get(i);
8809            ps = (PackageSetting) childPkg.mExtras;
8810            if (ps != null) {
8811                removePackageLI(ps, chatty);
8812            }
8813        }
8814    }
8815
8816    void removePackageLI(PackageSetting ps, boolean chatty) {
8817        if (DEBUG_INSTALL) {
8818            if (chatty)
8819                Log.d(TAG, "Removing package " + ps.name);
8820        }
8821
8822        // writer
8823        synchronized (mPackages) {
8824            mPackages.remove(ps.name);
8825            final PackageParser.Package pkg = ps.pkg;
8826            if (pkg != null) {
8827                cleanPackageDataStructuresLILPw(pkg, chatty);
8828            }
8829        }
8830    }
8831
8832    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8833        if (DEBUG_INSTALL) {
8834            if (chatty)
8835                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8836        }
8837
8838        // writer
8839        synchronized (mPackages) {
8840            // Remove the parent package
8841            mPackages.remove(pkg.applicationInfo.packageName);
8842            cleanPackageDataStructuresLILPw(pkg, chatty);
8843
8844            // Remove the child packages
8845            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8846            for (int i = 0; i < childCount; i++) {
8847                PackageParser.Package childPkg = pkg.childPackages.get(i);
8848                mPackages.remove(childPkg.applicationInfo.packageName);
8849                cleanPackageDataStructuresLILPw(childPkg, chatty);
8850            }
8851        }
8852    }
8853
8854    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8855        int N = pkg.providers.size();
8856        StringBuilder r = null;
8857        int i;
8858        for (i=0; i<N; i++) {
8859            PackageParser.Provider p = pkg.providers.get(i);
8860            mProviders.removeProvider(p);
8861            if (p.info.authority == null) {
8862
8863                /* There was another ContentProvider with this authority when
8864                 * this app was installed so this authority is null,
8865                 * Ignore it as we don't have to unregister the provider.
8866                 */
8867                continue;
8868            }
8869            String names[] = p.info.authority.split(";");
8870            for (int j = 0; j < names.length; j++) {
8871                if (mProvidersByAuthority.get(names[j]) == p) {
8872                    mProvidersByAuthority.remove(names[j]);
8873                    if (DEBUG_REMOVE) {
8874                        if (chatty)
8875                            Log.d(TAG, "Unregistered content provider: " + names[j]
8876                                    + ", className = " + p.info.name + ", isSyncable = "
8877                                    + p.info.isSyncable);
8878                    }
8879                }
8880            }
8881            if (DEBUG_REMOVE && chatty) {
8882                if (r == null) {
8883                    r = new StringBuilder(256);
8884                } else {
8885                    r.append(' ');
8886                }
8887                r.append(p.info.name);
8888            }
8889        }
8890        if (r != null) {
8891            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8892        }
8893
8894        N = pkg.services.size();
8895        r = null;
8896        for (i=0; i<N; i++) {
8897            PackageParser.Service s = pkg.services.get(i);
8898            mServices.removeService(s);
8899            if (chatty) {
8900                if (r == null) {
8901                    r = new StringBuilder(256);
8902                } else {
8903                    r.append(' ');
8904                }
8905                r.append(s.info.name);
8906            }
8907        }
8908        if (r != null) {
8909            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8910        }
8911
8912        N = pkg.receivers.size();
8913        r = null;
8914        for (i=0; i<N; i++) {
8915            PackageParser.Activity a = pkg.receivers.get(i);
8916            mReceivers.removeActivity(a, "receiver");
8917            if (DEBUG_REMOVE && chatty) {
8918                if (r == null) {
8919                    r = new StringBuilder(256);
8920                } else {
8921                    r.append(' ');
8922                }
8923                r.append(a.info.name);
8924            }
8925        }
8926        if (r != null) {
8927            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8928        }
8929
8930        N = pkg.activities.size();
8931        r = null;
8932        for (i=0; i<N; i++) {
8933            PackageParser.Activity a = pkg.activities.get(i);
8934            mActivities.removeActivity(a, "activity");
8935            if (DEBUG_REMOVE && chatty) {
8936                if (r == null) {
8937                    r = new StringBuilder(256);
8938                } else {
8939                    r.append(' ');
8940                }
8941                r.append(a.info.name);
8942            }
8943        }
8944        if (r != null) {
8945            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8946        }
8947
8948        N = pkg.permissions.size();
8949        r = null;
8950        for (i=0; i<N; i++) {
8951            PackageParser.Permission p = pkg.permissions.get(i);
8952            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8953            if (bp == null) {
8954                bp = mSettings.mPermissionTrees.get(p.info.name);
8955            }
8956            if (bp != null && bp.perm == p) {
8957                bp.perm = null;
8958                if (DEBUG_REMOVE && chatty) {
8959                    if (r == null) {
8960                        r = new StringBuilder(256);
8961                    } else {
8962                        r.append(' ');
8963                    }
8964                    r.append(p.info.name);
8965                }
8966            }
8967            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8968                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8969                if (appOpPkgs != null) {
8970                    appOpPkgs.remove(pkg.packageName);
8971                }
8972            }
8973        }
8974        if (r != null) {
8975            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8976        }
8977
8978        N = pkg.requestedPermissions.size();
8979        r = null;
8980        for (i=0; i<N; i++) {
8981            String perm = pkg.requestedPermissions.get(i);
8982            BasePermission bp = mSettings.mPermissions.get(perm);
8983            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8984                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8985                if (appOpPkgs != null) {
8986                    appOpPkgs.remove(pkg.packageName);
8987                    if (appOpPkgs.isEmpty()) {
8988                        mAppOpPermissionPackages.remove(perm);
8989                    }
8990                }
8991            }
8992        }
8993        if (r != null) {
8994            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8995        }
8996
8997        N = pkg.instrumentation.size();
8998        r = null;
8999        for (i=0; i<N; i++) {
9000            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9001            mInstrumentation.remove(a.getComponentName());
9002            if (DEBUG_REMOVE && chatty) {
9003                if (r == null) {
9004                    r = new StringBuilder(256);
9005                } else {
9006                    r.append(' ');
9007                }
9008                r.append(a.info.name);
9009            }
9010        }
9011        if (r != null) {
9012            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9013        }
9014
9015        r = null;
9016        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9017            // Only system apps can hold shared libraries.
9018            if (pkg.libraryNames != null) {
9019                for (i=0; i<pkg.libraryNames.size(); i++) {
9020                    String name = pkg.libraryNames.get(i);
9021                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9022                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9023                        mSharedLibraries.remove(name);
9024                        if (DEBUG_REMOVE && chatty) {
9025                            if (r == null) {
9026                                r = new StringBuilder(256);
9027                            } else {
9028                                r.append(' ');
9029                            }
9030                            r.append(name);
9031                        }
9032                    }
9033                }
9034            }
9035        }
9036        if (r != null) {
9037            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9038        }
9039    }
9040
9041    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9042        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9043            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9044                return true;
9045            }
9046        }
9047        return false;
9048    }
9049
9050    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9051    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9052    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9053
9054    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9055        // Update the parent permissions
9056        updatePermissionsLPw(pkg.packageName, pkg, flags);
9057        // Update the child permissions
9058        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9059        for (int i = 0; i < childCount; i++) {
9060            PackageParser.Package childPkg = pkg.childPackages.get(i);
9061            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9062        }
9063    }
9064
9065    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9066            int flags) {
9067        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9068        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9069    }
9070
9071    private void updatePermissionsLPw(String changingPkg,
9072            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9073        // Make sure there are no dangling permission trees.
9074        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9075        while (it.hasNext()) {
9076            final BasePermission bp = it.next();
9077            if (bp.packageSetting == null) {
9078                // We may not yet have parsed the package, so just see if
9079                // we still know about its settings.
9080                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9081            }
9082            if (bp.packageSetting == null) {
9083                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9084                        + " from package " + bp.sourcePackage);
9085                it.remove();
9086            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9087                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9088                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9089                            + " from package " + bp.sourcePackage);
9090                    flags |= UPDATE_PERMISSIONS_ALL;
9091                    it.remove();
9092                }
9093            }
9094        }
9095
9096        // Make sure all dynamic permissions have been assigned to a package,
9097        // and make sure there are no dangling permissions.
9098        it = mSettings.mPermissions.values().iterator();
9099        while (it.hasNext()) {
9100            final BasePermission bp = it.next();
9101            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9102                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9103                        + bp.name + " pkg=" + bp.sourcePackage
9104                        + " info=" + bp.pendingInfo);
9105                if (bp.packageSetting == null && bp.pendingInfo != null) {
9106                    final BasePermission tree = findPermissionTreeLP(bp.name);
9107                    if (tree != null && tree.perm != null) {
9108                        bp.packageSetting = tree.packageSetting;
9109                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9110                                new PermissionInfo(bp.pendingInfo));
9111                        bp.perm.info.packageName = tree.perm.info.packageName;
9112                        bp.perm.info.name = bp.name;
9113                        bp.uid = tree.uid;
9114                    }
9115                }
9116            }
9117            if (bp.packageSetting == null) {
9118                // We may not yet have parsed the package, so just see if
9119                // we still know about its settings.
9120                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9121            }
9122            if (bp.packageSetting == null) {
9123                Slog.w(TAG, "Removing dangling permission: " + bp.name
9124                        + " from package " + bp.sourcePackage);
9125                it.remove();
9126            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9127                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9128                    Slog.i(TAG, "Removing old permission: " + bp.name
9129                            + " from package " + bp.sourcePackage);
9130                    flags |= UPDATE_PERMISSIONS_ALL;
9131                    it.remove();
9132                }
9133            }
9134        }
9135
9136        // Now update the permissions for all packages, in particular
9137        // replace the granted permissions of the system packages.
9138        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9139            for (PackageParser.Package pkg : mPackages.values()) {
9140                if (pkg != pkgInfo) {
9141                    // Only replace for packages on requested volume
9142                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9143                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9144                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9145                    grantPermissionsLPw(pkg, replace, changingPkg);
9146                }
9147            }
9148        }
9149
9150        if (pkgInfo != null) {
9151            // Only replace for packages on requested volume
9152            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9153            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9154                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9155            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9156        }
9157    }
9158
9159    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9160            String packageOfInterest) {
9161        // IMPORTANT: There are two types of permissions: install and runtime.
9162        // Install time permissions are granted when the app is installed to
9163        // all device users and users added in the future. Runtime permissions
9164        // are granted at runtime explicitly to specific users. Normal and signature
9165        // protected permissions are install time permissions. Dangerous permissions
9166        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9167        // otherwise they are runtime permissions. This function does not manage
9168        // runtime permissions except for the case an app targeting Lollipop MR1
9169        // being upgraded to target a newer SDK, in which case dangerous permissions
9170        // are transformed from install time to runtime ones.
9171
9172        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9173        if (ps == null) {
9174            return;
9175        }
9176
9177        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9178
9179        PermissionsState permissionsState = ps.getPermissionsState();
9180        PermissionsState origPermissions = permissionsState;
9181
9182        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9183
9184        boolean runtimePermissionsRevoked = false;
9185        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9186
9187        boolean changedInstallPermission = false;
9188
9189        if (replace) {
9190            ps.installPermissionsFixed = false;
9191            if (!ps.isSharedUser()) {
9192                origPermissions = new PermissionsState(permissionsState);
9193                permissionsState.reset();
9194            } else {
9195                // We need to know only about runtime permission changes since the
9196                // calling code always writes the install permissions state but
9197                // the runtime ones are written only if changed. The only cases of
9198                // changed runtime permissions here are promotion of an install to
9199                // runtime and revocation of a runtime from a shared user.
9200                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9201                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9202                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9203                    runtimePermissionsRevoked = true;
9204                }
9205            }
9206        }
9207
9208        permissionsState.setGlobalGids(mGlobalGids);
9209
9210        final int N = pkg.requestedPermissions.size();
9211        for (int i=0; i<N; i++) {
9212            final String name = pkg.requestedPermissions.get(i);
9213            final BasePermission bp = mSettings.mPermissions.get(name);
9214
9215            if (DEBUG_INSTALL) {
9216                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9217            }
9218
9219            if (bp == null || bp.packageSetting == null) {
9220                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9221                    Slog.w(TAG, "Unknown permission " + name
9222                            + " in package " + pkg.packageName);
9223                }
9224                continue;
9225            }
9226
9227            final String perm = bp.name;
9228            boolean allowedSig = false;
9229            int grant = GRANT_DENIED;
9230
9231            // Keep track of app op permissions.
9232            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9233                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9234                if (pkgs == null) {
9235                    pkgs = new ArraySet<>();
9236                    mAppOpPermissionPackages.put(bp.name, pkgs);
9237                }
9238                pkgs.add(pkg.packageName);
9239            }
9240
9241            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9242            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9243                    >= Build.VERSION_CODES.M;
9244            switch (level) {
9245                case PermissionInfo.PROTECTION_NORMAL: {
9246                    // For all apps normal permissions are install time ones.
9247                    grant = GRANT_INSTALL;
9248                } break;
9249
9250                case PermissionInfo.PROTECTION_DANGEROUS: {
9251                    // If a permission review is required for legacy apps we represent
9252                    // their permissions as always granted runtime ones since we need
9253                    // to keep the review required permission flag per user while an
9254                    // install permission's state is shared across all users.
9255                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9256                        // For legacy apps dangerous permissions are install time ones.
9257                        grant = GRANT_INSTALL;
9258                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9259                        // For legacy apps that became modern, install becomes runtime.
9260                        grant = GRANT_UPGRADE;
9261                    } else if (mPromoteSystemApps
9262                            && isSystemApp(ps)
9263                            && mExistingSystemPackages.contains(ps.name)) {
9264                        // For legacy system apps, install becomes runtime.
9265                        // We cannot check hasInstallPermission() for system apps since those
9266                        // permissions were granted implicitly and not persisted pre-M.
9267                        grant = GRANT_UPGRADE;
9268                    } else {
9269                        // For modern apps keep runtime permissions unchanged.
9270                        grant = GRANT_RUNTIME;
9271                    }
9272                } break;
9273
9274                case PermissionInfo.PROTECTION_SIGNATURE: {
9275                    // For all apps signature permissions are install time ones.
9276                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9277                    if (allowedSig) {
9278                        grant = GRANT_INSTALL;
9279                    }
9280                } break;
9281            }
9282
9283            if (DEBUG_INSTALL) {
9284                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9285            }
9286
9287            if (grant != GRANT_DENIED) {
9288                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9289                    // If this is an existing, non-system package, then
9290                    // we can't add any new permissions to it.
9291                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9292                        // Except...  if this is a permission that was added
9293                        // to the platform (note: need to only do this when
9294                        // updating the platform).
9295                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9296                            grant = GRANT_DENIED;
9297                        }
9298                    }
9299                }
9300
9301                switch (grant) {
9302                    case GRANT_INSTALL: {
9303                        // Revoke this as runtime permission to handle the case of
9304                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9305                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9306                            if (origPermissions.getRuntimePermissionState(
9307                                    bp.name, userId) != null) {
9308                                // Revoke the runtime permission and clear the flags.
9309                                origPermissions.revokeRuntimePermission(bp, userId);
9310                                origPermissions.updatePermissionFlags(bp, userId,
9311                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9312                                // If we revoked a permission permission, we have to write.
9313                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9314                                        changedRuntimePermissionUserIds, userId);
9315                            }
9316                        }
9317                        // Grant an install permission.
9318                        if (permissionsState.grantInstallPermission(bp) !=
9319                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9320                            changedInstallPermission = true;
9321                        }
9322                    } break;
9323
9324                    case GRANT_RUNTIME: {
9325                        // Grant previously granted runtime permissions.
9326                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9327                            PermissionState permissionState = origPermissions
9328                                    .getRuntimePermissionState(bp.name, userId);
9329                            int flags = permissionState != null
9330                                    ? permissionState.getFlags() : 0;
9331                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9332                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9333                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9334                                    // If we cannot put the permission as it was, we have to write.
9335                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9336                                            changedRuntimePermissionUserIds, userId);
9337                                }
9338                                // If the app supports runtime permissions no need for a review.
9339                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9340                                        && appSupportsRuntimePermissions
9341                                        && (flags & PackageManager
9342                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9343                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9344                                    // Since we changed the flags, we have to write.
9345                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9346                                            changedRuntimePermissionUserIds, userId);
9347                                }
9348                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9349                                    && !appSupportsRuntimePermissions) {
9350                                // For legacy apps that need a permission review, every new
9351                                // runtime permission is granted but it is pending a review.
9352                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9353                                    permissionsState.grantRuntimePermission(bp, userId);
9354                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9355                                    // We changed the permission and flags, hence have to write.
9356                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9357                                            changedRuntimePermissionUserIds, userId);
9358                                }
9359                            }
9360                            // Propagate the permission flags.
9361                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9362                        }
9363                    } break;
9364
9365                    case GRANT_UPGRADE: {
9366                        // Grant runtime permissions for a previously held install permission.
9367                        PermissionState permissionState = origPermissions
9368                                .getInstallPermissionState(bp.name);
9369                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9370
9371                        if (origPermissions.revokeInstallPermission(bp)
9372                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9373                            // We will be transferring the permission flags, so clear them.
9374                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9375                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9376                            changedInstallPermission = true;
9377                        }
9378
9379                        // If the permission is not to be promoted to runtime we ignore it and
9380                        // also its other flags as they are not applicable to install permissions.
9381                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9382                            for (int userId : currentUserIds) {
9383                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9384                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9385                                    // Transfer the permission flags.
9386                                    permissionsState.updatePermissionFlags(bp, userId,
9387                                            flags, flags);
9388                                    // If we granted the permission, we have to write.
9389                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9390                                            changedRuntimePermissionUserIds, userId);
9391                                }
9392                            }
9393                        }
9394                    } break;
9395
9396                    default: {
9397                        if (packageOfInterest == null
9398                                || packageOfInterest.equals(pkg.packageName)) {
9399                            Slog.w(TAG, "Not granting permission " + perm
9400                                    + " to package " + pkg.packageName
9401                                    + " because it was previously installed without");
9402                        }
9403                    } break;
9404                }
9405            } else {
9406                if (permissionsState.revokeInstallPermission(bp) !=
9407                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9408                    // Also drop the permission flags.
9409                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9410                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9411                    changedInstallPermission = true;
9412                    Slog.i(TAG, "Un-granting permission " + perm
9413                            + " from package " + pkg.packageName
9414                            + " (protectionLevel=" + bp.protectionLevel
9415                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9416                            + ")");
9417                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9418                    // Don't print warning for app op permissions, since it is fine for them
9419                    // not to be granted, there is a UI for the user to decide.
9420                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9421                        Slog.w(TAG, "Not granting permission " + perm
9422                                + " to package " + pkg.packageName
9423                                + " (protectionLevel=" + bp.protectionLevel
9424                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9425                                + ")");
9426                    }
9427                }
9428            }
9429        }
9430
9431        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9432                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9433            // This is the first that we have heard about this package, so the
9434            // permissions we have now selected are fixed until explicitly
9435            // changed.
9436            ps.installPermissionsFixed = true;
9437        }
9438
9439        // Persist the runtime permissions state for users with changes. If permissions
9440        // were revoked because no app in the shared user declares them we have to
9441        // write synchronously to avoid losing runtime permissions state.
9442        for (int userId : changedRuntimePermissionUserIds) {
9443            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9444        }
9445
9446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9447    }
9448
9449    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9450        boolean allowed = false;
9451        final int NP = PackageParser.NEW_PERMISSIONS.length;
9452        for (int ip=0; ip<NP; ip++) {
9453            final PackageParser.NewPermissionInfo npi
9454                    = PackageParser.NEW_PERMISSIONS[ip];
9455            if (npi.name.equals(perm)
9456                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9457                allowed = true;
9458                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9459                        + pkg.packageName);
9460                break;
9461            }
9462        }
9463        return allowed;
9464    }
9465
9466    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9467            BasePermission bp, PermissionsState origPermissions) {
9468        boolean allowed;
9469        allowed = (compareSignatures(
9470                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9471                        == PackageManager.SIGNATURE_MATCH)
9472                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9473                        == PackageManager.SIGNATURE_MATCH);
9474        if (!allowed && (bp.protectionLevel
9475                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9476            if (isSystemApp(pkg)) {
9477                // For updated system applications, a system permission
9478                // is granted only if it had been defined by the original application.
9479                if (pkg.isUpdatedSystemApp()) {
9480                    final PackageSetting sysPs = mSettings
9481                            .getDisabledSystemPkgLPr(pkg.packageName);
9482                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9483                        // If the original was granted this permission, we take
9484                        // that grant decision as read and propagate it to the
9485                        // update.
9486                        if (sysPs.isPrivileged()) {
9487                            allowed = true;
9488                        }
9489                    } else {
9490                        // The system apk may have been updated with an older
9491                        // version of the one on the data partition, but which
9492                        // granted a new system permission that it didn't have
9493                        // before.  In this case we do want to allow the app to
9494                        // now get the new permission if the ancestral apk is
9495                        // privileged to get it.
9496                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9497                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9498                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9499                                    allowed = true;
9500                                    break;
9501                                }
9502                            }
9503                        }
9504                        // Also if a privileged parent package on the system image or any of
9505                        // its children requested a privileged permission, the updated child
9506                        // packages can also get the permission.
9507                        if (pkg.parentPackage != null) {
9508                            final PackageSetting disabledSysParentPs = mSettings
9509                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9510                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9511                                    && disabledSysParentPs.isPrivileged()) {
9512                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9513                                    allowed = true;
9514                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9515                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9516                                    for (int i = 0; i < count; i++) {
9517                                        PackageParser.Package disabledSysChildPkg =
9518                                                disabledSysParentPs.pkg.childPackages.get(i);
9519                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9520                                                perm)) {
9521                                            allowed = true;
9522                                            break;
9523                                        }
9524                                    }
9525                                }
9526                            }
9527                        }
9528                    }
9529                } else {
9530                    allowed = isPrivilegedApp(pkg);
9531                }
9532            }
9533        }
9534        if (!allowed) {
9535            if (!allowed && (bp.protectionLevel
9536                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9537                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9538                // If this was a previously normal/dangerous permission that got moved
9539                // to a system permission as part of the runtime permission redesign, then
9540                // we still want to blindly grant it to old apps.
9541                allowed = true;
9542            }
9543            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9544                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9545                // If this permission is to be granted to the system installer and
9546                // this app is an installer, then it gets the permission.
9547                allowed = true;
9548            }
9549            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9550                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9551                // If this permission is to be granted to the system verifier and
9552                // this app is a verifier, then it gets the permission.
9553                allowed = true;
9554            }
9555            if (!allowed && (bp.protectionLevel
9556                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9557                    && isSystemApp(pkg)) {
9558                // Any pre-installed system app is allowed to get this permission.
9559                allowed = true;
9560            }
9561            if (!allowed && (bp.protectionLevel
9562                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9563                // For development permissions, a development permission
9564                // is granted only if it was already granted.
9565                allowed = origPermissions.hasInstallPermission(perm);
9566            }
9567        }
9568        return allowed;
9569    }
9570
9571    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9572        final int permCount = pkg.requestedPermissions.size();
9573        for (int j = 0; j < permCount; j++) {
9574            String requestedPermission = pkg.requestedPermissions.get(j);
9575            if (permission.equals(requestedPermission)) {
9576                return true;
9577            }
9578        }
9579        return false;
9580    }
9581
9582    final class ActivityIntentResolver
9583            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9584        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9585                boolean defaultOnly, int userId) {
9586            if (!sUserManager.exists(userId)) return null;
9587            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9588            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9589        }
9590
9591        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9592                int userId) {
9593            if (!sUserManager.exists(userId)) return null;
9594            mFlags = flags;
9595            return super.queryIntent(intent, resolvedType,
9596                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9597        }
9598
9599        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9600                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9601            if (!sUserManager.exists(userId)) return null;
9602            if (packageActivities == null) {
9603                return null;
9604            }
9605            mFlags = flags;
9606            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9607            final int N = packageActivities.size();
9608            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9609                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9610
9611            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9612            for (int i = 0; i < N; ++i) {
9613                intentFilters = packageActivities.get(i).intents;
9614                if (intentFilters != null && intentFilters.size() > 0) {
9615                    PackageParser.ActivityIntentInfo[] array =
9616                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9617                    intentFilters.toArray(array);
9618                    listCut.add(array);
9619                }
9620            }
9621            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9622        }
9623
9624        public final void addActivity(PackageParser.Activity a, String type) {
9625            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9626            mActivities.put(a.getComponentName(), a);
9627            if (DEBUG_SHOW_INFO)
9628                Log.v(
9629                TAG, "  " + type + " " +
9630                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9631            if (DEBUG_SHOW_INFO)
9632                Log.v(TAG, "    Class=" + a.info.name);
9633            final int NI = a.intents.size();
9634            for (int j=0; j<NI; j++) {
9635                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9636                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9637                    intent.setPriority(0);
9638                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9639                            + a.className + " with priority > 0, forcing to 0");
9640                }
9641                if (DEBUG_SHOW_INFO) {
9642                    Log.v(TAG, "    IntentFilter:");
9643                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9644                }
9645                if (!intent.debugCheck()) {
9646                    Log.w(TAG, "==> For Activity " + a.info.name);
9647                }
9648                addFilter(intent);
9649            }
9650        }
9651
9652        public final void removeActivity(PackageParser.Activity a, String type) {
9653            mActivities.remove(a.getComponentName());
9654            if (DEBUG_SHOW_INFO) {
9655                Log.v(TAG, "  " + type + " "
9656                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9657                                : a.info.name) + ":");
9658                Log.v(TAG, "    Class=" + a.info.name);
9659            }
9660            final int NI = a.intents.size();
9661            for (int j=0; j<NI; j++) {
9662                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9663                if (DEBUG_SHOW_INFO) {
9664                    Log.v(TAG, "    IntentFilter:");
9665                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9666                }
9667                removeFilter(intent);
9668            }
9669        }
9670
9671        @Override
9672        protected boolean allowFilterResult(
9673                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9674            ActivityInfo filterAi = filter.activity.info;
9675            for (int i=dest.size()-1; i>=0; i--) {
9676                ActivityInfo destAi = dest.get(i).activityInfo;
9677                if (destAi.name == filterAi.name
9678                        && destAi.packageName == filterAi.packageName) {
9679                    return false;
9680                }
9681            }
9682            return true;
9683        }
9684
9685        @Override
9686        protected ActivityIntentInfo[] newArray(int size) {
9687            return new ActivityIntentInfo[size];
9688        }
9689
9690        @Override
9691        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9692            if (!sUserManager.exists(userId)) return true;
9693            PackageParser.Package p = filter.activity.owner;
9694            if (p != null) {
9695                PackageSetting ps = (PackageSetting)p.mExtras;
9696                if (ps != null) {
9697                    // System apps are never considered stopped for purposes of
9698                    // filtering, because there may be no way for the user to
9699                    // actually re-launch them.
9700                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9701                            && ps.getStopped(userId);
9702                }
9703            }
9704            return false;
9705        }
9706
9707        @Override
9708        protected boolean isPackageForFilter(String packageName,
9709                PackageParser.ActivityIntentInfo info) {
9710            return packageName.equals(info.activity.owner.packageName);
9711        }
9712
9713        @Override
9714        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9715                int match, int userId) {
9716            if (!sUserManager.exists(userId)) return null;
9717            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9718                return null;
9719            }
9720            final PackageParser.Activity activity = info.activity;
9721            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9722            if (ps == null) {
9723                return null;
9724            }
9725            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9726                    ps.readUserState(userId), userId);
9727            if (ai == null) {
9728                return null;
9729            }
9730            final ResolveInfo res = new ResolveInfo();
9731            res.activityInfo = ai;
9732            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9733                res.filter = info;
9734            }
9735            if (info != null) {
9736                res.handleAllWebDataURI = info.handleAllWebDataURI();
9737            }
9738            res.priority = info.getPriority();
9739            res.preferredOrder = activity.owner.mPreferredOrder;
9740            //System.out.println("Result: " + res.activityInfo.className +
9741            //                   " = " + res.priority);
9742            res.match = match;
9743            res.isDefault = info.hasDefault;
9744            res.labelRes = info.labelRes;
9745            res.nonLocalizedLabel = info.nonLocalizedLabel;
9746            if (userNeedsBadging(userId)) {
9747                res.noResourceId = true;
9748            } else {
9749                res.icon = info.icon;
9750            }
9751            res.iconResourceId = info.icon;
9752            res.system = res.activityInfo.applicationInfo.isSystemApp();
9753            return res;
9754        }
9755
9756        @Override
9757        protected void sortResults(List<ResolveInfo> results) {
9758            Collections.sort(results, mResolvePrioritySorter);
9759        }
9760
9761        @Override
9762        protected void dumpFilter(PrintWriter out, String prefix,
9763                PackageParser.ActivityIntentInfo filter) {
9764            out.print(prefix); out.print(
9765                    Integer.toHexString(System.identityHashCode(filter.activity)));
9766                    out.print(' ');
9767                    filter.activity.printComponentShortName(out);
9768                    out.print(" filter ");
9769                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9770        }
9771
9772        @Override
9773        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9774            return filter.activity;
9775        }
9776
9777        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9778            PackageParser.Activity activity = (PackageParser.Activity)label;
9779            out.print(prefix); out.print(
9780                    Integer.toHexString(System.identityHashCode(activity)));
9781                    out.print(' ');
9782                    activity.printComponentShortName(out);
9783            if (count > 1) {
9784                out.print(" ("); out.print(count); out.print(" filters)");
9785            }
9786            out.println();
9787        }
9788
9789//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9790//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9791//            final List<ResolveInfo> retList = Lists.newArrayList();
9792//            while (i.hasNext()) {
9793//                final ResolveInfo resolveInfo = i.next();
9794//                if (isEnabledLP(resolveInfo.activityInfo)) {
9795//                    retList.add(resolveInfo);
9796//                }
9797//            }
9798//            return retList;
9799//        }
9800
9801        // Keys are String (activity class name), values are Activity.
9802        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9803                = new ArrayMap<ComponentName, PackageParser.Activity>();
9804        private int mFlags;
9805    }
9806
9807    private final class ServiceIntentResolver
9808            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9809        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9810                boolean defaultOnly, int userId) {
9811            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9812            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9813        }
9814
9815        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9816                int userId) {
9817            if (!sUserManager.exists(userId)) return null;
9818            mFlags = flags;
9819            return super.queryIntent(intent, resolvedType,
9820                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9821        }
9822
9823        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9824                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9825            if (!sUserManager.exists(userId)) return null;
9826            if (packageServices == null) {
9827                return null;
9828            }
9829            mFlags = flags;
9830            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9831            final int N = packageServices.size();
9832            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9833                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9834
9835            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9836            for (int i = 0; i < N; ++i) {
9837                intentFilters = packageServices.get(i).intents;
9838                if (intentFilters != null && intentFilters.size() > 0) {
9839                    PackageParser.ServiceIntentInfo[] array =
9840                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9841                    intentFilters.toArray(array);
9842                    listCut.add(array);
9843                }
9844            }
9845            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9846        }
9847
9848        public final void addService(PackageParser.Service s) {
9849            mServices.put(s.getComponentName(), s);
9850            if (DEBUG_SHOW_INFO) {
9851                Log.v(TAG, "  "
9852                        + (s.info.nonLocalizedLabel != null
9853                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9854                Log.v(TAG, "    Class=" + s.info.name);
9855            }
9856            final int NI = s.intents.size();
9857            int j;
9858            for (j=0; j<NI; j++) {
9859                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9860                if (DEBUG_SHOW_INFO) {
9861                    Log.v(TAG, "    IntentFilter:");
9862                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9863                }
9864                if (!intent.debugCheck()) {
9865                    Log.w(TAG, "==> For Service " + s.info.name);
9866                }
9867                addFilter(intent);
9868            }
9869        }
9870
9871        public final void removeService(PackageParser.Service s) {
9872            mServices.remove(s.getComponentName());
9873            if (DEBUG_SHOW_INFO) {
9874                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9875                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9876                Log.v(TAG, "    Class=" + s.info.name);
9877            }
9878            final int NI = s.intents.size();
9879            int j;
9880            for (j=0; j<NI; j++) {
9881                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9882                if (DEBUG_SHOW_INFO) {
9883                    Log.v(TAG, "    IntentFilter:");
9884                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9885                }
9886                removeFilter(intent);
9887            }
9888        }
9889
9890        @Override
9891        protected boolean allowFilterResult(
9892                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9893            ServiceInfo filterSi = filter.service.info;
9894            for (int i=dest.size()-1; i>=0; i--) {
9895                ServiceInfo destAi = dest.get(i).serviceInfo;
9896                if (destAi.name == filterSi.name
9897                        && destAi.packageName == filterSi.packageName) {
9898                    return false;
9899                }
9900            }
9901            return true;
9902        }
9903
9904        @Override
9905        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9906            return new PackageParser.ServiceIntentInfo[size];
9907        }
9908
9909        @Override
9910        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9911            if (!sUserManager.exists(userId)) return true;
9912            PackageParser.Package p = filter.service.owner;
9913            if (p != null) {
9914                PackageSetting ps = (PackageSetting)p.mExtras;
9915                if (ps != null) {
9916                    // System apps are never considered stopped for purposes of
9917                    // filtering, because there may be no way for the user to
9918                    // actually re-launch them.
9919                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9920                            && ps.getStopped(userId);
9921                }
9922            }
9923            return false;
9924        }
9925
9926        @Override
9927        protected boolean isPackageForFilter(String packageName,
9928                PackageParser.ServiceIntentInfo info) {
9929            return packageName.equals(info.service.owner.packageName);
9930        }
9931
9932        @Override
9933        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9934                int match, int userId) {
9935            if (!sUserManager.exists(userId)) return null;
9936            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9937            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9938                return null;
9939            }
9940            final PackageParser.Service service = info.service;
9941            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9942            if (ps == null) {
9943                return null;
9944            }
9945            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9946                    ps.readUserState(userId), userId);
9947            if (si == null) {
9948                return null;
9949            }
9950            final ResolveInfo res = new ResolveInfo();
9951            res.serviceInfo = si;
9952            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9953                res.filter = filter;
9954            }
9955            res.priority = info.getPriority();
9956            res.preferredOrder = service.owner.mPreferredOrder;
9957            res.match = match;
9958            res.isDefault = info.hasDefault;
9959            res.labelRes = info.labelRes;
9960            res.nonLocalizedLabel = info.nonLocalizedLabel;
9961            res.icon = info.icon;
9962            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9963            return res;
9964        }
9965
9966        @Override
9967        protected void sortResults(List<ResolveInfo> results) {
9968            Collections.sort(results, mResolvePrioritySorter);
9969        }
9970
9971        @Override
9972        protected void dumpFilter(PrintWriter out, String prefix,
9973                PackageParser.ServiceIntentInfo filter) {
9974            out.print(prefix); out.print(
9975                    Integer.toHexString(System.identityHashCode(filter.service)));
9976                    out.print(' ');
9977                    filter.service.printComponentShortName(out);
9978                    out.print(" filter ");
9979                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9980        }
9981
9982        @Override
9983        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9984            return filter.service;
9985        }
9986
9987        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9988            PackageParser.Service service = (PackageParser.Service)label;
9989            out.print(prefix); out.print(
9990                    Integer.toHexString(System.identityHashCode(service)));
9991                    out.print(' ');
9992                    service.printComponentShortName(out);
9993            if (count > 1) {
9994                out.print(" ("); out.print(count); out.print(" filters)");
9995            }
9996            out.println();
9997        }
9998
9999//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10000//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10001//            final List<ResolveInfo> retList = Lists.newArrayList();
10002//            while (i.hasNext()) {
10003//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10004//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10005//                    retList.add(resolveInfo);
10006//                }
10007//            }
10008//            return retList;
10009//        }
10010
10011        // Keys are String (activity class name), values are Activity.
10012        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10013                = new ArrayMap<ComponentName, PackageParser.Service>();
10014        private int mFlags;
10015    };
10016
10017    private final class ProviderIntentResolver
10018            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10019        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10020                boolean defaultOnly, int userId) {
10021            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10022            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10023        }
10024
10025        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10026                int userId) {
10027            if (!sUserManager.exists(userId))
10028                return null;
10029            mFlags = flags;
10030            return super.queryIntent(intent, resolvedType,
10031                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10032        }
10033
10034        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10035                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10036            if (!sUserManager.exists(userId))
10037                return null;
10038            if (packageProviders == null) {
10039                return null;
10040            }
10041            mFlags = flags;
10042            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10043            final int N = packageProviders.size();
10044            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10045                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10046
10047            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10048            for (int i = 0; i < N; ++i) {
10049                intentFilters = packageProviders.get(i).intents;
10050                if (intentFilters != null && intentFilters.size() > 0) {
10051                    PackageParser.ProviderIntentInfo[] array =
10052                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10053                    intentFilters.toArray(array);
10054                    listCut.add(array);
10055                }
10056            }
10057            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10058        }
10059
10060        public final void addProvider(PackageParser.Provider p) {
10061            if (mProviders.containsKey(p.getComponentName())) {
10062                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10063                return;
10064            }
10065
10066            mProviders.put(p.getComponentName(), p);
10067            if (DEBUG_SHOW_INFO) {
10068                Log.v(TAG, "  "
10069                        + (p.info.nonLocalizedLabel != null
10070                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10071                Log.v(TAG, "    Class=" + p.info.name);
10072            }
10073            final int NI = p.intents.size();
10074            int j;
10075            for (j = 0; j < NI; j++) {
10076                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10077                if (DEBUG_SHOW_INFO) {
10078                    Log.v(TAG, "    IntentFilter:");
10079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10080                }
10081                if (!intent.debugCheck()) {
10082                    Log.w(TAG, "==> For Provider " + p.info.name);
10083                }
10084                addFilter(intent);
10085            }
10086        }
10087
10088        public final void removeProvider(PackageParser.Provider p) {
10089            mProviders.remove(p.getComponentName());
10090            if (DEBUG_SHOW_INFO) {
10091                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10092                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10093                Log.v(TAG, "    Class=" + p.info.name);
10094            }
10095            final int NI = p.intents.size();
10096            int j;
10097            for (j = 0; j < NI; j++) {
10098                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10099                if (DEBUG_SHOW_INFO) {
10100                    Log.v(TAG, "    IntentFilter:");
10101                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10102                }
10103                removeFilter(intent);
10104            }
10105        }
10106
10107        @Override
10108        protected boolean allowFilterResult(
10109                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10110            ProviderInfo filterPi = filter.provider.info;
10111            for (int i = dest.size() - 1; i >= 0; i--) {
10112                ProviderInfo destPi = dest.get(i).providerInfo;
10113                if (destPi.name == filterPi.name
10114                        && destPi.packageName == filterPi.packageName) {
10115                    return false;
10116                }
10117            }
10118            return true;
10119        }
10120
10121        @Override
10122        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10123            return new PackageParser.ProviderIntentInfo[size];
10124        }
10125
10126        @Override
10127        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10128            if (!sUserManager.exists(userId))
10129                return true;
10130            PackageParser.Package p = filter.provider.owner;
10131            if (p != null) {
10132                PackageSetting ps = (PackageSetting) p.mExtras;
10133                if (ps != null) {
10134                    // System apps are never considered stopped for purposes of
10135                    // filtering, because there may be no way for the user to
10136                    // actually re-launch them.
10137                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10138                            && ps.getStopped(userId);
10139                }
10140            }
10141            return false;
10142        }
10143
10144        @Override
10145        protected boolean isPackageForFilter(String packageName,
10146                PackageParser.ProviderIntentInfo info) {
10147            return packageName.equals(info.provider.owner.packageName);
10148        }
10149
10150        @Override
10151        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10152                int match, int userId) {
10153            if (!sUserManager.exists(userId))
10154                return null;
10155            final PackageParser.ProviderIntentInfo info = filter;
10156            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10157                return null;
10158            }
10159            final PackageParser.Provider provider = info.provider;
10160            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10161            if (ps == null) {
10162                return null;
10163            }
10164            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10165                    ps.readUserState(userId), userId);
10166            if (pi == null) {
10167                return null;
10168            }
10169            final ResolveInfo res = new ResolveInfo();
10170            res.providerInfo = pi;
10171            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10172                res.filter = filter;
10173            }
10174            res.priority = info.getPriority();
10175            res.preferredOrder = provider.owner.mPreferredOrder;
10176            res.match = match;
10177            res.isDefault = info.hasDefault;
10178            res.labelRes = info.labelRes;
10179            res.nonLocalizedLabel = info.nonLocalizedLabel;
10180            res.icon = info.icon;
10181            res.system = res.providerInfo.applicationInfo.isSystemApp();
10182            return res;
10183        }
10184
10185        @Override
10186        protected void sortResults(List<ResolveInfo> results) {
10187            Collections.sort(results, mResolvePrioritySorter);
10188        }
10189
10190        @Override
10191        protected void dumpFilter(PrintWriter out, String prefix,
10192                PackageParser.ProviderIntentInfo filter) {
10193            out.print(prefix);
10194            out.print(
10195                    Integer.toHexString(System.identityHashCode(filter.provider)));
10196            out.print(' ');
10197            filter.provider.printComponentShortName(out);
10198            out.print(" filter ");
10199            out.println(Integer.toHexString(System.identityHashCode(filter)));
10200        }
10201
10202        @Override
10203        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10204            return filter.provider;
10205        }
10206
10207        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10208            PackageParser.Provider provider = (PackageParser.Provider)label;
10209            out.print(prefix); out.print(
10210                    Integer.toHexString(System.identityHashCode(provider)));
10211                    out.print(' ');
10212                    provider.printComponentShortName(out);
10213            if (count > 1) {
10214                out.print(" ("); out.print(count); out.print(" filters)");
10215            }
10216            out.println();
10217        }
10218
10219        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10220                = new ArrayMap<ComponentName, PackageParser.Provider>();
10221        private int mFlags;
10222    }
10223
10224    private static final class EphemeralIntentResolver
10225            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10226        @Override
10227        protected EphemeralResolveIntentInfo[] newArray(int size) {
10228            return new EphemeralResolveIntentInfo[size];
10229        }
10230
10231        @Override
10232        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10233            return true;
10234        }
10235
10236        @Override
10237        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10238                int userId) {
10239            if (!sUserManager.exists(userId)) {
10240                return null;
10241            }
10242            return info.getEphemeralResolveInfo();
10243        }
10244    }
10245
10246    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10247            new Comparator<ResolveInfo>() {
10248        public int compare(ResolveInfo r1, ResolveInfo r2) {
10249            int v1 = r1.priority;
10250            int v2 = r2.priority;
10251            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10252            if (v1 != v2) {
10253                return (v1 > v2) ? -1 : 1;
10254            }
10255            v1 = r1.preferredOrder;
10256            v2 = r2.preferredOrder;
10257            if (v1 != v2) {
10258                return (v1 > v2) ? -1 : 1;
10259            }
10260            if (r1.isDefault != r2.isDefault) {
10261                return r1.isDefault ? -1 : 1;
10262            }
10263            v1 = r1.match;
10264            v2 = r2.match;
10265            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10266            if (v1 != v2) {
10267                return (v1 > v2) ? -1 : 1;
10268            }
10269            if (r1.system != r2.system) {
10270                return r1.system ? -1 : 1;
10271            }
10272            if (r1.activityInfo != null) {
10273                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10274            }
10275            if (r1.serviceInfo != null) {
10276                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10277            }
10278            if (r1.providerInfo != null) {
10279                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10280            }
10281            return 0;
10282        }
10283    };
10284
10285    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10286            new Comparator<ProviderInfo>() {
10287        public int compare(ProviderInfo p1, ProviderInfo p2) {
10288            final int v1 = p1.initOrder;
10289            final int v2 = p2.initOrder;
10290            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10291        }
10292    };
10293
10294    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10295            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10296            final int[] userIds) {
10297        mHandler.post(new Runnable() {
10298            @Override
10299            public void run() {
10300                try {
10301                    final IActivityManager am = ActivityManagerNative.getDefault();
10302                    if (am == null) return;
10303                    final int[] resolvedUserIds;
10304                    if (userIds == null) {
10305                        resolvedUserIds = am.getRunningUserIds();
10306                    } else {
10307                        resolvedUserIds = userIds;
10308                    }
10309                    for (int id : resolvedUserIds) {
10310                        final Intent intent = new Intent(action,
10311                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10312                        if (extras != null) {
10313                            intent.putExtras(extras);
10314                        }
10315                        if (targetPkg != null) {
10316                            intent.setPackage(targetPkg);
10317                        }
10318                        // Modify the UID when posting to other users
10319                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10320                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10321                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10322                            intent.putExtra(Intent.EXTRA_UID, uid);
10323                        }
10324                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10325                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10326                        if (DEBUG_BROADCASTS) {
10327                            RuntimeException here = new RuntimeException("here");
10328                            here.fillInStackTrace();
10329                            Slog.d(TAG, "Sending to user " + id + ": "
10330                                    + intent.toShortString(false, true, false, false)
10331                                    + " " + intent.getExtras(), here);
10332                        }
10333                        am.broadcastIntent(null, intent, null, finishedReceiver,
10334                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10335                                null, finishedReceiver != null, false, id);
10336                    }
10337                } catch (RemoteException ex) {
10338                }
10339            }
10340        });
10341    }
10342
10343    /**
10344     * Check if the external storage media is available. This is true if there
10345     * is a mounted external storage medium or if the external storage is
10346     * emulated.
10347     */
10348    private boolean isExternalMediaAvailable() {
10349        return mMediaMounted || Environment.isExternalStorageEmulated();
10350    }
10351
10352    @Override
10353    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10354        // writer
10355        synchronized (mPackages) {
10356            if (!isExternalMediaAvailable()) {
10357                // If the external storage is no longer mounted at this point,
10358                // the caller may not have been able to delete all of this
10359                // packages files and can not delete any more.  Bail.
10360                return null;
10361            }
10362            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10363            if (lastPackage != null) {
10364                pkgs.remove(lastPackage);
10365            }
10366            if (pkgs.size() > 0) {
10367                return pkgs.get(0);
10368            }
10369        }
10370        return null;
10371    }
10372
10373    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10374        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10375                userId, andCode ? 1 : 0, packageName);
10376        if (mSystemReady) {
10377            msg.sendToTarget();
10378        } else {
10379            if (mPostSystemReadyMessages == null) {
10380                mPostSystemReadyMessages = new ArrayList<>();
10381            }
10382            mPostSystemReadyMessages.add(msg);
10383        }
10384    }
10385
10386    void startCleaningPackages() {
10387        // reader
10388        synchronized (mPackages) {
10389            if (!isExternalMediaAvailable()) {
10390                return;
10391            }
10392            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10393                return;
10394            }
10395        }
10396        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10397        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10398        IActivityManager am = ActivityManagerNative.getDefault();
10399        if (am != null) {
10400            try {
10401                am.startService(null, intent, null, mContext.getOpPackageName(),
10402                        UserHandle.USER_SYSTEM);
10403            } catch (RemoteException e) {
10404            }
10405        }
10406    }
10407
10408    @Override
10409    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10410            int installFlags, String installerPackageName, int userId) {
10411        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10412
10413        final int callingUid = Binder.getCallingUid();
10414        enforceCrossUserPermission(callingUid, userId,
10415                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10416
10417        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10418            try {
10419                if (observer != null) {
10420                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10421                }
10422            } catch (RemoteException re) {
10423            }
10424            return;
10425        }
10426
10427        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10428            installFlags |= PackageManager.INSTALL_FROM_ADB;
10429
10430        } else {
10431            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10432            // about installerPackageName.
10433
10434            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10435            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10436        }
10437
10438        UserHandle user;
10439        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10440            user = UserHandle.ALL;
10441        } else {
10442            user = new UserHandle(userId);
10443        }
10444
10445        // Only system components can circumvent runtime permissions when installing.
10446        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10447                && mContext.checkCallingOrSelfPermission(Manifest.permission
10448                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10449            throw new SecurityException("You need the "
10450                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10451                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10452        }
10453
10454        final File originFile = new File(originPath);
10455        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10456
10457        final Message msg = mHandler.obtainMessage(INIT_COPY);
10458        final VerificationInfo verificationInfo = new VerificationInfo(
10459                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10460        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10461                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10462                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10463        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10464        msg.obj = params;
10465
10466        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10467                System.identityHashCode(msg.obj));
10468        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10469                System.identityHashCode(msg.obj));
10470
10471        mHandler.sendMessage(msg);
10472    }
10473
10474    void installStage(String packageName, File stagedDir, String stagedCid,
10475            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10476            String installerPackageName, int installerUid, UserHandle user) {
10477        if (DEBUG_EPHEMERAL) {
10478            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10479                Slog.d(TAG, "Ephemeral install of " + packageName);
10480            }
10481        }
10482        final VerificationInfo verificationInfo = new VerificationInfo(
10483                sessionParams.originatingUri, sessionParams.referrerUri,
10484                sessionParams.originatingUid, installerUid);
10485
10486        final OriginInfo origin;
10487        if (stagedDir != null) {
10488            origin = OriginInfo.fromStagedFile(stagedDir);
10489        } else {
10490            origin = OriginInfo.fromStagedContainer(stagedCid);
10491        }
10492
10493        final Message msg = mHandler.obtainMessage(INIT_COPY);
10494        final InstallParams params = new InstallParams(origin, null, observer,
10495                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10496                verificationInfo, user, sessionParams.abiOverride,
10497                sessionParams.grantedRuntimePermissions);
10498        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10499        msg.obj = params;
10500
10501        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10502                System.identityHashCode(msg.obj));
10503        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10504                System.identityHashCode(msg.obj));
10505
10506        mHandler.sendMessage(msg);
10507    }
10508
10509    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10510            int userId) {
10511        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10512        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10513    }
10514
10515    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10516            int appId, int userId) {
10517        Bundle extras = new Bundle(1);
10518        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10519
10520        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10521                packageName, extras, 0, null, null, new int[] {userId});
10522        try {
10523            IActivityManager am = ActivityManagerNative.getDefault();
10524            if (isSystem && am.isUserRunning(userId, 0)) {
10525                // The just-installed/enabled app is bundled on the system, so presumed
10526                // to be able to run automatically without needing an explicit launch.
10527                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10528                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10529                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10530                        .setPackage(packageName);
10531                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10532                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10533            }
10534        } catch (RemoteException e) {
10535            // shouldn't happen
10536            Slog.w(TAG, "Unable to bootstrap installed package", e);
10537        }
10538    }
10539
10540    @Override
10541    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10542            int userId) {
10543        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10544        PackageSetting pkgSetting;
10545        final int uid = Binder.getCallingUid();
10546        enforceCrossUserPermission(uid, userId,
10547                true /* requireFullPermission */, true /* checkShell */,
10548                "setApplicationHiddenSetting for user " + userId);
10549
10550        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10551            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10552            return false;
10553        }
10554
10555        long callingId = Binder.clearCallingIdentity();
10556        try {
10557            boolean sendAdded = false;
10558            boolean sendRemoved = false;
10559            // writer
10560            synchronized (mPackages) {
10561                pkgSetting = mSettings.mPackages.get(packageName);
10562                if (pkgSetting == null) {
10563                    return false;
10564                }
10565                if (pkgSetting.getHidden(userId) != hidden) {
10566                    pkgSetting.setHidden(hidden, userId);
10567                    mSettings.writePackageRestrictionsLPr(userId);
10568                    if (hidden) {
10569                        sendRemoved = true;
10570                    } else {
10571                        sendAdded = true;
10572                    }
10573                }
10574            }
10575            if (sendAdded) {
10576                sendPackageAddedForUser(packageName, pkgSetting, userId);
10577                return true;
10578            }
10579            if (sendRemoved) {
10580                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10581                        "hiding pkg");
10582                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10583                return true;
10584            }
10585        } finally {
10586            Binder.restoreCallingIdentity(callingId);
10587        }
10588        return false;
10589    }
10590
10591    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10592            int userId) {
10593        final PackageRemovedInfo info = new PackageRemovedInfo();
10594        info.removedPackage = packageName;
10595        info.removedUsers = new int[] {userId};
10596        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10597        info.sendPackageRemovedBroadcasts();
10598    }
10599
10600    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10601        if (pkgList.length > 0) {
10602            Bundle extras = new Bundle(1);
10603            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10604
10605            sendPackageBroadcast(
10606                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10607                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10608                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10609                    new int[] {userId});
10610        }
10611    }
10612
10613    /**
10614     * Returns true if application is not found or there was an error. Otherwise it returns
10615     * the hidden state of the package for the given user.
10616     */
10617    @Override
10618    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10619        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10620        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10621                true /* requireFullPermission */, false /* checkShell */,
10622                "getApplicationHidden for user " + userId);
10623        PackageSetting pkgSetting;
10624        long callingId = Binder.clearCallingIdentity();
10625        try {
10626            // writer
10627            synchronized (mPackages) {
10628                pkgSetting = mSettings.mPackages.get(packageName);
10629                if (pkgSetting == null) {
10630                    return true;
10631                }
10632                return pkgSetting.getHidden(userId);
10633            }
10634        } finally {
10635            Binder.restoreCallingIdentity(callingId);
10636        }
10637    }
10638
10639    /**
10640     * @hide
10641     */
10642    @Override
10643    public int installExistingPackageAsUser(String packageName, int userId) {
10644        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10645                null);
10646        PackageSetting pkgSetting;
10647        final int uid = Binder.getCallingUid();
10648        enforceCrossUserPermission(uid, userId,
10649                true /* requireFullPermission */, true /* checkShell */,
10650                "installExistingPackage for user " + userId);
10651        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10652            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10653        }
10654
10655        long callingId = Binder.clearCallingIdentity();
10656        try {
10657            boolean installed = false;
10658
10659            // writer
10660            synchronized (mPackages) {
10661                pkgSetting = mSettings.mPackages.get(packageName);
10662                if (pkgSetting == null) {
10663                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10664                }
10665                if (!pkgSetting.getInstalled(userId)) {
10666                    pkgSetting.setInstalled(true, userId);
10667                    pkgSetting.setHidden(false, userId);
10668                    mSettings.writePackageRestrictionsLPr(userId);
10669                    installed = true;
10670                }
10671            }
10672
10673            if (installed) {
10674                if (pkgSetting.pkg != null) {
10675                    prepareAppDataAfterInstall(pkgSetting.pkg);
10676                }
10677                sendPackageAddedForUser(packageName, pkgSetting, userId);
10678            }
10679        } finally {
10680            Binder.restoreCallingIdentity(callingId);
10681        }
10682
10683        return PackageManager.INSTALL_SUCCEEDED;
10684    }
10685
10686    boolean isUserRestricted(int userId, String restrictionKey) {
10687        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10688        if (restrictions.getBoolean(restrictionKey, false)) {
10689            Log.w(TAG, "User is restricted: " + restrictionKey);
10690            return true;
10691        }
10692        return false;
10693    }
10694
10695    @Override
10696    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10697            int userId) {
10698        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10699        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10700                true /* requireFullPermission */, true /* checkShell */,
10701                "setPackagesSuspended for user " + userId);
10702
10703        if (ArrayUtils.isEmpty(packageNames)) {
10704            return packageNames;
10705        }
10706
10707        // List of package names for whom the suspended state has changed.
10708        List<String> changedPackages = new ArrayList<>(packageNames.length);
10709        // List of package names for whom the suspended state is not set as requested in this
10710        // method.
10711        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10712        for (int i = 0; i < packageNames.length; i++) {
10713            String packageName = packageNames[i];
10714            long callingId = Binder.clearCallingIdentity();
10715            try {
10716                boolean changed = false;
10717                final int appId;
10718                synchronized (mPackages) {
10719                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10720                    if (pkgSetting == null) {
10721                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10722                                + "\". Skipping suspending/un-suspending.");
10723                        unactionedPackages.add(packageName);
10724                        continue;
10725                    }
10726                    appId = pkgSetting.appId;
10727                    if (pkgSetting.getSuspended(userId) != suspended) {
10728                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10729                            unactionedPackages.add(packageName);
10730                            continue;
10731                        }
10732                        pkgSetting.setSuspended(suspended, userId);
10733                        mSettings.writePackageRestrictionsLPr(userId);
10734                        changed = true;
10735                        changedPackages.add(packageName);
10736                    }
10737                }
10738
10739                if (changed && suspended) {
10740                    killApplication(packageName, UserHandle.getUid(userId, appId),
10741                            "suspending package");
10742                }
10743            } finally {
10744                Binder.restoreCallingIdentity(callingId);
10745            }
10746        }
10747
10748        if (!changedPackages.isEmpty()) {
10749            sendPackagesSuspendedForUser(changedPackages.toArray(
10750                    new String[changedPackages.size()]), userId, suspended);
10751        }
10752
10753        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10754    }
10755
10756    @Override
10757    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10759                true /* requireFullPermission */, false /* checkShell */,
10760                "isPackageSuspendedForUser for user " + userId);
10761        synchronized (mPackages) {
10762            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10763            return pkgSetting != null && pkgSetting.getSuspended(userId);
10764        }
10765    }
10766
10767    // TODO: investigate and add more restrictions for suspending crucial packages.
10768    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10769        if (isPackageDeviceAdmin(packageName, userId)) {
10770            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10771                    + "\": has active device admin");
10772            return false;
10773        }
10774
10775        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10776        if (packageName.equals(activeLauncherPackageName)) {
10777            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10778                    + "\" because it is set as the active launcher");
10779            return false;
10780        }
10781
10782        final PackageParser.Package pkg = mPackages.get(packageName);
10783        if (pkg != null && isPrivilegedApp(pkg)) {
10784            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10785                    + "\" because it is a privileged app");
10786            return false;
10787        }
10788
10789        return true;
10790    }
10791
10792    private String getActiveLauncherPackageName(int userId) {
10793        Intent intent = new Intent(Intent.ACTION_MAIN);
10794        intent.addCategory(Intent.CATEGORY_HOME);
10795        ResolveInfo resolveInfo = resolveIntent(
10796                intent,
10797                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10798                PackageManager.MATCH_DEFAULT_ONLY,
10799                userId);
10800
10801        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10802    }
10803
10804    @Override
10805    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10806        mContext.enforceCallingOrSelfPermission(
10807                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10808                "Only package verification agents can verify applications");
10809
10810        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10811        final PackageVerificationResponse response = new PackageVerificationResponse(
10812                verificationCode, Binder.getCallingUid());
10813        msg.arg1 = id;
10814        msg.obj = response;
10815        mHandler.sendMessage(msg);
10816    }
10817
10818    @Override
10819    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10820            long millisecondsToDelay) {
10821        mContext.enforceCallingOrSelfPermission(
10822                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10823                "Only package verification agents can extend verification timeouts");
10824
10825        final PackageVerificationState state = mPendingVerification.get(id);
10826        final PackageVerificationResponse response = new PackageVerificationResponse(
10827                verificationCodeAtTimeout, Binder.getCallingUid());
10828
10829        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10830            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10831        }
10832        if (millisecondsToDelay < 0) {
10833            millisecondsToDelay = 0;
10834        }
10835        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10836                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10837            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10838        }
10839
10840        if ((state != null) && !state.timeoutExtended()) {
10841            state.extendTimeout();
10842
10843            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10844            msg.arg1 = id;
10845            msg.obj = response;
10846            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10847        }
10848    }
10849
10850    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10851            int verificationCode, UserHandle user) {
10852        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10853        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10854        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10855        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10856        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10857
10858        mContext.sendBroadcastAsUser(intent, user,
10859                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10860    }
10861
10862    private ComponentName matchComponentForVerifier(String packageName,
10863            List<ResolveInfo> receivers) {
10864        ActivityInfo targetReceiver = null;
10865
10866        final int NR = receivers.size();
10867        for (int i = 0; i < NR; i++) {
10868            final ResolveInfo info = receivers.get(i);
10869            if (info.activityInfo == null) {
10870                continue;
10871            }
10872
10873            if (packageName.equals(info.activityInfo.packageName)) {
10874                targetReceiver = info.activityInfo;
10875                break;
10876            }
10877        }
10878
10879        if (targetReceiver == null) {
10880            return null;
10881        }
10882
10883        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10884    }
10885
10886    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10887            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10888        if (pkgInfo.verifiers.length == 0) {
10889            return null;
10890        }
10891
10892        final int N = pkgInfo.verifiers.length;
10893        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10894        for (int i = 0; i < N; i++) {
10895            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10896
10897            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10898                    receivers);
10899            if (comp == null) {
10900                continue;
10901            }
10902
10903            final int verifierUid = getUidForVerifier(verifierInfo);
10904            if (verifierUid == -1) {
10905                continue;
10906            }
10907
10908            if (DEBUG_VERIFY) {
10909                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10910                        + " with the correct signature");
10911            }
10912            sufficientVerifiers.add(comp);
10913            verificationState.addSufficientVerifier(verifierUid);
10914        }
10915
10916        return sufficientVerifiers;
10917    }
10918
10919    private int getUidForVerifier(VerifierInfo verifierInfo) {
10920        synchronized (mPackages) {
10921            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10922            if (pkg == null) {
10923                return -1;
10924            } else if (pkg.mSignatures.length != 1) {
10925                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10926                        + " has more than one signature; ignoring");
10927                return -1;
10928            }
10929
10930            /*
10931             * If the public key of the package's signature does not match
10932             * our expected public key, then this is a different package and
10933             * we should skip.
10934             */
10935
10936            final byte[] expectedPublicKey;
10937            try {
10938                final Signature verifierSig = pkg.mSignatures[0];
10939                final PublicKey publicKey = verifierSig.getPublicKey();
10940                expectedPublicKey = publicKey.getEncoded();
10941            } catch (CertificateException e) {
10942                return -1;
10943            }
10944
10945            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10946
10947            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10948                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10949                        + " does not have the expected public key; ignoring");
10950                return -1;
10951            }
10952
10953            return pkg.applicationInfo.uid;
10954        }
10955    }
10956
10957    @Override
10958    public void finishPackageInstall(int token) {
10959        enforceSystemOrRoot("Only the system is allowed to finish installs");
10960
10961        if (DEBUG_INSTALL) {
10962            Slog.v(TAG, "BM finishing package install for " + token);
10963        }
10964        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10965
10966        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10967        mHandler.sendMessage(msg);
10968    }
10969
10970    /**
10971     * Get the verification agent timeout.
10972     *
10973     * @return verification timeout in milliseconds
10974     */
10975    private long getVerificationTimeout() {
10976        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10977                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10978                DEFAULT_VERIFICATION_TIMEOUT);
10979    }
10980
10981    /**
10982     * Get the default verification agent response code.
10983     *
10984     * @return default verification response code
10985     */
10986    private int getDefaultVerificationResponse() {
10987        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10988                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10989                DEFAULT_VERIFICATION_RESPONSE);
10990    }
10991
10992    /**
10993     * Check whether or not package verification has been enabled.
10994     *
10995     * @return true if verification should be performed
10996     */
10997    private boolean isVerificationEnabled(int userId, int installFlags) {
10998        if (!DEFAULT_VERIFY_ENABLE) {
10999            return false;
11000        }
11001        // Ephemeral apps don't get the full verification treatment
11002        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11003            if (DEBUG_EPHEMERAL) {
11004                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11005            }
11006            return false;
11007        }
11008
11009        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11010
11011        // Check if installing from ADB
11012        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11013            // Do not run verification in a test harness environment
11014            if (ActivityManager.isRunningInTestHarness()) {
11015                return false;
11016            }
11017            if (ensureVerifyAppsEnabled) {
11018                return true;
11019            }
11020            // Check if the developer does not want package verification for ADB installs
11021            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11022                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11023                return false;
11024            }
11025        }
11026
11027        if (ensureVerifyAppsEnabled) {
11028            return true;
11029        }
11030
11031        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11032                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11033    }
11034
11035    @Override
11036    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11037            throws RemoteException {
11038        mContext.enforceCallingOrSelfPermission(
11039                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11040                "Only intentfilter verification agents can verify applications");
11041
11042        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11043        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11044                Binder.getCallingUid(), verificationCode, failedDomains);
11045        msg.arg1 = id;
11046        msg.obj = response;
11047        mHandler.sendMessage(msg);
11048    }
11049
11050    @Override
11051    public int getIntentVerificationStatus(String packageName, int userId) {
11052        synchronized (mPackages) {
11053            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11054        }
11055    }
11056
11057    @Override
11058    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11059        mContext.enforceCallingOrSelfPermission(
11060                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11061
11062        boolean result = false;
11063        synchronized (mPackages) {
11064            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11065        }
11066        if (result) {
11067            scheduleWritePackageRestrictionsLocked(userId);
11068        }
11069        return result;
11070    }
11071
11072    @Override
11073    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11074        synchronized (mPackages) {
11075            return mSettings.getIntentFilterVerificationsLPr(packageName);
11076        }
11077    }
11078
11079    @Override
11080    public List<IntentFilter> getAllIntentFilters(String packageName) {
11081        if (TextUtils.isEmpty(packageName)) {
11082            return Collections.<IntentFilter>emptyList();
11083        }
11084        synchronized (mPackages) {
11085            PackageParser.Package pkg = mPackages.get(packageName);
11086            if (pkg == null || pkg.activities == null) {
11087                return Collections.<IntentFilter>emptyList();
11088            }
11089            final int count = pkg.activities.size();
11090            ArrayList<IntentFilter> result = new ArrayList<>();
11091            for (int n=0; n<count; n++) {
11092                PackageParser.Activity activity = pkg.activities.get(n);
11093                if (activity.intents != null && activity.intents.size() > 0) {
11094                    result.addAll(activity.intents);
11095                }
11096            }
11097            return result;
11098        }
11099    }
11100
11101    @Override
11102    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11103        mContext.enforceCallingOrSelfPermission(
11104                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11105
11106        synchronized (mPackages) {
11107            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11108            if (packageName != null) {
11109                result |= updateIntentVerificationStatus(packageName,
11110                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11111                        userId);
11112                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11113                        packageName, userId);
11114            }
11115            return result;
11116        }
11117    }
11118
11119    @Override
11120    public String getDefaultBrowserPackageName(int userId) {
11121        synchronized (mPackages) {
11122            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11123        }
11124    }
11125
11126    /**
11127     * Get the "allow unknown sources" setting.
11128     *
11129     * @return the current "allow unknown sources" setting
11130     */
11131    private int getUnknownSourcesSettings() {
11132        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11133                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11134                -1);
11135    }
11136
11137    @Override
11138    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11139        final int uid = Binder.getCallingUid();
11140        // writer
11141        synchronized (mPackages) {
11142            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11143            if (targetPackageSetting == null) {
11144                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11145            }
11146
11147            PackageSetting installerPackageSetting;
11148            if (installerPackageName != null) {
11149                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11150                if (installerPackageSetting == null) {
11151                    throw new IllegalArgumentException("Unknown installer package: "
11152                            + installerPackageName);
11153                }
11154            } else {
11155                installerPackageSetting = null;
11156            }
11157
11158            Signature[] callerSignature;
11159            Object obj = mSettings.getUserIdLPr(uid);
11160            if (obj != null) {
11161                if (obj instanceof SharedUserSetting) {
11162                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11163                } else if (obj instanceof PackageSetting) {
11164                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11165                } else {
11166                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11167                }
11168            } else {
11169                throw new SecurityException("Unknown calling UID: " + uid);
11170            }
11171
11172            // Verify: can't set installerPackageName to a package that is
11173            // not signed with the same cert as the caller.
11174            if (installerPackageSetting != null) {
11175                if (compareSignatures(callerSignature,
11176                        installerPackageSetting.signatures.mSignatures)
11177                        != PackageManager.SIGNATURE_MATCH) {
11178                    throw new SecurityException(
11179                            "Caller does not have same cert as new installer package "
11180                            + installerPackageName);
11181                }
11182            }
11183
11184            // Verify: if target already has an installer package, it must
11185            // be signed with the same cert as the caller.
11186            if (targetPackageSetting.installerPackageName != null) {
11187                PackageSetting setting = mSettings.mPackages.get(
11188                        targetPackageSetting.installerPackageName);
11189                // If the currently set package isn't valid, then it's always
11190                // okay to change it.
11191                if (setting != null) {
11192                    if (compareSignatures(callerSignature,
11193                            setting.signatures.mSignatures)
11194                            != PackageManager.SIGNATURE_MATCH) {
11195                        throw new SecurityException(
11196                                "Caller does not have same cert as old installer package "
11197                                + targetPackageSetting.installerPackageName);
11198                    }
11199                }
11200            }
11201
11202            // Okay!
11203            targetPackageSetting.installerPackageName = installerPackageName;
11204            scheduleWriteSettingsLocked();
11205        }
11206    }
11207
11208    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11209        // Queue up an async operation since the package installation may take a little while.
11210        mHandler.post(new Runnable() {
11211            public void run() {
11212                mHandler.removeCallbacks(this);
11213                 // Result object to be returned
11214                PackageInstalledInfo res = new PackageInstalledInfo();
11215                res.setReturnCode(currentStatus);
11216                res.uid = -1;
11217                res.pkg = null;
11218                res.removedInfo = null;
11219                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11220                    args.doPreInstall(res.returnCode);
11221                    synchronized (mInstallLock) {
11222                        installPackageTracedLI(args, res);
11223                    }
11224                    args.doPostInstall(res.returnCode, res.uid);
11225                }
11226
11227                // A restore should be performed at this point if (a) the install
11228                // succeeded, (b) the operation is not an update, and (c) the new
11229                // package has not opted out of backup participation.
11230                final boolean update = res.removedInfo != null
11231                        && res.removedInfo.removedPackage != null;
11232                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11233                boolean doRestore = !update
11234                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11235
11236                // Set up the post-install work request bookkeeping.  This will be used
11237                // and cleaned up by the post-install event handling regardless of whether
11238                // there's a restore pass performed.  Token values are >= 1.
11239                int token;
11240                if (mNextInstallToken < 0) mNextInstallToken = 1;
11241                token = mNextInstallToken++;
11242
11243                PostInstallData data = new PostInstallData(args, res);
11244                mRunningInstalls.put(token, data);
11245                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11246
11247                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11248                    // Pass responsibility to the Backup Manager.  It will perform a
11249                    // restore if appropriate, then pass responsibility back to the
11250                    // Package Manager to run the post-install observer callbacks
11251                    // and broadcasts.
11252                    IBackupManager bm = IBackupManager.Stub.asInterface(
11253                            ServiceManager.getService(Context.BACKUP_SERVICE));
11254                    if (bm != null) {
11255                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11256                                + " to BM for possible restore");
11257                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11258                        try {
11259                            // TODO: http://b/22388012
11260                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11261                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11262                            } else {
11263                                doRestore = false;
11264                            }
11265                        } catch (RemoteException e) {
11266                            // can't happen; the backup manager is local
11267                        } catch (Exception e) {
11268                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11269                            doRestore = false;
11270                        }
11271                    } else {
11272                        Slog.e(TAG, "Backup Manager not found!");
11273                        doRestore = false;
11274                    }
11275                }
11276
11277                if (!doRestore) {
11278                    // No restore possible, or the Backup Manager was mysteriously not
11279                    // available -- just fire the post-install work request directly.
11280                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11281
11282                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11283
11284                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11285                    mHandler.sendMessage(msg);
11286                }
11287            }
11288        });
11289    }
11290
11291    private abstract class HandlerParams {
11292        private static final int MAX_RETRIES = 4;
11293
11294        /**
11295         * Number of times startCopy() has been attempted and had a non-fatal
11296         * error.
11297         */
11298        private int mRetries = 0;
11299
11300        /** User handle for the user requesting the information or installation. */
11301        private final UserHandle mUser;
11302        String traceMethod;
11303        int traceCookie;
11304
11305        HandlerParams(UserHandle user) {
11306            mUser = user;
11307        }
11308
11309        UserHandle getUser() {
11310            return mUser;
11311        }
11312
11313        HandlerParams setTraceMethod(String traceMethod) {
11314            this.traceMethod = traceMethod;
11315            return this;
11316        }
11317
11318        HandlerParams setTraceCookie(int traceCookie) {
11319            this.traceCookie = traceCookie;
11320            return this;
11321        }
11322
11323        final boolean startCopy() {
11324            boolean res;
11325            try {
11326                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11327
11328                if (++mRetries > MAX_RETRIES) {
11329                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11330                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11331                    handleServiceError();
11332                    return false;
11333                } else {
11334                    handleStartCopy();
11335                    res = true;
11336                }
11337            } catch (RemoteException e) {
11338                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11339                mHandler.sendEmptyMessage(MCS_RECONNECT);
11340                res = false;
11341            }
11342            handleReturnCode();
11343            return res;
11344        }
11345
11346        final void serviceError() {
11347            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11348            handleServiceError();
11349            handleReturnCode();
11350        }
11351
11352        abstract void handleStartCopy() throws RemoteException;
11353        abstract void handleServiceError();
11354        abstract void handleReturnCode();
11355    }
11356
11357    class MeasureParams extends HandlerParams {
11358        private final PackageStats mStats;
11359        private boolean mSuccess;
11360
11361        private final IPackageStatsObserver mObserver;
11362
11363        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11364            super(new UserHandle(stats.userHandle));
11365            mObserver = observer;
11366            mStats = stats;
11367        }
11368
11369        @Override
11370        public String toString() {
11371            return "MeasureParams{"
11372                + Integer.toHexString(System.identityHashCode(this))
11373                + " " + mStats.packageName + "}";
11374        }
11375
11376        @Override
11377        void handleStartCopy() throws RemoteException {
11378            synchronized (mInstallLock) {
11379                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11380            }
11381
11382            if (mSuccess) {
11383                final boolean mounted;
11384                if (Environment.isExternalStorageEmulated()) {
11385                    mounted = true;
11386                } else {
11387                    final String status = Environment.getExternalStorageState();
11388                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11389                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11390                }
11391
11392                if (mounted) {
11393                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11394
11395                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11396                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11397
11398                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11399                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11400
11401                    // Always subtract cache size, since it's a subdirectory
11402                    mStats.externalDataSize -= mStats.externalCacheSize;
11403
11404                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11405                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11406
11407                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11408                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11409                }
11410            }
11411        }
11412
11413        @Override
11414        void handleReturnCode() {
11415            if (mObserver != null) {
11416                try {
11417                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11418                } catch (RemoteException e) {
11419                    Slog.i(TAG, "Observer no longer exists.");
11420                }
11421            }
11422        }
11423
11424        @Override
11425        void handleServiceError() {
11426            Slog.e(TAG, "Could not measure application " + mStats.packageName
11427                            + " external storage");
11428        }
11429    }
11430
11431    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11432            throws RemoteException {
11433        long result = 0;
11434        for (File path : paths) {
11435            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11436        }
11437        return result;
11438    }
11439
11440    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11441        for (File path : paths) {
11442            try {
11443                mcs.clearDirectory(path.getAbsolutePath());
11444            } catch (RemoteException e) {
11445            }
11446        }
11447    }
11448
11449    static class OriginInfo {
11450        /**
11451         * Location where install is coming from, before it has been
11452         * copied/renamed into place. This could be a single monolithic APK
11453         * file, or a cluster directory. This location may be untrusted.
11454         */
11455        final File file;
11456        final String cid;
11457
11458        /**
11459         * Flag indicating that {@link #file} or {@link #cid} has already been
11460         * staged, meaning downstream users don't need to defensively copy the
11461         * contents.
11462         */
11463        final boolean staged;
11464
11465        /**
11466         * Flag indicating that {@link #file} or {@link #cid} is an already
11467         * installed app that is being moved.
11468         */
11469        final boolean existing;
11470
11471        final String resolvedPath;
11472        final File resolvedFile;
11473
11474        static OriginInfo fromNothing() {
11475            return new OriginInfo(null, null, false, false);
11476        }
11477
11478        static OriginInfo fromUntrustedFile(File file) {
11479            return new OriginInfo(file, null, false, false);
11480        }
11481
11482        static OriginInfo fromExistingFile(File file) {
11483            return new OriginInfo(file, null, false, true);
11484        }
11485
11486        static OriginInfo fromStagedFile(File file) {
11487            return new OriginInfo(file, null, true, false);
11488        }
11489
11490        static OriginInfo fromStagedContainer(String cid) {
11491            return new OriginInfo(null, cid, true, false);
11492        }
11493
11494        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11495            this.file = file;
11496            this.cid = cid;
11497            this.staged = staged;
11498            this.existing = existing;
11499
11500            if (cid != null) {
11501                resolvedPath = PackageHelper.getSdDir(cid);
11502                resolvedFile = new File(resolvedPath);
11503            } else if (file != null) {
11504                resolvedPath = file.getAbsolutePath();
11505                resolvedFile = file;
11506            } else {
11507                resolvedPath = null;
11508                resolvedFile = null;
11509            }
11510        }
11511    }
11512
11513    static class MoveInfo {
11514        final int moveId;
11515        final String fromUuid;
11516        final String toUuid;
11517        final String packageName;
11518        final String dataAppName;
11519        final int appId;
11520        final String seinfo;
11521        final int targetSdkVersion;
11522
11523        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11524                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11525            this.moveId = moveId;
11526            this.fromUuid = fromUuid;
11527            this.toUuid = toUuid;
11528            this.packageName = packageName;
11529            this.dataAppName = dataAppName;
11530            this.appId = appId;
11531            this.seinfo = seinfo;
11532            this.targetSdkVersion = targetSdkVersion;
11533        }
11534    }
11535
11536    static class VerificationInfo {
11537        /** A constant used to indicate that a uid value is not present. */
11538        public static final int NO_UID = -1;
11539
11540        /** URI referencing where the package was downloaded from. */
11541        final Uri originatingUri;
11542
11543        /** HTTP referrer URI associated with the originatingURI. */
11544        final Uri referrer;
11545
11546        /** UID of the application that the install request originated from. */
11547        final int originatingUid;
11548
11549        /** UID of application requesting the install */
11550        final int installerUid;
11551
11552        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11553            this.originatingUri = originatingUri;
11554            this.referrer = referrer;
11555            this.originatingUid = originatingUid;
11556            this.installerUid = installerUid;
11557        }
11558    }
11559
11560    class InstallParams extends HandlerParams {
11561        final OriginInfo origin;
11562        final MoveInfo move;
11563        final IPackageInstallObserver2 observer;
11564        int installFlags;
11565        final String installerPackageName;
11566        final String volumeUuid;
11567        private InstallArgs mArgs;
11568        private int mRet;
11569        final String packageAbiOverride;
11570        final String[] grantedRuntimePermissions;
11571        final VerificationInfo verificationInfo;
11572
11573        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11574                int installFlags, String installerPackageName, String volumeUuid,
11575                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11576                String[] grantedPermissions) {
11577            super(user);
11578            this.origin = origin;
11579            this.move = move;
11580            this.observer = observer;
11581            this.installFlags = installFlags;
11582            this.installerPackageName = installerPackageName;
11583            this.volumeUuid = volumeUuid;
11584            this.verificationInfo = verificationInfo;
11585            this.packageAbiOverride = packageAbiOverride;
11586            this.grantedRuntimePermissions = grantedPermissions;
11587        }
11588
11589        @Override
11590        public String toString() {
11591            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11592                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11593        }
11594
11595        private int installLocationPolicy(PackageInfoLite pkgLite) {
11596            String packageName = pkgLite.packageName;
11597            int installLocation = pkgLite.installLocation;
11598            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11599            // reader
11600            synchronized (mPackages) {
11601                // Currently installed package which the new package is attempting to replace or
11602                // null if no such package is installed.
11603                PackageParser.Package installedPkg = mPackages.get(packageName);
11604                // Package which currently owns the data which the new package will own if installed.
11605                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11606                // will be null whereas dataOwnerPkg will contain information about the package
11607                // which was uninstalled while keeping its data.
11608                PackageParser.Package dataOwnerPkg = installedPkg;
11609                if (dataOwnerPkg  == null) {
11610                    PackageSetting ps = mSettings.mPackages.get(packageName);
11611                    if (ps != null) {
11612                        dataOwnerPkg = ps.pkg;
11613                    }
11614                }
11615
11616                if (dataOwnerPkg != null) {
11617                    // If installed, the package will get access to data left on the device by its
11618                    // predecessor. As a security measure, this is permited only if this is not a
11619                    // version downgrade or if the predecessor package is marked as debuggable and
11620                    // a downgrade is explicitly requested.
11621                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11622                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11623                        try {
11624                            checkDowngrade(dataOwnerPkg, pkgLite);
11625                        } catch (PackageManagerException e) {
11626                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11627                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11628                        }
11629                    }
11630                }
11631
11632                if (installedPkg != null) {
11633                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11634                        // Check for updated system application.
11635                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11636                            if (onSd) {
11637                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11638                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11639                            }
11640                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11641                        } else {
11642                            if (onSd) {
11643                                // Install flag overrides everything.
11644                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11645                            }
11646                            // If current upgrade specifies particular preference
11647                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11648                                // Application explicitly specified internal.
11649                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11650                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11651                                // App explictly prefers external. Let policy decide
11652                            } else {
11653                                // Prefer previous location
11654                                if (isExternal(installedPkg)) {
11655                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11656                                }
11657                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11658                            }
11659                        }
11660                    } else {
11661                        // Invalid install. Return error code
11662                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11663                    }
11664                }
11665            }
11666            // All the special cases have been taken care of.
11667            // Return result based on recommended install location.
11668            if (onSd) {
11669                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11670            }
11671            return pkgLite.recommendedInstallLocation;
11672        }
11673
11674        /*
11675         * Invoke remote method to get package information and install
11676         * location values. Override install location based on default
11677         * policy if needed and then create install arguments based
11678         * on the install location.
11679         */
11680        public void handleStartCopy() throws RemoteException {
11681            int ret = PackageManager.INSTALL_SUCCEEDED;
11682
11683            // If we're already staged, we've firmly committed to an install location
11684            if (origin.staged) {
11685                if (origin.file != null) {
11686                    installFlags |= PackageManager.INSTALL_INTERNAL;
11687                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11688                } else if (origin.cid != null) {
11689                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11690                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11691                } else {
11692                    throw new IllegalStateException("Invalid stage location");
11693                }
11694            }
11695
11696            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11697            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11698            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11699            PackageInfoLite pkgLite = null;
11700
11701            if (onInt && onSd) {
11702                // Check if both bits are set.
11703                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11704                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11705            } else if (onSd && ephemeral) {
11706                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11707                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11708            } else {
11709                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11710                        packageAbiOverride);
11711
11712                if (DEBUG_EPHEMERAL && ephemeral) {
11713                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11714                }
11715
11716                /*
11717                 * If we have too little free space, try to free cache
11718                 * before giving up.
11719                 */
11720                if (!origin.staged && pkgLite.recommendedInstallLocation
11721                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11722                    // TODO: focus freeing disk space on the target device
11723                    final StorageManager storage = StorageManager.from(mContext);
11724                    final long lowThreshold = storage.getStorageLowBytes(
11725                            Environment.getDataDirectory());
11726
11727                    final long sizeBytes = mContainerService.calculateInstalledSize(
11728                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11729
11730                    try {
11731                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11732                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11733                                installFlags, packageAbiOverride);
11734                    } catch (InstallerException e) {
11735                        Slog.w(TAG, "Failed to free cache", e);
11736                    }
11737
11738                    /*
11739                     * The cache free must have deleted the file we
11740                     * downloaded to install.
11741                     *
11742                     * TODO: fix the "freeCache" call to not delete
11743                     *       the file we care about.
11744                     */
11745                    if (pkgLite.recommendedInstallLocation
11746                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11747                        pkgLite.recommendedInstallLocation
11748                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11749                    }
11750                }
11751            }
11752
11753            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11754                int loc = pkgLite.recommendedInstallLocation;
11755                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11756                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11757                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11758                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11759                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11760                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11761                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11762                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11763                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11764                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11765                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11766                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11767                } else {
11768                    // Override with defaults if needed.
11769                    loc = installLocationPolicy(pkgLite);
11770                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11771                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11772                    } else if (!onSd && !onInt) {
11773                        // Override install location with flags
11774                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11775                            // Set the flag to install on external media.
11776                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11777                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11778                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11779                            if (DEBUG_EPHEMERAL) {
11780                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11781                            }
11782                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11783                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11784                                    |PackageManager.INSTALL_INTERNAL);
11785                        } else {
11786                            // Make sure the flag for installing on external
11787                            // media is unset
11788                            installFlags |= PackageManager.INSTALL_INTERNAL;
11789                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11790                        }
11791                    }
11792                }
11793            }
11794
11795            final InstallArgs args = createInstallArgs(this);
11796            mArgs = args;
11797
11798            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11799                // TODO: http://b/22976637
11800                // Apps installed for "all" users use the device owner to verify the app
11801                UserHandle verifierUser = getUser();
11802                if (verifierUser == UserHandle.ALL) {
11803                    verifierUser = UserHandle.SYSTEM;
11804                }
11805
11806                /*
11807                 * Determine if we have any installed package verifiers. If we
11808                 * do, then we'll defer to them to verify the packages.
11809                 */
11810                final int requiredUid = mRequiredVerifierPackage == null ? -1
11811                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11812                                verifierUser.getIdentifier());
11813                if (!origin.existing && requiredUid != -1
11814                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11815                    final Intent verification = new Intent(
11816                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11817                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11818                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11819                            PACKAGE_MIME_TYPE);
11820                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11821
11822                    // Query all live verifiers based on current user state
11823                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11824                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11825
11826                    if (DEBUG_VERIFY) {
11827                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11828                                + verification.toString() + " with " + pkgLite.verifiers.length
11829                                + " optional verifiers");
11830                    }
11831
11832                    final int verificationId = mPendingVerificationToken++;
11833
11834                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11835
11836                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11837                            installerPackageName);
11838
11839                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11840                            installFlags);
11841
11842                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11843                            pkgLite.packageName);
11844
11845                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11846                            pkgLite.versionCode);
11847
11848                    if (verificationInfo != null) {
11849                        if (verificationInfo.originatingUri != null) {
11850                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11851                                    verificationInfo.originatingUri);
11852                        }
11853                        if (verificationInfo.referrer != null) {
11854                            verification.putExtra(Intent.EXTRA_REFERRER,
11855                                    verificationInfo.referrer);
11856                        }
11857                        if (verificationInfo.originatingUid >= 0) {
11858                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11859                                    verificationInfo.originatingUid);
11860                        }
11861                        if (verificationInfo.installerUid >= 0) {
11862                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11863                                    verificationInfo.installerUid);
11864                        }
11865                    }
11866
11867                    final PackageVerificationState verificationState = new PackageVerificationState(
11868                            requiredUid, args);
11869
11870                    mPendingVerification.append(verificationId, verificationState);
11871
11872                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11873                            receivers, verificationState);
11874
11875                    /*
11876                     * If any sufficient verifiers were listed in the package
11877                     * manifest, attempt to ask them.
11878                     */
11879                    if (sufficientVerifiers != null) {
11880                        final int N = sufficientVerifiers.size();
11881                        if (N == 0) {
11882                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11883                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11884                        } else {
11885                            for (int i = 0; i < N; i++) {
11886                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11887
11888                                final Intent sufficientIntent = new Intent(verification);
11889                                sufficientIntent.setComponent(verifierComponent);
11890                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11891                            }
11892                        }
11893                    }
11894
11895                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11896                            mRequiredVerifierPackage, receivers);
11897                    if (ret == PackageManager.INSTALL_SUCCEEDED
11898                            && mRequiredVerifierPackage != null) {
11899                        Trace.asyncTraceBegin(
11900                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11901                        /*
11902                         * Send the intent to the required verification agent,
11903                         * but only start the verification timeout after the
11904                         * target BroadcastReceivers have run.
11905                         */
11906                        verification.setComponent(requiredVerifierComponent);
11907                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11908                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11909                                new BroadcastReceiver() {
11910                                    @Override
11911                                    public void onReceive(Context context, Intent intent) {
11912                                        final Message msg = mHandler
11913                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11914                                        msg.arg1 = verificationId;
11915                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11916                                    }
11917                                }, null, 0, null, null);
11918
11919                        /*
11920                         * We don't want the copy to proceed until verification
11921                         * succeeds, so null out this field.
11922                         */
11923                        mArgs = null;
11924                    }
11925                } else {
11926                    /*
11927                     * No package verification is enabled, so immediately start
11928                     * the remote call to initiate copy using temporary file.
11929                     */
11930                    ret = args.copyApk(mContainerService, true);
11931                }
11932            }
11933
11934            mRet = ret;
11935        }
11936
11937        @Override
11938        void handleReturnCode() {
11939            // If mArgs is null, then MCS couldn't be reached. When it
11940            // reconnects, it will try again to install. At that point, this
11941            // will succeed.
11942            if (mArgs != null) {
11943                processPendingInstall(mArgs, mRet);
11944            }
11945        }
11946
11947        @Override
11948        void handleServiceError() {
11949            mArgs = createInstallArgs(this);
11950            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11951        }
11952
11953        public boolean isForwardLocked() {
11954            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11955        }
11956    }
11957
11958    /**
11959     * Used during creation of InstallArgs
11960     *
11961     * @param installFlags package installation flags
11962     * @return true if should be installed on external storage
11963     */
11964    private static boolean installOnExternalAsec(int installFlags) {
11965        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11966            return false;
11967        }
11968        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11969            return true;
11970        }
11971        return false;
11972    }
11973
11974    /**
11975     * Used during creation of InstallArgs
11976     *
11977     * @param installFlags package installation flags
11978     * @return true if should be installed as forward locked
11979     */
11980    private static boolean installForwardLocked(int installFlags) {
11981        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11982    }
11983
11984    private InstallArgs createInstallArgs(InstallParams params) {
11985        if (params.move != null) {
11986            return new MoveInstallArgs(params);
11987        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11988            return new AsecInstallArgs(params);
11989        } else {
11990            return new FileInstallArgs(params);
11991        }
11992    }
11993
11994    /**
11995     * Create args that describe an existing installed package. Typically used
11996     * when cleaning up old installs, or used as a move source.
11997     */
11998    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11999            String resourcePath, String[] instructionSets) {
12000        final boolean isInAsec;
12001        if (installOnExternalAsec(installFlags)) {
12002            /* Apps on SD card are always in ASEC containers. */
12003            isInAsec = true;
12004        } else if (installForwardLocked(installFlags)
12005                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12006            /*
12007             * Forward-locked apps are only in ASEC containers if they're the
12008             * new style
12009             */
12010            isInAsec = true;
12011        } else {
12012            isInAsec = false;
12013        }
12014
12015        if (isInAsec) {
12016            return new AsecInstallArgs(codePath, instructionSets,
12017                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12018        } else {
12019            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12020        }
12021    }
12022
12023    static abstract class InstallArgs {
12024        /** @see InstallParams#origin */
12025        final OriginInfo origin;
12026        /** @see InstallParams#move */
12027        final MoveInfo move;
12028
12029        final IPackageInstallObserver2 observer;
12030        // Always refers to PackageManager flags only
12031        final int installFlags;
12032        final String installerPackageName;
12033        final String volumeUuid;
12034        final UserHandle user;
12035        final String abiOverride;
12036        final String[] installGrantPermissions;
12037        /** If non-null, drop an async trace when the install completes */
12038        final String traceMethod;
12039        final int traceCookie;
12040
12041        // The list of instruction sets supported by this app. This is currently
12042        // only used during the rmdex() phase to clean up resources. We can get rid of this
12043        // if we move dex files under the common app path.
12044        /* nullable */ String[] instructionSets;
12045
12046        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12047                int installFlags, String installerPackageName, String volumeUuid,
12048                UserHandle user, String[] instructionSets,
12049                String abiOverride, String[] installGrantPermissions,
12050                String traceMethod, int traceCookie) {
12051            this.origin = origin;
12052            this.move = move;
12053            this.installFlags = installFlags;
12054            this.observer = observer;
12055            this.installerPackageName = installerPackageName;
12056            this.volumeUuid = volumeUuid;
12057            this.user = user;
12058            this.instructionSets = instructionSets;
12059            this.abiOverride = abiOverride;
12060            this.installGrantPermissions = installGrantPermissions;
12061            this.traceMethod = traceMethod;
12062            this.traceCookie = traceCookie;
12063        }
12064
12065        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12066        abstract int doPreInstall(int status);
12067
12068        /**
12069         * Rename package into final resting place. All paths on the given
12070         * scanned package should be updated to reflect the rename.
12071         */
12072        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12073        abstract int doPostInstall(int status, int uid);
12074
12075        /** @see PackageSettingBase#codePathString */
12076        abstract String getCodePath();
12077        /** @see PackageSettingBase#resourcePathString */
12078        abstract String getResourcePath();
12079
12080        // Need installer lock especially for dex file removal.
12081        abstract void cleanUpResourcesLI();
12082        abstract boolean doPostDeleteLI(boolean delete);
12083
12084        /**
12085         * Called before the source arguments are copied. This is used mostly
12086         * for MoveParams when it needs to read the source file to put it in the
12087         * destination.
12088         */
12089        int doPreCopy() {
12090            return PackageManager.INSTALL_SUCCEEDED;
12091        }
12092
12093        /**
12094         * Called after the source arguments are copied. This is used mostly for
12095         * MoveParams when it needs to read the source file to put it in the
12096         * destination.
12097         *
12098         * @return
12099         */
12100        int doPostCopy(int uid) {
12101            return PackageManager.INSTALL_SUCCEEDED;
12102        }
12103
12104        protected boolean isFwdLocked() {
12105            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12106        }
12107
12108        protected boolean isExternalAsec() {
12109            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12110        }
12111
12112        protected boolean isEphemeral() {
12113            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12114        }
12115
12116        UserHandle getUser() {
12117            return user;
12118        }
12119    }
12120
12121    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12122        if (!allCodePaths.isEmpty()) {
12123            if (instructionSets == null) {
12124                throw new IllegalStateException("instructionSet == null");
12125            }
12126            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12127            for (String codePath : allCodePaths) {
12128                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12129                    try {
12130                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12131                    } catch (InstallerException ignored) {
12132                    }
12133                }
12134            }
12135        }
12136    }
12137
12138    /**
12139     * Logic to handle installation of non-ASEC applications, including copying
12140     * and renaming logic.
12141     */
12142    class FileInstallArgs extends InstallArgs {
12143        private File codeFile;
12144        private File resourceFile;
12145
12146        // Example topology:
12147        // /data/app/com.example/base.apk
12148        // /data/app/com.example/split_foo.apk
12149        // /data/app/com.example/lib/arm/libfoo.so
12150        // /data/app/com.example/lib/arm64/libfoo.so
12151        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12152
12153        /** New install */
12154        FileInstallArgs(InstallParams params) {
12155            super(params.origin, params.move, params.observer, params.installFlags,
12156                    params.installerPackageName, params.volumeUuid,
12157                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12158                    params.grantedRuntimePermissions,
12159                    params.traceMethod, params.traceCookie);
12160            if (isFwdLocked()) {
12161                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12162            }
12163        }
12164
12165        /** Existing install */
12166        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12167            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12168                    null, null, null, 0);
12169            this.codeFile = (codePath != null) ? new File(codePath) : null;
12170            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12171        }
12172
12173        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12174            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12175            try {
12176                return doCopyApk(imcs, temp);
12177            } finally {
12178                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12179            }
12180        }
12181
12182        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12183            if (origin.staged) {
12184                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12185                codeFile = origin.file;
12186                resourceFile = origin.file;
12187                return PackageManager.INSTALL_SUCCEEDED;
12188            }
12189
12190            try {
12191                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12192                final File tempDir =
12193                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12194                codeFile = tempDir;
12195                resourceFile = tempDir;
12196            } catch (IOException e) {
12197                Slog.w(TAG, "Failed to create copy file: " + e);
12198                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12199            }
12200
12201            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12202                @Override
12203                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12204                    if (!FileUtils.isValidExtFilename(name)) {
12205                        throw new IllegalArgumentException("Invalid filename: " + name);
12206                    }
12207                    try {
12208                        final File file = new File(codeFile, name);
12209                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12210                                O_RDWR | O_CREAT, 0644);
12211                        Os.chmod(file.getAbsolutePath(), 0644);
12212                        return new ParcelFileDescriptor(fd);
12213                    } catch (ErrnoException e) {
12214                        throw new RemoteException("Failed to open: " + e.getMessage());
12215                    }
12216                }
12217            };
12218
12219            int ret = PackageManager.INSTALL_SUCCEEDED;
12220            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12221            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12222                Slog.e(TAG, "Failed to copy package");
12223                return ret;
12224            }
12225
12226            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12227            NativeLibraryHelper.Handle handle = null;
12228            try {
12229                handle = NativeLibraryHelper.Handle.create(codeFile);
12230                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12231                        abiOverride);
12232            } catch (IOException e) {
12233                Slog.e(TAG, "Copying native libraries failed", e);
12234                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12235            } finally {
12236                IoUtils.closeQuietly(handle);
12237            }
12238
12239            return ret;
12240        }
12241
12242        int doPreInstall(int status) {
12243            if (status != PackageManager.INSTALL_SUCCEEDED) {
12244                cleanUp();
12245            }
12246            return status;
12247        }
12248
12249        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12250            if (status != PackageManager.INSTALL_SUCCEEDED) {
12251                cleanUp();
12252                return false;
12253            }
12254
12255            final File targetDir = codeFile.getParentFile();
12256            final File beforeCodeFile = codeFile;
12257            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12258
12259            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12260            try {
12261                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12262            } catch (ErrnoException e) {
12263                Slog.w(TAG, "Failed to rename", e);
12264                return false;
12265            }
12266
12267            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12268                Slog.w(TAG, "Failed to restorecon");
12269                return false;
12270            }
12271
12272            // Reflect the rename internally
12273            codeFile = afterCodeFile;
12274            resourceFile = afterCodeFile;
12275
12276            // Reflect the rename in scanned details
12277            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12278            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12279                    afterCodeFile, pkg.baseCodePath));
12280            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12281                    afterCodeFile, pkg.splitCodePaths));
12282
12283            // Reflect the rename in app info
12284            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12285            pkg.setApplicationInfoCodePath(pkg.codePath);
12286            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12287            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12288            pkg.setApplicationInfoResourcePath(pkg.codePath);
12289            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12290            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12291
12292            return true;
12293        }
12294
12295        int doPostInstall(int status, int uid) {
12296            if (status != PackageManager.INSTALL_SUCCEEDED) {
12297                cleanUp();
12298            }
12299            return status;
12300        }
12301
12302        @Override
12303        String getCodePath() {
12304            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12305        }
12306
12307        @Override
12308        String getResourcePath() {
12309            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12310        }
12311
12312        private boolean cleanUp() {
12313            if (codeFile == null || !codeFile.exists()) {
12314                return false;
12315            }
12316
12317            removeCodePathLI(codeFile);
12318
12319            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12320                resourceFile.delete();
12321            }
12322
12323            return true;
12324        }
12325
12326        void cleanUpResourcesLI() {
12327            // Try enumerating all code paths before deleting
12328            List<String> allCodePaths = Collections.EMPTY_LIST;
12329            if (codeFile != null && codeFile.exists()) {
12330                try {
12331                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12332                    allCodePaths = pkg.getAllCodePaths();
12333                } catch (PackageParserException e) {
12334                    // Ignored; we tried our best
12335                }
12336            }
12337
12338            cleanUp();
12339            removeDexFiles(allCodePaths, instructionSets);
12340        }
12341
12342        boolean doPostDeleteLI(boolean delete) {
12343            // XXX err, shouldn't we respect the delete flag?
12344            cleanUpResourcesLI();
12345            return true;
12346        }
12347    }
12348
12349    private boolean isAsecExternal(String cid) {
12350        final String asecPath = PackageHelper.getSdFilesystem(cid);
12351        return !asecPath.startsWith(mAsecInternalPath);
12352    }
12353
12354    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12355            PackageManagerException {
12356        if (copyRet < 0) {
12357            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12358                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12359                throw new PackageManagerException(copyRet, message);
12360            }
12361        }
12362    }
12363
12364    /**
12365     * Extract the MountService "container ID" from the full code path of an
12366     * .apk.
12367     */
12368    static String cidFromCodePath(String fullCodePath) {
12369        int eidx = fullCodePath.lastIndexOf("/");
12370        String subStr1 = fullCodePath.substring(0, eidx);
12371        int sidx = subStr1.lastIndexOf("/");
12372        return subStr1.substring(sidx+1, eidx);
12373    }
12374
12375    /**
12376     * Logic to handle installation of ASEC applications, including copying and
12377     * renaming logic.
12378     */
12379    class AsecInstallArgs extends InstallArgs {
12380        static final String RES_FILE_NAME = "pkg.apk";
12381        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12382
12383        String cid;
12384        String packagePath;
12385        String resourcePath;
12386
12387        /** New install */
12388        AsecInstallArgs(InstallParams params) {
12389            super(params.origin, params.move, params.observer, params.installFlags,
12390                    params.installerPackageName, params.volumeUuid,
12391                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12392                    params.grantedRuntimePermissions,
12393                    params.traceMethod, params.traceCookie);
12394        }
12395
12396        /** Existing install */
12397        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12398                        boolean isExternal, boolean isForwardLocked) {
12399            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12400                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12401                    instructionSets, null, null, null, 0);
12402            // Hackily pretend we're still looking at a full code path
12403            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12404                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12405            }
12406
12407            // Extract cid from fullCodePath
12408            int eidx = fullCodePath.lastIndexOf("/");
12409            String subStr1 = fullCodePath.substring(0, eidx);
12410            int sidx = subStr1.lastIndexOf("/");
12411            cid = subStr1.substring(sidx+1, eidx);
12412            setMountPath(subStr1);
12413        }
12414
12415        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12416            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12417                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12418                    instructionSets, null, null, null, 0);
12419            this.cid = cid;
12420            setMountPath(PackageHelper.getSdDir(cid));
12421        }
12422
12423        void createCopyFile() {
12424            cid = mInstallerService.allocateExternalStageCidLegacy();
12425        }
12426
12427        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12428            if (origin.staged && origin.cid != null) {
12429                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12430                cid = origin.cid;
12431                setMountPath(PackageHelper.getSdDir(cid));
12432                return PackageManager.INSTALL_SUCCEEDED;
12433            }
12434
12435            if (temp) {
12436                createCopyFile();
12437            } else {
12438                /*
12439                 * Pre-emptively destroy the container since it's destroyed if
12440                 * copying fails due to it existing anyway.
12441                 */
12442                PackageHelper.destroySdDir(cid);
12443            }
12444
12445            final String newMountPath = imcs.copyPackageToContainer(
12446                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12447                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12448
12449            if (newMountPath != null) {
12450                setMountPath(newMountPath);
12451                return PackageManager.INSTALL_SUCCEEDED;
12452            } else {
12453                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12454            }
12455        }
12456
12457        @Override
12458        String getCodePath() {
12459            return packagePath;
12460        }
12461
12462        @Override
12463        String getResourcePath() {
12464            return resourcePath;
12465        }
12466
12467        int doPreInstall(int status) {
12468            if (status != PackageManager.INSTALL_SUCCEEDED) {
12469                // Destroy container
12470                PackageHelper.destroySdDir(cid);
12471            } else {
12472                boolean mounted = PackageHelper.isContainerMounted(cid);
12473                if (!mounted) {
12474                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12475                            Process.SYSTEM_UID);
12476                    if (newMountPath != null) {
12477                        setMountPath(newMountPath);
12478                    } else {
12479                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12480                    }
12481                }
12482            }
12483            return status;
12484        }
12485
12486        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12487            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12488            String newMountPath = null;
12489            if (PackageHelper.isContainerMounted(cid)) {
12490                // Unmount the container
12491                if (!PackageHelper.unMountSdDir(cid)) {
12492                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12493                    return false;
12494                }
12495            }
12496            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12497                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12498                        " which might be stale. Will try to clean up.");
12499                // Clean up the stale container and proceed to recreate.
12500                if (!PackageHelper.destroySdDir(newCacheId)) {
12501                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12502                    return false;
12503                }
12504                // Successfully cleaned up stale container. Try to rename again.
12505                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12506                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12507                            + " inspite of cleaning it up.");
12508                    return false;
12509                }
12510            }
12511            if (!PackageHelper.isContainerMounted(newCacheId)) {
12512                Slog.w(TAG, "Mounting container " + newCacheId);
12513                newMountPath = PackageHelper.mountSdDir(newCacheId,
12514                        getEncryptKey(), Process.SYSTEM_UID);
12515            } else {
12516                newMountPath = PackageHelper.getSdDir(newCacheId);
12517            }
12518            if (newMountPath == null) {
12519                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12520                return false;
12521            }
12522            Log.i(TAG, "Succesfully renamed " + cid +
12523                    " to " + newCacheId +
12524                    " at new path: " + newMountPath);
12525            cid = newCacheId;
12526
12527            final File beforeCodeFile = new File(packagePath);
12528            setMountPath(newMountPath);
12529            final File afterCodeFile = new File(packagePath);
12530
12531            // Reflect the rename in scanned details
12532            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12533            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12534                    afterCodeFile, pkg.baseCodePath));
12535            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12536                    afterCodeFile, pkg.splitCodePaths));
12537
12538            // Reflect the rename in app info
12539            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12540            pkg.setApplicationInfoCodePath(pkg.codePath);
12541            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12542            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12543            pkg.setApplicationInfoResourcePath(pkg.codePath);
12544            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12545            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12546
12547            return true;
12548        }
12549
12550        private void setMountPath(String mountPath) {
12551            final File mountFile = new File(mountPath);
12552
12553            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12554            if (monolithicFile.exists()) {
12555                packagePath = monolithicFile.getAbsolutePath();
12556                if (isFwdLocked()) {
12557                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12558                } else {
12559                    resourcePath = packagePath;
12560                }
12561            } else {
12562                packagePath = mountFile.getAbsolutePath();
12563                resourcePath = packagePath;
12564            }
12565        }
12566
12567        int doPostInstall(int status, int uid) {
12568            if (status != PackageManager.INSTALL_SUCCEEDED) {
12569                cleanUp();
12570            } else {
12571                final int groupOwner;
12572                final String protectedFile;
12573                if (isFwdLocked()) {
12574                    groupOwner = UserHandle.getSharedAppGid(uid);
12575                    protectedFile = RES_FILE_NAME;
12576                } else {
12577                    groupOwner = -1;
12578                    protectedFile = null;
12579                }
12580
12581                if (uid < Process.FIRST_APPLICATION_UID
12582                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12583                    Slog.e(TAG, "Failed to finalize " + cid);
12584                    PackageHelper.destroySdDir(cid);
12585                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12586                }
12587
12588                boolean mounted = PackageHelper.isContainerMounted(cid);
12589                if (!mounted) {
12590                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12591                }
12592            }
12593            return status;
12594        }
12595
12596        private void cleanUp() {
12597            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12598
12599            // Destroy secure container
12600            PackageHelper.destroySdDir(cid);
12601        }
12602
12603        private List<String> getAllCodePaths() {
12604            final File codeFile = new File(getCodePath());
12605            if (codeFile != null && codeFile.exists()) {
12606                try {
12607                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12608                    return pkg.getAllCodePaths();
12609                } catch (PackageParserException e) {
12610                    // Ignored; we tried our best
12611                }
12612            }
12613            return Collections.EMPTY_LIST;
12614        }
12615
12616        void cleanUpResourcesLI() {
12617            // Enumerate all code paths before deleting
12618            cleanUpResourcesLI(getAllCodePaths());
12619        }
12620
12621        private void cleanUpResourcesLI(List<String> allCodePaths) {
12622            cleanUp();
12623            removeDexFiles(allCodePaths, instructionSets);
12624        }
12625
12626        String getPackageName() {
12627            return getAsecPackageName(cid);
12628        }
12629
12630        boolean doPostDeleteLI(boolean delete) {
12631            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12632            final List<String> allCodePaths = getAllCodePaths();
12633            boolean mounted = PackageHelper.isContainerMounted(cid);
12634            if (mounted) {
12635                // Unmount first
12636                if (PackageHelper.unMountSdDir(cid)) {
12637                    mounted = false;
12638                }
12639            }
12640            if (!mounted && delete) {
12641                cleanUpResourcesLI(allCodePaths);
12642            }
12643            return !mounted;
12644        }
12645
12646        @Override
12647        int doPreCopy() {
12648            if (isFwdLocked()) {
12649                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12650                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12651                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12652                }
12653            }
12654
12655            return PackageManager.INSTALL_SUCCEEDED;
12656        }
12657
12658        @Override
12659        int doPostCopy(int uid) {
12660            if (isFwdLocked()) {
12661                if (uid < Process.FIRST_APPLICATION_UID
12662                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12663                                RES_FILE_NAME)) {
12664                    Slog.e(TAG, "Failed to finalize " + cid);
12665                    PackageHelper.destroySdDir(cid);
12666                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12667                }
12668            }
12669
12670            return PackageManager.INSTALL_SUCCEEDED;
12671        }
12672    }
12673
12674    /**
12675     * Logic to handle movement of existing installed applications.
12676     */
12677    class MoveInstallArgs extends InstallArgs {
12678        private File codeFile;
12679        private File resourceFile;
12680
12681        /** New install */
12682        MoveInstallArgs(InstallParams params) {
12683            super(params.origin, params.move, params.observer, params.installFlags,
12684                    params.installerPackageName, params.volumeUuid,
12685                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12686                    params.grantedRuntimePermissions,
12687                    params.traceMethod, params.traceCookie);
12688        }
12689
12690        int copyApk(IMediaContainerService imcs, boolean temp) {
12691            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12692                    + move.fromUuid + " to " + move.toUuid);
12693            synchronized (mInstaller) {
12694                try {
12695                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12696                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12697                } catch (InstallerException e) {
12698                    Slog.w(TAG, "Failed to move app", e);
12699                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12700                }
12701            }
12702
12703            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12704            resourceFile = codeFile;
12705            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12706
12707            return PackageManager.INSTALL_SUCCEEDED;
12708        }
12709
12710        int doPreInstall(int status) {
12711            if (status != PackageManager.INSTALL_SUCCEEDED) {
12712                cleanUp(move.toUuid);
12713            }
12714            return status;
12715        }
12716
12717        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12718            if (status != PackageManager.INSTALL_SUCCEEDED) {
12719                cleanUp(move.toUuid);
12720                return false;
12721            }
12722
12723            // Reflect the move in app info
12724            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12725            pkg.setApplicationInfoCodePath(pkg.codePath);
12726            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12727            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12728            pkg.setApplicationInfoResourcePath(pkg.codePath);
12729            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12730            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12731
12732            return true;
12733        }
12734
12735        int doPostInstall(int status, int uid) {
12736            if (status == PackageManager.INSTALL_SUCCEEDED) {
12737                cleanUp(move.fromUuid);
12738            } else {
12739                cleanUp(move.toUuid);
12740            }
12741            return status;
12742        }
12743
12744        @Override
12745        String getCodePath() {
12746            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12747        }
12748
12749        @Override
12750        String getResourcePath() {
12751            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12752        }
12753
12754        private boolean cleanUp(String volumeUuid) {
12755            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12756                    move.dataAppName);
12757            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12758            synchronized (mInstallLock) {
12759                // Clean up both app data and code
12760                removeDataDirsLI(volumeUuid, move.packageName);
12761                removeCodePathLI(codeFile);
12762            }
12763            return true;
12764        }
12765
12766        void cleanUpResourcesLI() {
12767            throw new UnsupportedOperationException();
12768        }
12769
12770        boolean doPostDeleteLI(boolean delete) {
12771            throw new UnsupportedOperationException();
12772        }
12773    }
12774
12775    static String getAsecPackageName(String packageCid) {
12776        int idx = packageCid.lastIndexOf("-");
12777        if (idx == -1) {
12778            return packageCid;
12779        }
12780        return packageCid.substring(0, idx);
12781    }
12782
12783    // Utility method used to create code paths based on package name and available index.
12784    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12785        String idxStr = "";
12786        int idx = 1;
12787        // Fall back to default value of idx=1 if prefix is not
12788        // part of oldCodePath
12789        if (oldCodePath != null) {
12790            String subStr = oldCodePath;
12791            // Drop the suffix right away
12792            if (suffix != null && subStr.endsWith(suffix)) {
12793                subStr = subStr.substring(0, subStr.length() - suffix.length());
12794            }
12795            // If oldCodePath already contains prefix find out the
12796            // ending index to either increment or decrement.
12797            int sidx = subStr.lastIndexOf(prefix);
12798            if (sidx != -1) {
12799                subStr = subStr.substring(sidx + prefix.length());
12800                if (subStr != null) {
12801                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12802                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12803                    }
12804                    try {
12805                        idx = Integer.parseInt(subStr);
12806                        if (idx <= 1) {
12807                            idx++;
12808                        } else {
12809                            idx--;
12810                        }
12811                    } catch(NumberFormatException e) {
12812                    }
12813                }
12814            }
12815        }
12816        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12817        return prefix + idxStr;
12818    }
12819
12820    private File getNextCodePath(File targetDir, String packageName) {
12821        int suffix = 1;
12822        File result;
12823        do {
12824            result = new File(targetDir, packageName + "-" + suffix);
12825            suffix++;
12826        } while (result.exists());
12827        return result;
12828    }
12829
12830    // Utility method that returns the relative package path with respect
12831    // to the installation directory. Like say for /data/data/com.test-1.apk
12832    // string com.test-1 is returned.
12833    static String deriveCodePathName(String codePath) {
12834        if (codePath == null) {
12835            return null;
12836        }
12837        final File codeFile = new File(codePath);
12838        final String name = codeFile.getName();
12839        if (codeFile.isDirectory()) {
12840            return name;
12841        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12842            final int lastDot = name.lastIndexOf('.');
12843            return name.substring(0, lastDot);
12844        } else {
12845            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12846            return null;
12847        }
12848    }
12849
12850    static class PackageInstalledInfo {
12851        String name;
12852        int uid;
12853        // The set of users that originally had this package installed.
12854        int[] origUsers;
12855        // The set of users that now have this package installed.
12856        int[] newUsers;
12857        PackageParser.Package pkg;
12858        int returnCode;
12859        String returnMsg;
12860        PackageRemovedInfo removedInfo;
12861        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12862
12863        public void setError(int code, String msg) {
12864            setReturnCode(code);
12865            setReturnMessage(msg);
12866            Slog.w(TAG, msg);
12867        }
12868
12869        public void setError(String msg, PackageParserException e) {
12870            setReturnCode(e.error);
12871            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12872            Slog.w(TAG, msg, e);
12873        }
12874
12875        public void setError(String msg, PackageManagerException e) {
12876            returnCode = e.error;
12877            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12878            Slog.w(TAG, msg, e);
12879        }
12880
12881        public void setReturnCode(int returnCode) {
12882            this.returnCode = returnCode;
12883            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12884            for (int i = 0; i < childCount; i++) {
12885                addedChildPackages.valueAt(i).returnCode = returnCode;
12886            }
12887        }
12888
12889        private void setReturnMessage(String returnMsg) {
12890            this.returnMsg = returnMsg;
12891            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12892            for (int i = 0; i < childCount; i++) {
12893                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12894            }
12895        }
12896
12897        // In some error cases we want to convey more info back to the observer
12898        String origPackage;
12899        String origPermission;
12900    }
12901
12902    /*
12903     * Install a non-existing package.
12904     */
12905    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12906            UserHandle user, String installerPackageName, String volumeUuid,
12907            PackageInstalledInfo res) {
12908        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12909
12910        // Remember this for later, in case we need to rollback this install
12911        String pkgName = pkg.packageName;
12912
12913        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12914
12915        synchronized(mPackages) {
12916            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12917                // A package with the same name is already installed, though
12918                // it has been renamed to an older name.  The package we
12919                // are trying to install should be installed as an update to
12920                // the existing one, but that has not been requested, so bail.
12921                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12922                        + " without first uninstalling package running as "
12923                        + mSettings.mRenamedPackages.get(pkgName));
12924                return;
12925            }
12926            if (mPackages.containsKey(pkgName)) {
12927                // Don't allow installation over an existing package with the same name.
12928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12929                        + " without first uninstalling.");
12930                return;
12931            }
12932        }
12933
12934        try {
12935            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12936                    System.currentTimeMillis(), user);
12937
12938            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12939
12940            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12941                prepareAppDataAfterInstall(newPackage);
12942
12943            } else {
12944                // Remove package from internal structures, but keep around any
12945                // data that might have already existed
12946                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12947                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12948            }
12949        } catch (PackageManagerException e) {
12950            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12951        }
12952
12953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12954    }
12955
12956    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12957        // Can't rotate keys during boot or if sharedUser.
12958        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12959                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12960            return false;
12961        }
12962        // app is using upgradeKeySets; make sure all are valid
12963        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12964        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12965        for (int i = 0; i < upgradeKeySets.length; i++) {
12966            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12967                Slog.wtf(TAG, "Package "
12968                         + (oldPs.name != null ? oldPs.name : "<null>")
12969                         + " contains upgrade-key-set reference to unknown key-set: "
12970                         + upgradeKeySets[i]
12971                         + " reverting to signatures check.");
12972                return false;
12973            }
12974        }
12975        return true;
12976    }
12977
12978    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12979        // Upgrade keysets are being used.  Determine if new package has a superset of the
12980        // required keys.
12981        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12982        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12983        for (int i = 0; i < upgradeKeySets.length; i++) {
12984            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12985            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12986                return true;
12987            }
12988        }
12989        return false;
12990    }
12991
12992    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12993            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12994        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12995
12996        final PackageParser.Package oldPackage;
12997        final String pkgName = pkg.packageName;
12998        final int[] allUsers;
12999
13000        // First find the old package info and check signatures
13001        synchronized(mPackages) {
13002            oldPackage = mPackages.get(pkgName);
13003            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13004            if (isEphemeral && !oldIsEphemeral) {
13005                // can't downgrade from full to ephemeral
13006                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13007                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13008                return;
13009            }
13010            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13011            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13012            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13013                if (!checkUpgradeKeySetLP(ps, pkg)) {
13014                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13015                            "New package not signed by keys specified by upgrade-keysets: "
13016                                    + pkgName);
13017                    return;
13018                }
13019            } else {
13020                // default to original signature matching
13021                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13022                        != PackageManager.SIGNATURE_MATCH) {
13023                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13024                            "New package has a different signature: " + pkgName);
13025                    return;
13026                }
13027            }
13028
13029            // In case of rollback, remember per-user/profile install state
13030            allUsers = sUserManager.getUserIds();
13031        }
13032
13033        // Update what is removed
13034        res.removedInfo = new PackageRemovedInfo();
13035        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13036        res.removedInfo.removedPackage = oldPackage.packageName;
13037        res.removedInfo.isUpdate = true;
13038        final int childCount = (oldPackage.childPackages != null)
13039                ? oldPackage.childPackages.size() : 0;
13040        for (int i = 0; i < childCount; i++) {
13041            boolean childPackageUpdated = false;
13042            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13043            if (res.addedChildPackages != null) {
13044                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13045                if (childRes != null) {
13046                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13047                    childRes.removedInfo.removedPackage = childPkg.packageName;
13048                    childRes.removedInfo.isUpdate = true;
13049                    childPackageUpdated = true;
13050                }
13051            }
13052            if (!childPackageUpdated) {
13053                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13054                childRemovedRes.removedPackage = childPkg.packageName;
13055                childRemovedRes.isUpdate = false;
13056                childRemovedRes.dataRemoved = true;
13057                synchronized (mPackages) {
13058                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13059                    if (childPs != null) {
13060                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13061                    }
13062                }
13063                if (res.removedInfo.removedChildPackages == null) {
13064                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13065                }
13066                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13067            }
13068        }
13069
13070        boolean sysPkg = (isSystemApp(oldPackage));
13071        if (sysPkg) {
13072            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13073                    user, allUsers, installerPackageName, res);
13074        } else {
13075            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13076                    user, allUsers, installerPackageName, res);
13077        }
13078    }
13079
13080    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13081            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13082            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13083        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13084                + deletedPackage);
13085
13086        String pkgName = deletedPackage.packageName;
13087        boolean deletedPkg = true;
13088        boolean addedPkg = false;
13089
13090        final long origUpdateTime = (pkg.mExtras != null)
13091                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13092
13093        // First delete the existing package while retaining the data directory
13094        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13095                res.removedInfo, true, pkg)) {
13096            // If the existing package wasn't successfully deleted
13097            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13098            deletedPkg = false;
13099        } else {
13100            // Successfully deleted the old package; proceed with replace.
13101
13102            // If deleted package lived in a container, give users a chance to
13103            // relinquish resources before killing.
13104            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13105                if (DEBUG_INSTALL) {
13106                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13107                }
13108                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13109                final ArrayList<String> pkgList = new ArrayList<String>(1);
13110                pkgList.add(deletedPackage.applicationInfo.packageName);
13111                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13112            }
13113
13114            deleteCodeCacheDirsLI(pkg);
13115
13116            try {
13117                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13118                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13119                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13120                prepareAppDataAfterInstall(newPackage);
13121                addedPkg = true;
13122            } catch (PackageManagerException e) {
13123                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13124            }
13125        }
13126
13127        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13128            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13129
13130            // Revert all internal state mutations and added folders for the failed install
13131            if (addedPkg) {
13132                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13133                        res.removedInfo, true, null);
13134            }
13135
13136            // Restore the old package
13137            if (deletedPkg) {
13138                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13139                File restoreFile = new File(deletedPackage.codePath);
13140                // Parse old package
13141                boolean oldExternal = isExternal(deletedPackage);
13142                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13143                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13144                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13145                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13146                try {
13147                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13148                            null);
13149                } catch (PackageManagerException e) {
13150                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13151                            + e.getMessage());
13152                    return;
13153                }
13154
13155                synchronized (mPackages) {
13156                    // Ensure the installer package name up to date
13157                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13158
13159                    // Update permissions for restored package
13160                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13161
13162                    mSettings.writeLPr();
13163                }
13164
13165                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13166            }
13167        } else {
13168            synchronized (mPackages) {
13169                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13170                if (ps != null) {
13171                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13172                    if (res.removedInfo.removedChildPackages != null) {
13173                        final int childCount = res.removedInfo.removedChildPackages.size();
13174                        // Iterate in reverse as we may modify the collection
13175                        for (int i = childCount - 1; i >= 0; i--) {
13176                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13177                            if (res.addedChildPackages.containsKey(childPackageName)) {
13178                                res.removedInfo.removedChildPackages.removeAt(i);
13179                            } else {
13180                                PackageRemovedInfo childInfo = res.removedInfo
13181                                        .removedChildPackages.valueAt(i);
13182                                childInfo.removedForAllUsers = mPackages.get(
13183                                        childInfo.removedPackage) == null;
13184                            }
13185                        }
13186                    }
13187                }
13188            }
13189        }
13190    }
13191
13192    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13193            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13194            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13195        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13196                + ", old=" + deletedPackage);
13197
13198        final boolean disabledSystem;
13199
13200        // Set the system/privileged flags as needed
13201        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13202        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13203                != 0) {
13204            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13205        }
13206
13207        // Kill package processes including services, providers, etc.
13208        killPackage(deletedPackage, "replace sys pkg");
13209
13210        // Remove existing system package
13211        removePackageLI(deletedPackage, true);
13212
13213        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13214        if (!disabledSystem) {
13215            // We didn't need to disable the .apk as a current system package,
13216            // which means we are replacing another update that is already
13217            // installed.  We need to make sure to delete the older one's .apk.
13218            res.removedInfo.args = createInstallArgsForExisting(0,
13219                    deletedPackage.applicationInfo.getCodePath(),
13220                    deletedPackage.applicationInfo.getResourcePath(),
13221                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13222        } else {
13223            res.removedInfo.args = null;
13224        }
13225
13226        // Successfully disabled the old package. Now proceed with re-installation
13227        deleteCodeCacheDirsLI(pkg);
13228
13229        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13230        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13231                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13232
13233        PackageParser.Package newPackage = null;
13234        try {
13235            // Add the package to the internal data structures
13236            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13237
13238            // Set the update and install times
13239            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13240            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13241                    System.currentTimeMillis());
13242
13243            // Check for shared user id changes
13244            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13245                    deletedPackage, newPackage);
13246            if (invalidPackageName != null) {
13247                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13248                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13249                                + " to " + invalidPackageName);
13250            }
13251
13252            // Update the package dynamic state if succeeded
13253            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13254                // Now that the install succeeded make sure we remove data
13255                // directories for any child package the update removed.
13256                final int deletedChildCount = (deletedPackage.childPackages != null)
13257                        ? deletedPackage.childPackages.size() : 0;
13258                final int newChildCount = (newPackage.childPackages != null)
13259                        ? newPackage.childPackages.size() : 0;
13260                for (int i = 0; i < deletedChildCount; i++) {
13261                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13262                    boolean childPackageDeleted = true;
13263                    for (int j = 0; j < newChildCount; j++) {
13264                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13265                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13266                            childPackageDeleted = false;
13267                            break;
13268                        }
13269                    }
13270                    if (childPackageDeleted) {
13271                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13272                                deletedChildPkg.packageName);
13273                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13274                            PackageRemovedInfo removedChildRes = res.removedInfo
13275                                    .removedChildPackages.get(deletedChildPkg.packageName);
13276                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13277                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13278                        }
13279                    }
13280                }
13281
13282                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13283                prepareAppDataAfterInstall(newPackage);
13284            }
13285        } catch (PackageManagerException e) {
13286            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13287            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13288        }
13289
13290        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13291            // Re installation failed. Restore old information
13292            // Remove new pkg information
13293            if (newPackage != null) {
13294                removeInstalledPackageLI(newPackage, true);
13295            }
13296            // Add back the old system package
13297            try {
13298                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13299            } catch (PackageManagerException e) {
13300                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13301            }
13302
13303            synchronized (mPackages) {
13304                if (disabledSystem) {
13305                    enableSystemPackageLPw(deletedPackage);
13306                }
13307
13308                // Ensure the installer package name up to date
13309                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13310
13311                // Update permissions for restored package
13312                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13313
13314                mSettings.writeLPr();
13315            }
13316
13317            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13318                    + " after failed upgrade");
13319        }
13320    }
13321
13322    /**
13323     * Checks whether the parent or any of the child packages have a change shared
13324     * user. For a package to be a valid update the shred users of the parent and
13325     * the children should match. We may later support changing child shared users.
13326     * @param oldPkg The updated package.
13327     * @param newPkg The update package.
13328     * @return The shared user that change between the versions.
13329     */
13330    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13331            PackageParser.Package newPkg) {
13332        // Check parent shared user
13333        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13334            return newPkg.packageName;
13335        }
13336        // Check child shared users
13337        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13338        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13339        for (int i = 0; i < newChildCount; i++) {
13340            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13341            // If this child was present, did it have the same shared user?
13342            for (int j = 0; j < oldChildCount; j++) {
13343                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13344                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13345                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13346                    return newChildPkg.packageName;
13347                }
13348            }
13349        }
13350        return null;
13351    }
13352
13353    private void removeNativeBinariesLI(PackageSetting ps) {
13354        // Remove the lib path for the parent package
13355        if (ps != null) {
13356            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13357            // Remove the lib path for the child packages
13358            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13359            for (int i = 0; i < childCount; i++) {
13360                PackageSetting childPs = null;
13361                synchronized (mPackages) {
13362                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13363                }
13364                if (childPs != null) {
13365                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13366                            .legacyNativeLibraryPathString);
13367                }
13368            }
13369        }
13370    }
13371
13372    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13373        // Enable the parent package
13374        mSettings.enableSystemPackageLPw(pkg.packageName);
13375        // Enable the child packages
13376        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13377        for (int i = 0; i < childCount; i++) {
13378            PackageParser.Package childPkg = pkg.childPackages.get(i);
13379            mSettings.enableSystemPackageLPw(childPkg.packageName);
13380        }
13381    }
13382
13383    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13384            PackageParser.Package newPkg) {
13385        // Disable the parent package (parent always replaced)
13386        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13387        // Disable the child packages
13388        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13389        for (int i = 0; i < childCount; i++) {
13390            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13391            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13392            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13393        }
13394        return disabled;
13395    }
13396
13397    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13398            String installerPackageName) {
13399        // Enable the parent package
13400        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13401        // Enable the child packages
13402        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13403        for (int i = 0; i < childCount; i++) {
13404            PackageParser.Package childPkg = pkg.childPackages.get(i);
13405            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13406        }
13407    }
13408
13409    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13410        // Collect all used permissions in the UID
13411        ArraySet<String> usedPermissions = new ArraySet<>();
13412        final int packageCount = su.packages.size();
13413        for (int i = 0; i < packageCount; i++) {
13414            PackageSetting ps = su.packages.valueAt(i);
13415            if (ps.pkg == null) {
13416                continue;
13417            }
13418            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13419            for (int j = 0; j < requestedPermCount; j++) {
13420                String permission = ps.pkg.requestedPermissions.get(j);
13421                BasePermission bp = mSettings.mPermissions.get(permission);
13422                if (bp != null) {
13423                    usedPermissions.add(permission);
13424                }
13425            }
13426        }
13427
13428        PermissionsState permissionsState = su.getPermissionsState();
13429        // Prune install permissions
13430        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13431        final int installPermCount = installPermStates.size();
13432        for (int i = installPermCount - 1; i >= 0;  i--) {
13433            PermissionState permissionState = installPermStates.get(i);
13434            if (!usedPermissions.contains(permissionState.getName())) {
13435                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13436                if (bp != null) {
13437                    permissionsState.revokeInstallPermission(bp);
13438                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13439                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13440                }
13441            }
13442        }
13443
13444        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13445
13446        // Prune runtime permissions
13447        for (int userId : allUserIds) {
13448            List<PermissionState> runtimePermStates = permissionsState
13449                    .getRuntimePermissionStates(userId);
13450            final int runtimePermCount = runtimePermStates.size();
13451            for (int i = runtimePermCount - 1; i >= 0; i--) {
13452                PermissionState permissionState = runtimePermStates.get(i);
13453                if (!usedPermissions.contains(permissionState.getName())) {
13454                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13455                    if (bp != null) {
13456                        permissionsState.revokeRuntimePermission(bp, userId);
13457                        permissionsState.updatePermissionFlags(bp, userId,
13458                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13459                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13460                                runtimePermissionChangedUserIds, userId);
13461                    }
13462                }
13463            }
13464        }
13465
13466        return runtimePermissionChangedUserIds;
13467    }
13468
13469    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13470            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13471        // Update the parent package setting
13472        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13473                res, user);
13474        // Update the child packages setting
13475        final int childCount = (newPackage.childPackages != null)
13476                ? newPackage.childPackages.size() : 0;
13477        for (int i = 0; i < childCount; i++) {
13478            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13479            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13480            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13481                    childRes.origUsers, childRes, user);
13482        }
13483    }
13484
13485    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13486            String installerPackageName, int[] allUsers, int[] installedForUsers,
13487            PackageInstalledInfo res, UserHandle user) {
13488        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13489
13490        String pkgName = newPackage.packageName;
13491        synchronized (mPackages) {
13492            //write settings. the installStatus will be incomplete at this stage.
13493            //note that the new package setting would have already been
13494            //added to mPackages. It hasn't been persisted yet.
13495            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13497            mSettings.writeLPr();
13498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13499        }
13500
13501        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13502        synchronized (mPackages) {
13503            updatePermissionsLPw(newPackage.packageName, newPackage,
13504                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13505                            ? UPDATE_PERMISSIONS_ALL : 0));
13506            // For system-bundled packages, we assume that installing an upgraded version
13507            // of the package implies that the user actually wants to run that new code,
13508            // so we enable the package.
13509            PackageSetting ps = mSettings.mPackages.get(pkgName);
13510            final int userId = user.getIdentifier();
13511            if (ps != null) {
13512                if (isSystemApp(newPackage)) {
13513                    if (DEBUG_INSTALL) {
13514                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13515                    }
13516                    // Enable system package for requested users
13517                    if (res.origUsers != null) {
13518                        for (int origUserId : res.origUsers) {
13519                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13520                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13521                                        origUserId, installerPackageName);
13522                            }
13523                        }
13524                    }
13525                    // Also convey the prior install/uninstall state
13526                    if (allUsers != null && installedForUsers != null) {
13527                        for (int currentUserId : allUsers) {
13528                            final boolean installed = ArrayUtils.contains(
13529                                    installedForUsers, currentUserId);
13530                            if (DEBUG_INSTALL) {
13531                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13532                            }
13533                            ps.setInstalled(installed, currentUserId);
13534                        }
13535                        // these install state changes will be persisted in the
13536                        // upcoming call to mSettings.writeLPr().
13537                    }
13538                }
13539                // It's implied that when a user requests installation, they want the app to be
13540                // installed and enabled.
13541                if (userId != UserHandle.USER_ALL) {
13542                    ps.setInstalled(true, userId);
13543                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13544                }
13545            }
13546            res.name = pkgName;
13547            res.uid = newPackage.applicationInfo.uid;
13548            res.pkg = newPackage;
13549            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13550            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13551            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13552            //to update install status
13553            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13554            mSettings.writeLPr();
13555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13556        }
13557
13558        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13559    }
13560
13561    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13562        try {
13563            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13564            installPackageLI(args, res);
13565        } finally {
13566            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13567        }
13568    }
13569
13570    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13571        final int installFlags = args.installFlags;
13572        final String installerPackageName = args.installerPackageName;
13573        final String volumeUuid = args.volumeUuid;
13574        final File tmpPackageFile = new File(args.getCodePath());
13575        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13576        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13577                || (args.volumeUuid != null));
13578        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13579        boolean replace = false;
13580        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13581        if (args.move != null) {
13582            // moving a complete application; perform an initial scan on the new install location
13583            scanFlags |= SCAN_INITIAL;
13584        }
13585
13586        // Result object to be returned
13587        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13588
13589        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13590
13591        // Sanity check
13592        if (ephemeral && (forwardLocked || onExternal)) {
13593            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13594                    + " external=" + onExternal);
13595            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13596            return;
13597        }
13598
13599        // Retrieve PackageSettings and parse package
13600        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13601                | PackageParser.PARSE_ENFORCE_CODE
13602                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13603                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13604                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13605        PackageParser pp = new PackageParser();
13606        pp.setSeparateProcesses(mSeparateProcesses);
13607        pp.setDisplayMetrics(mMetrics);
13608
13609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13610        final PackageParser.Package pkg;
13611        try {
13612            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13613        } catch (PackageParserException e) {
13614            res.setError("Failed parse during installPackageLI", e);
13615            return;
13616        } finally {
13617            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13618        }
13619
13620        // If we are installing a clustered package add results for the children
13621        if (pkg.childPackages != null) {
13622            synchronized (mPackages) {
13623                final int childCount = pkg.childPackages.size();
13624                for (int i = 0; i < childCount; i++) {
13625                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13626                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13627                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13628                    childRes.pkg = childPkg;
13629                    childRes.name = childPkg.packageName;
13630                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13631                    if (childPs != null) {
13632                        childRes.origUsers = childPs.queryInstalledUsers(
13633                                sUserManager.getUserIds(), true);
13634                    }
13635                    if ((mPackages.containsKey(childPkg.packageName))) {
13636                        childRes.removedInfo = new PackageRemovedInfo();
13637                        childRes.removedInfo.removedPackage = childPkg.packageName;
13638                    }
13639                    if (res.addedChildPackages == null) {
13640                        res.addedChildPackages = new ArrayMap<>();
13641                    }
13642                    res.addedChildPackages.put(childPkg.packageName, childRes);
13643                }
13644            }
13645        }
13646
13647        // If package doesn't declare API override, mark that we have an install
13648        // time CPU ABI override.
13649        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13650            pkg.cpuAbiOverride = args.abiOverride;
13651        }
13652
13653        String pkgName = res.name = pkg.packageName;
13654        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13655            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13656                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13657                return;
13658            }
13659        }
13660
13661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13662        try {
13663            PackageParser.collectCertificates(pkg, parseFlags);
13664        } catch (PackageParserException e) {
13665            res.setError("Failed collect during installPackageLI", e);
13666            return;
13667        } finally {
13668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13669        }
13670
13671        // Get rid of all references to package scan path via parser.
13672        pp = null;
13673        String oldCodePath = null;
13674        boolean systemApp = false;
13675        synchronized (mPackages) {
13676            // Check if installing already existing package
13677            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13678                String oldName = mSettings.mRenamedPackages.get(pkgName);
13679                if (pkg.mOriginalPackages != null
13680                        && pkg.mOriginalPackages.contains(oldName)
13681                        && mPackages.containsKey(oldName)) {
13682                    // This package is derived from an original package,
13683                    // and this device has been updating from that original
13684                    // name.  We must continue using the original name, so
13685                    // rename the new package here.
13686                    pkg.setPackageName(oldName);
13687                    pkgName = pkg.packageName;
13688                    replace = true;
13689                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13690                            + oldName + " pkgName=" + pkgName);
13691                } else if (mPackages.containsKey(pkgName)) {
13692                    // This package, under its official name, already exists
13693                    // on the device; we should replace it.
13694                    replace = true;
13695                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13696                }
13697
13698                // Child packages are installed through the parent package
13699                if (pkg.parentPackage != null) {
13700                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13701                            "Package " + pkg.packageName + " is child of package "
13702                                    + pkg.parentPackage.parentPackage + ". Child packages "
13703                                    + "can be updated only through the parent package.");
13704                    return;
13705                }
13706
13707                if (replace) {
13708                    // Prevent apps opting out from runtime permissions
13709                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13710                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13711                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13712                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13713                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13714                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13715                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13716                                        + " doesn't support runtime permissions but the old"
13717                                        + " target SDK " + oldTargetSdk + " does.");
13718                        return;
13719                    }
13720
13721                    // Prevent installing of child packages
13722                    if (oldPackage.parentPackage != null) {
13723                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13724                                "Package " + pkg.packageName + " is child of package "
13725                                        + oldPackage.parentPackage + ". Child packages "
13726                                        + "can be updated only through the parent package.");
13727                        return;
13728                    }
13729                }
13730            }
13731
13732            PackageSetting ps = mSettings.mPackages.get(pkgName);
13733            if (ps != null) {
13734                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13735
13736                // Quick sanity check that we're signed correctly if updating;
13737                // we'll check this again later when scanning, but we want to
13738                // bail early here before tripping over redefined permissions.
13739                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13740                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13741                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13742                                + pkg.packageName + " upgrade keys do not match the "
13743                                + "previously installed version");
13744                        return;
13745                    }
13746                } else {
13747                    try {
13748                        verifySignaturesLP(ps, pkg);
13749                    } catch (PackageManagerException e) {
13750                        res.setError(e.error, e.getMessage());
13751                        return;
13752                    }
13753                }
13754
13755                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13756                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13757                    systemApp = (ps.pkg.applicationInfo.flags &
13758                            ApplicationInfo.FLAG_SYSTEM) != 0;
13759                }
13760                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13761            }
13762
13763            // Check whether the newly-scanned package wants to define an already-defined perm
13764            int N = pkg.permissions.size();
13765            for (int i = N-1; i >= 0; i--) {
13766                PackageParser.Permission perm = pkg.permissions.get(i);
13767                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13768                if (bp != null) {
13769                    // If the defining package is signed with our cert, it's okay.  This
13770                    // also includes the "updating the same package" case, of course.
13771                    // "updating same package" could also involve key-rotation.
13772                    final boolean sigsOk;
13773                    if (bp.sourcePackage.equals(pkg.packageName)
13774                            && (bp.packageSetting instanceof PackageSetting)
13775                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13776                                    scanFlags))) {
13777                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13778                    } else {
13779                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13780                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13781                    }
13782                    if (!sigsOk) {
13783                        // If the owning package is the system itself, we log but allow
13784                        // install to proceed; we fail the install on all other permission
13785                        // redefinitions.
13786                        if (!bp.sourcePackage.equals("android")) {
13787                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13788                                    + pkg.packageName + " attempting to redeclare permission "
13789                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13790                            res.origPermission = perm.info.name;
13791                            res.origPackage = bp.sourcePackage;
13792                            return;
13793                        } else {
13794                            Slog.w(TAG, "Package " + pkg.packageName
13795                                    + " attempting to redeclare system permission "
13796                                    + perm.info.name + "; ignoring new declaration");
13797                            pkg.permissions.remove(i);
13798                        }
13799                    }
13800                }
13801            }
13802        }
13803
13804        if (systemApp) {
13805            if (onExternal) {
13806                // Abort update; system app can't be replaced with app on sdcard
13807                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13808                        "Cannot install updates to system apps on sdcard");
13809                return;
13810            } else if (ephemeral) {
13811                // Abort update; system app can't be replaced with an ephemeral app
13812                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13813                        "Cannot update a system app with an ephemeral app");
13814                return;
13815            }
13816        }
13817
13818        if (args.move != null) {
13819            // We did an in-place move, so dex is ready to roll
13820            scanFlags |= SCAN_NO_DEX;
13821            scanFlags |= SCAN_MOVE;
13822
13823            synchronized (mPackages) {
13824                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13825                if (ps == null) {
13826                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13827                            "Missing settings for moved package " + pkgName);
13828                }
13829
13830                // We moved the entire application as-is, so bring over the
13831                // previously derived ABI information.
13832                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13833                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13834            }
13835
13836        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13837            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13838            scanFlags |= SCAN_NO_DEX;
13839
13840            try {
13841                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13842                    args.abiOverride : pkg.cpuAbiOverride);
13843                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13844                        true /* extract libs */);
13845            } catch (PackageManagerException pme) {
13846                Slog.e(TAG, "Error deriving application ABI", pme);
13847                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13848                return;
13849            }
13850
13851
13852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13853            // Do not run PackageDexOptimizer through the local performDexOpt
13854            // method because `pkg` is not in `mPackages` yet.
13855            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13856                    false /* useProfiles */, true /* extractOnly */);
13857            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13858            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13859                String msg = "Extracking package failed for " + pkgName;
13860                res.setError(INSTALL_FAILED_DEXOPT, msg);
13861                return;
13862            }
13863        }
13864
13865        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13866            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13867            return;
13868        }
13869
13870        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13871
13872        if (replace) {
13873            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13874                    installerPackageName, res);
13875        } else {
13876            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13877                    args.user, installerPackageName, volumeUuid, res);
13878        }
13879        synchronized (mPackages) {
13880            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13881            if (ps != null) {
13882                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13883            }
13884
13885            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13886            for (int i = 0; i < childCount; i++) {
13887                PackageParser.Package childPkg = pkg.childPackages.get(i);
13888                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13889                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13890                if (childPs != null) {
13891                    childRes.newUsers = childPs.queryInstalledUsers(
13892                            sUserManager.getUserIds(), true);
13893                }
13894            }
13895        }
13896    }
13897
13898    private void startIntentFilterVerifications(int userId, boolean replacing,
13899            PackageParser.Package pkg) {
13900        if (mIntentFilterVerifierComponent == null) {
13901            Slog.w(TAG, "No IntentFilter verification will not be done as "
13902                    + "there is no IntentFilterVerifier available!");
13903            return;
13904        }
13905
13906        final int verifierUid = getPackageUid(
13907                mIntentFilterVerifierComponent.getPackageName(),
13908                MATCH_DEBUG_TRIAGED_MISSING,
13909                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13910
13911        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13912        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13913        mHandler.sendMessage(msg);
13914
13915        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13916        for (int i = 0; i < childCount; i++) {
13917            PackageParser.Package childPkg = pkg.childPackages.get(i);
13918            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13919            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13920            mHandler.sendMessage(msg);
13921        }
13922    }
13923
13924    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13925            PackageParser.Package pkg) {
13926        int size = pkg.activities.size();
13927        if (size == 0) {
13928            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13929                    "No activity, so no need to verify any IntentFilter!");
13930            return;
13931        }
13932
13933        final boolean hasDomainURLs = hasDomainURLs(pkg);
13934        if (!hasDomainURLs) {
13935            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13936                    "No domain URLs, so no need to verify any IntentFilter!");
13937            return;
13938        }
13939
13940        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13941                + " if any IntentFilter from the " + size
13942                + " Activities needs verification ...");
13943
13944        int count = 0;
13945        final String packageName = pkg.packageName;
13946
13947        synchronized (mPackages) {
13948            // If this is a new install and we see that we've already run verification for this
13949            // package, we have nothing to do: it means the state was restored from backup.
13950            if (!replacing) {
13951                IntentFilterVerificationInfo ivi =
13952                        mSettings.getIntentFilterVerificationLPr(packageName);
13953                if (ivi != null) {
13954                    if (DEBUG_DOMAIN_VERIFICATION) {
13955                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13956                                + ivi.getStatusString());
13957                    }
13958                    return;
13959                }
13960            }
13961
13962            // If any filters need to be verified, then all need to be.
13963            boolean needToVerify = false;
13964            for (PackageParser.Activity a : pkg.activities) {
13965                for (ActivityIntentInfo filter : a.intents) {
13966                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13967                        if (DEBUG_DOMAIN_VERIFICATION) {
13968                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13969                        }
13970                        needToVerify = true;
13971                        break;
13972                    }
13973                }
13974            }
13975
13976            if (needToVerify) {
13977                final int verificationId = mIntentFilterVerificationToken++;
13978                for (PackageParser.Activity a : pkg.activities) {
13979                    for (ActivityIntentInfo filter : a.intents) {
13980                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13981                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13982                                    "Verification needed for IntentFilter:" + filter.toString());
13983                            mIntentFilterVerifier.addOneIntentFilterVerification(
13984                                    verifierUid, userId, verificationId, filter, packageName);
13985                            count++;
13986                        }
13987                    }
13988                }
13989            }
13990        }
13991
13992        if (count > 0) {
13993            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13994                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13995                    +  " for userId:" + userId);
13996            mIntentFilterVerifier.startVerifications(userId);
13997        } else {
13998            if (DEBUG_DOMAIN_VERIFICATION) {
13999                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14000            }
14001        }
14002    }
14003
14004    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14005        final ComponentName cn  = filter.activity.getComponentName();
14006        final String packageName = cn.getPackageName();
14007
14008        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14009                packageName);
14010        if (ivi == null) {
14011            return true;
14012        }
14013        int status = ivi.getStatus();
14014        switch (status) {
14015            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14016            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14017                return true;
14018
14019            default:
14020                // Nothing to do
14021                return false;
14022        }
14023    }
14024
14025    private static boolean isMultiArch(ApplicationInfo info) {
14026        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14027    }
14028
14029    private static boolean isExternal(PackageParser.Package pkg) {
14030        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14031    }
14032
14033    private static boolean isExternal(PackageSetting ps) {
14034        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14035    }
14036
14037    private static boolean isEphemeral(PackageParser.Package pkg) {
14038        return pkg.applicationInfo.isEphemeralApp();
14039    }
14040
14041    private static boolean isEphemeral(PackageSetting ps) {
14042        return ps.pkg != null && isEphemeral(ps.pkg);
14043    }
14044
14045    private static boolean isSystemApp(PackageParser.Package pkg) {
14046        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14047    }
14048
14049    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14050        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14051    }
14052
14053    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14054        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14055    }
14056
14057    private static boolean isSystemApp(PackageSetting ps) {
14058        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14059    }
14060
14061    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14062        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14063    }
14064
14065    private int packageFlagsToInstallFlags(PackageSetting ps) {
14066        int installFlags = 0;
14067        if (isEphemeral(ps)) {
14068            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14069        }
14070        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14071            // This existing package was an external ASEC install when we have
14072            // the external flag without a UUID
14073            installFlags |= PackageManager.INSTALL_EXTERNAL;
14074        }
14075        if (ps.isForwardLocked()) {
14076            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14077        }
14078        return installFlags;
14079    }
14080
14081    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14082        if (isExternal(pkg)) {
14083            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14084                return StorageManager.UUID_PRIMARY_PHYSICAL;
14085            } else {
14086                return pkg.volumeUuid;
14087            }
14088        } else {
14089            return StorageManager.UUID_PRIVATE_INTERNAL;
14090        }
14091    }
14092
14093    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14094        if (isExternal(pkg)) {
14095            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14096                return mSettings.getExternalVersion();
14097            } else {
14098                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14099            }
14100        } else {
14101            return mSettings.getInternalVersion();
14102        }
14103    }
14104
14105    private void deleteTempPackageFiles() {
14106        final FilenameFilter filter = new FilenameFilter() {
14107            public boolean accept(File dir, String name) {
14108                return name.startsWith("vmdl") && name.endsWith(".tmp");
14109            }
14110        };
14111        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14112            file.delete();
14113        }
14114    }
14115
14116    @Override
14117    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14118            int flags) {
14119        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14120                flags);
14121    }
14122
14123    @Override
14124    public void deletePackage(final String packageName,
14125            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14126        mContext.enforceCallingOrSelfPermission(
14127                android.Manifest.permission.DELETE_PACKAGES, null);
14128        Preconditions.checkNotNull(packageName);
14129        Preconditions.checkNotNull(observer);
14130        final int uid = Binder.getCallingUid();
14131        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14132        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14133        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14134            mContext.enforceCallingOrSelfPermission(
14135                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14136                    "deletePackage for user " + userId);
14137        }
14138
14139        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14140            try {
14141                observer.onPackageDeleted(packageName,
14142                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14143            } catch (RemoteException re) {
14144            }
14145            return;
14146        }
14147
14148        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14149            try {
14150                observer.onPackageDeleted(packageName,
14151                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14152            } catch (RemoteException re) {
14153            }
14154            return;
14155        }
14156
14157        if (DEBUG_REMOVE) {
14158            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14159                    + " deleteAllUsers: " + deleteAllUsers );
14160        }
14161        // Queue up an async operation since the package deletion may take a little while.
14162        mHandler.post(new Runnable() {
14163            public void run() {
14164                mHandler.removeCallbacks(this);
14165                int returnCode;
14166                if (!deleteAllUsers) {
14167                    returnCode = deletePackageX(packageName, userId, flags);
14168                } else {
14169                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14170                    // If nobody is blocking uninstall, proceed with delete for all users
14171                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14172                        returnCode = deletePackageX(packageName, userId, flags);
14173                    } else {
14174                        // Otherwise uninstall individually for users with blockUninstalls=false
14175                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14176                        for (int userId : users) {
14177                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14178                                returnCode = deletePackageX(packageName, userId, userFlags);
14179                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14180                                    Slog.w(TAG, "Package delete failed for user " + userId
14181                                            + ", returnCode " + returnCode);
14182                                }
14183                            }
14184                        }
14185                        // The app has only been marked uninstalled for certain users.
14186                        // We still need to report that delete was blocked
14187                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14188                    }
14189                }
14190                try {
14191                    observer.onPackageDeleted(packageName, returnCode, null);
14192                } catch (RemoteException e) {
14193                    Log.i(TAG, "Observer no longer exists.");
14194                } //end catch
14195            } //end run
14196        });
14197    }
14198
14199    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14200        int[] result = EMPTY_INT_ARRAY;
14201        for (int userId : userIds) {
14202            if (getBlockUninstallForUser(packageName, userId)) {
14203                result = ArrayUtils.appendInt(result, userId);
14204            }
14205        }
14206        return result;
14207    }
14208
14209    @Override
14210    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14211        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14212    }
14213
14214    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14215        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14216                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14217        try {
14218            if (dpm != null) {
14219                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14220                        /* callingUserOnly =*/ false);
14221                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14222                        : deviceOwnerComponentName.getPackageName();
14223                // Does the package contains the device owner?
14224                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14225                // this check is probably not needed, since DO should be registered as a device
14226                // admin on some user too. (Original bug for this: b/17657954)
14227                if (packageName.equals(deviceOwnerPackageName)) {
14228                    return true;
14229                }
14230                // Does it contain a device admin for any user?
14231                int[] users;
14232                if (userId == UserHandle.USER_ALL) {
14233                    users = sUserManager.getUserIds();
14234                } else {
14235                    users = new int[]{userId};
14236                }
14237                for (int i = 0; i < users.length; ++i) {
14238                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14239                        return true;
14240                    }
14241                }
14242            }
14243        } catch (RemoteException e) {
14244        }
14245        return false;
14246    }
14247
14248    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14249        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14250    }
14251
14252    /**
14253     *  This method is an internal method that could be get invoked either
14254     *  to delete an installed package or to clean up a failed installation.
14255     *  After deleting an installed package, a broadcast is sent to notify any
14256     *  listeners that the package has been installed. For cleaning up a failed
14257     *  installation, the broadcast is not necessary since the package's
14258     *  installation wouldn't have sent the initial broadcast either
14259     *  The key steps in deleting a package are
14260     *  deleting the package information in internal structures like mPackages,
14261     *  deleting the packages base directories through installd
14262     *  updating mSettings to reflect current status
14263     *  persisting settings for later use
14264     *  sending a broadcast if necessary
14265     */
14266    private int deletePackageX(String packageName, int userId, int flags) {
14267        final PackageRemovedInfo info = new PackageRemovedInfo();
14268        final boolean res;
14269
14270        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14271                ? UserHandle.ALL : new UserHandle(userId);
14272
14273        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14274            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14275            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14276        }
14277
14278        PackageSetting uninstalledPs = null;
14279
14280        // for the uninstall-updates case and restricted profiles, remember the per-
14281        // user handle installed state
14282        int[] allUsers;
14283        synchronized (mPackages) {
14284            uninstalledPs = mSettings.mPackages.get(packageName);
14285            if (uninstalledPs == null) {
14286                Slog.w(TAG, "Not removing non-existent package " + packageName);
14287                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14288            }
14289            allUsers = sUserManager.getUserIds();
14290            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14291        }
14292
14293        synchronized (mInstallLock) {
14294            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14295            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14296                    flags | REMOVE_CHATTY, info, true, null);
14297            synchronized (mPackages) {
14298                if (res) {
14299                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14300                }
14301            }
14302        }
14303
14304        if (res) {
14305            info.sendPackageRemovedBroadcasts();
14306            info.sendSystemPackageUpdatedBroadcasts();
14307            info.sendSystemPackageAppearedBroadcasts();
14308        }
14309        // Force a gc here.
14310        Runtime.getRuntime().gc();
14311        // Delete the resources here after sending the broadcast to let
14312        // other processes clean up before deleting resources.
14313        if (info.args != null) {
14314            synchronized (mInstallLock) {
14315                info.args.doPostDeleteLI(true);
14316            }
14317        }
14318
14319        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14320    }
14321
14322    class PackageRemovedInfo {
14323        String removedPackage;
14324        int uid = -1;
14325        int removedAppId = -1;
14326        int[] origUsers;
14327        int[] removedUsers = null;
14328        boolean isRemovedPackageSystemUpdate = false;
14329        boolean isUpdate;
14330        boolean dataRemoved;
14331        boolean removedForAllUsers;
14332        // Clean up resources deleted packages.
14333        InstallArgs args = null;
14334        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14335        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14336
14337        void sendPackageRemovedBroadcasts() {
14338            sendPackageRemovedBroadcastInternal();
14339            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14340            for (int i = 0; i < childCount; i++) {
14341                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14342                childInfo.sendPackageRemovedBroadcastInternal();
14343            }
14344        }
14345
14346        void sendSystemPackageUpdatedBroadcasts() {
14347            if (isRemovedPackageSystemUpdate) {
14348                sendSystemPackageUpdatedBroadcastsInternal();
14349                final int childCount = (removedChildPackages != null)
14350                        ? removedChildPackages.size() : 0;
14351                for (int i = 0; i < childCount; i++) {
14352                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14353                    if (childInfo.isRemovedPackageSystemUpdate) {
14354                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14355                    }
14356                }
14357            }
14358        }
14359
14360        void sendSystemPackageAppearedBroadcasts() {
14361            final int packageCount = (appearedChildPackages != null)
14362                    ? appearedChildPackages.size() : 0;
14363            for (int i = 0; i < packageCount; i++) {
14364                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14365                for (int userId : installedInfo.newUsers) {
14366                    sendPackageAddedForUser(installedInfo.name, true,
14367                            UserHandle.getAppId(installedInfo.uid), userId);
14368                }
14369            }
14370        }
14371
14372        private void sendSystemPackageUpdatedBroadcastsInternal() {
14373            Bundle extras = new Bundle(2);
14374            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14375            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14376            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14377                    extras, 0, null, null, null);
14378            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14379                    extras, 0, null, null, null);
14380            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14381                    null, 0, removedPackage, null, null);
14382        }
14383
14384        private void sendPackageRemovedBroadcastInternal() {
14385            Bundle extras = new Bundle(2);
14386            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14387            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14388            if (isUpdate || isRemovedPackageSystemUpdate) {
14389                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14390            }
14391            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14392            if (removedPackage != null) {
14393                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14394                        extras, 0, null, null, removedUsers);
14395                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14396                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14397                            removedPackage, extras, 0, null, null, removedUsers);
14398                }
14399            }
14400            if (removedAppId >= 0) {
14401                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14402                        removedUsers);
14403            }
14404        }
14405    }
14406
14407    /*
14408     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14409     * flag is not set, the data directory is removed as well.
14410     * make sure this flag is set for partially installed apps. If not its meaningless to
14411     * delete a partially installed application.
14412     */
14413    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14414            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14415        String packageName = ps.name;
14416        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14417        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14418        // Retrieve object to delete permissions for shared user later on
14419        final PackageSetting deletedPs;
14420        // reader
14421        synchronized (mPackages) {
14422            deletedPs = mSettings.mPackages.get(packageName);
14423            if (outInfo != null) {
14424                outInfo.removedPackage = packageName;
14425                outInfo.removedUsers = deletedPs != null
14426                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14427                        : null;
14428            }
14429        }
14430        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14431            removeDataDirsLI(ps.volumeUuid, packageName);
14432            if (outInfo != null) {
14433                outInfo.dataRemoved = true;
14434            }
14435            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14436        }
14437        // writer
14438        synchronized (mPackages) {
14439            if (deletedPs != null) {
14440                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14441                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14442                    clearDefaultBrowserIfNeeded(packageName);
14443                    if (outInfo != null) {
14444                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14445                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14446                    }
14447                    updatePermissionsLPw(deletedPs.name, null, 0);
14448                    if (deletedPs.sharedUser != null) {
14449                        // Remove permissions associated with package. Since runtime
14450                        // permissions are per user we have to kill the removed package
14451                        // or packages running under the shared user of the removed
14452                        // package if revoking the permissions requested only by the removed
14453                        // package is successful and this causes a change in gids.
14454                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14455                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14456                                    userId);
14457                            if (userIdToKill == UserHandle.USER_ALL
14458                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14459                                // If gids changed for this user, kill all affected packages.
14460                                mHandler.post(new Runnable() {
14461                                    @Override
14462                                    public void run() {
14463                                        // This has to happen with no lock held.
14464                                        killApplication(deletedPs.name, deletedPs.appId,
14465                                                KILL_APP_REASON_GIDS_CHANGED);
14466                                    }
14467                                });
14468                                break;
14469                            }
14470                        }
14471                    }
14472                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14473                }
14474                // make sure to preserve per-user disabled state if this removal was just
14475                // a downgrade of a system app to the factory package
14476                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14477                    if (DEBUG_REMOVE) {
14478                        Slog.d(TAG, "Propagating install state across downgrade");
14479                    }
14480                    for (int userId : allUserHandles) {
14481                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14482                        if (DEBUG_REMOVE) {
14483                            Slog.d(TAG, "    user " + userId + " => " + installed);
14484                        }
14485                        ps.setInstalled(installed, userId);
14486                    }
14487                }
14488            }
14489            // can downgrade to reader
14490            if (writeSettings) {
14491                // Save settings now
14492                mSettings.writeLPr();
14493            }
14494        }
14495        if (outInfo != null) {
14496            // A user ID was deleted here. Go through all users and remove it
14497            // from KeyStore.
14498            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14499        }
14500    }
14501
14502    static boolean locationIsPrivileged(File path) {
14503        try {
14504            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14505                    .getCanonicalPath();
14506            return path.getCanonicalPath().startsWith(privilegedAppDir);
14507        } catch (IOException e) {
14508            Slog.e(TAG, "Unable to access code path " + path);
14509        }
14510        return false;
14511    }
14512
14513    /*
14514     * Tries to delete system package.
14515     */
14516    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14517            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14518            boolean writeSettings) {
14519        if (deletedPs.parentPackageName != null) {
14520            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14521            return false;
14522        }
14523
14524        final boolean applyUserRestrictions
14525                = (allUserHandles != null) && (outInfo.origUsers != null);
14526        final PackageSetting disabledPs;
14527        // Confirm if the system package has been updated
14528        // An updated system app can be deleted. This will also have to restore
14529        // the system pkg from system partition
14530        // reader
14531        synchronized (mPackages) {
14532            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14533        }
14534
14535        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14536                + " disabledPs=" + disabledPs);
14537
14538        if (disabledPs == null) {
14539            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14540            return false;
14541        } else if (DEBUG_REMOVE) {
14542            Slog.d(TAG, "Deleting system pkg from data partition");
14543        }
14544
14545        if (DEBUG_REMOVE) {
14546            if (applyUserRestrictions) {
14547                Slog.d(TAG, "Remembering install states:");
14548                for (int userId : allUserHandles) {
14549                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14550                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14551                }
14552            }
14553        }
14554
14555        // Delete the updated package
14556        outInfo.isRemovedPackageSystemUpdate = true;
14557        if (outInfo.removedChildPackages != null) {
14558            final int childCount = (deletedPs.childPackageNames != null)
14559                    ? deletedPs.childPackageNames.size() : 0;
14560            for (int i = 0; i < childCount; i++) {
14561                String childPackageName = deletedPs.childPackageNames.get(i);
14562                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14563                        .contains(childPackageName)) {
14564                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14565                            childPackageName);
14566                    if (childInfo != null) {
14567                        childInfo.isRemovedPackageSystemUpdate = true;
14568                    }
14569                }
14570            }
14571        }
14572
14573        if (disabledPs.versionCode < deletedPs.versionCode) {
14574            // Delete data for downgrades
14575            flags &= ~PackageManager.DELETE_KEEP_DATA;
14576        } else {
14577            // Preserve data by setting flag
14578            flags |= PackageManager.DELETE_KEEP_DATA;
14579        }
14580
14581        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14582                outInfo, writeSettings, disabledPs.pkg);
14583        if (!ret) {
14584            return false;
14585        }
14586
14587        // writer
14588        synchronized (mPackages) {
14589            // Reinstate the old system package
14590            enableSystemPackageLPw(disabledPs.pkg);
14591            // Remove any native libraries from the upgraded package.
14592            removeNativeBinariesLI(deletedPs);
14593        }
14594
14595        // Install the system package
14596        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14597        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14598        if (locationIsPrivileged(disabledPs.codePath)) {
14599            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14600        }
14601
14602        final PackageParser.Package newPkg;
14603        try {
14604            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14605        } catch (PackageManagerException e) {
14606            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14607                    + e.getMessage());
14608            return false;
14609        }
14610
14611        prepareAppDataAfterInstall(newPkg);
14612
14613        // writer
14614        synchronized (mPackages) {
14615            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14616
14617            // Propagate the permissions state as we do not want to drop on the floor
14618            // runtime permissions. The update permissions method below will take
14619            // care of removing obsolete permissions and grant install permissions.
14620            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14621            updatePermissionsLPw(newPkg.packageName, newPkg,
14622                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14623
14624            if (applyUserRestrictions) {
14625                if (DEBUG_REMOVE) {
14626                    Slog.d(TAG, "Propagating install state across reinstall");
14627                }
14628                for (int userId : allUserHandles) {
14629                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14630                    if (DEBUG_REMOVE) {
14631                        Slog.d(TAG, "    user " + userId + " => " + installed);
14632                    }
14633                    ps.setInstalled(installed, userId);
14634
14635                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14636                }
14637                // Regardless of writeSettings we need to ensure that this restriction
14638                // state propagation is persisted
14639                mSettings.writeAllUsersPackageRestrictionsLPr();
14640            }
14641            // can downgrade to reader here
14642            if (writeSettings) {
14643                mSettings.writeLPr();
14644            }
14645        }
14646        return true;
14647    }
14648
14649    private boolean deleteInstalledPackageLI(PackageSetting ps,
14650            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14651            PackageRemovedInfo outInfo, boolean writeSettings,
14652            PackageParser.Package replacingPackage) {
14653        synchronized (mPackages) {
14654            if (outInfo != null) {
14655                outInfo.uid = ps.appId;
14656            }
14657
14658            if (outInfo != null && outInfo.removedChildPackages != null) {
14659                final int childCount = (ps.childPackageNames != null)
14660                        ? ps.childPackageNames.size() : 0;
14661                for (int i = 0; i < childCount; i++) {
14662                    String childPackageName = ps.childPackageNames.get(i);
14663                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14664                    if (childPs == null) {
14665                        return false;
14666                    }
14667                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14668                            childPackageName);
14669                    if (childInfo != null) {
14670                        childInfo.uid = childPs.appId;
14671                    }
14672                }
14673            }
14674        }
14675
14676        // Delete package data from internal structures and also remove data if flag is set
14677        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14678
14679        // Delete the child packages data
14680        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14681        for (int i = 0; i < childCount; i++) {
14682            PackageSetting childPs;
14683            synchronized (mPackages) {
14684                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14685            }
14686            if (childPs != null) {
14687                PackageRemovedInfo childOutInfo = (outInfo != null
14688                        && outInfo.removedChildPackages != null)
14689                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14690                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14691                        && (replacingPackage != null
14692                        && !replacingPackage.hasChildPackage(childPs.name))
14693                        ? flags & ~DELETE_KEEP_DATA : flags;
14694                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14695                        deleteFlags, writeSettings);
14696            }
14697        }
14698
14699        // Delete application code and resources only for parent packages
14700        if (ps.parentPackageName == null) {
14701            if (deleteCodeAndResources && (outInfo != null)) {
14702                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14703                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14704                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14705            }
14706        }
14707
14708        return true;
14709    }
14710
14711    @Override
14712    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14713            int userId) {
14714        mContext.enforceCallingOrSelfPermission(
14715                android.Manifest.permission.DELETE_PACKAGES, null);
14716        synchronized (mPackages) {
14717            PackageSetting ps = mSettings.mPackages.get(packageName);
14718            if (ps == null) {
14719                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14720                return false;
14721            }
14722            if (!ps.getInstalled(userId)) {
14723                // Can't block uninstall for an app that is not installed or enabled.
14724                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14725                return false;
14726            }
14727            ps.setBlockUninstall(blockUninstall, userId);
14728            mSettings.writePackageRestrictionsLPr(userId);
14729        }
14730        return true;
14731    }
14732
14733    @Override
14734    public boolean getBlockUninstallForUser(String packageName, int userId) {
14735        synchronized (mPackages) {
14736            PackageSetting ps = mSettings.mPackages.get(packageName);
14737            if (ps == null) {
14738                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14739                return false;
14740            }
14741            return ps.getBlockUninstall(userId);
14742        }
14743    }
14744
14745    @Override
14746    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14747        int callingUid = Binder.getCallingUid();
14748        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14749            throw new SecurityException(
14750                    "setRequiredForSystemUser can only be run by the system or root");
14751        }
14752        synchronized (mPackages) {
14753            PackageSetting ps = mSettings.mPackages.get(packageName);
14754            if (ps == null) {
14755                Log.w(TAG, "Package doesn't exist: " + packageName);
14756                return false;
14757            }
14758            if (systemUserApp) {
14759                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14760            } else {
14761                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14762            }
14763            mSettings.writeLPr();
14764        }
14765        return true;
14766    }
14767
14768    /*
14769     * This method handles package deletion in general
14770     */
14771    private boolean deletePackageLI(String packageName, UserHandle user,
14772            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14773            PackageRemovedInfo outInfo, boolean writeSettings,
14774            PackageParser.Package replacingPackage) {
14775        if (packageName == null) {
14776            Slog.w(TAG, "Attempt to delete null packageName.");
14777            return false;
14778        }
14779
14780        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14781
14782        PackageSetting ps;
14783
14784        synchronized (mPackages) {
14785            ps = mSettings.mPackages.get(packageName);
14786            if (ps == null) {
14787                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14788                return false;
14789            }
14790
14791            if (ps.parentPackageName != null && (!isSystemApp(ps)
14792                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14793                if (DEBUG_REMOVE) {
14794                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14795                            + ((user == null) ? UserHandle.USER_ALL : user));
14796                }
14797                final int removedUserId = (user != null) ? user.getIdentifier()
14798                        : UserHandle.USER_ALL;
14799                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14800                    return false;
14801                }
14802                markPackageUninstalledForUserLPw(ps, user);
14803                scheduleWritePackageRestrictionsLocked(user);
14804                return true;
14805            }
14806        }
14807
14808        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14809                && user.getIdentifier() != UserHandle.USER_ALL)) {
14810            // The caller is asking that the package only be deleted for a single
14811            // user.  To do this, we just mark its uninstalled state and delete
14812            // its data. If this is a system app, we only allow this to happen if
14813            // they have set the special DELETE_SYSTEM_APP which requests different
14814            // semantics than normal for uninstalling system apps.
14815            markPackageUninstalledForUserLPw(ps, user);
14816
14817            if (!isSystemApp(ps)) {
14818                // Do not uninstall the APK if an app should be cached
14819                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14820                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14821                    // Other user still have this package installed, so all
14822                    // we need to do is clear this user's data and save that
14823                    // it is uninstalled.
14824                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14825                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14826                        return false;
14827                    }
14828                    scheduleWritePackageRestrictionsLocked(user);
14829                    return true;
14830                } else {
14831                    // We need to set it back to 'installed' so the uninstall
14832                    // broadcasts will be sent correctly.
14833                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14834                    ps.setInstalled(true, user.getIdentifier());
14835                }
14836            } else {
14837                // This is a system app, so we assume that the
14838                // other users still have this package installed, so all
14839                // we need to do is clear this user's data and save that
14840                // it is uninstalled.
14841                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14842                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14843                    return false;
14844                }
14845                scheduleWritePackageRestrictionsLocked(user);
14846                return true;
14847            }
14848        }
14849
14850        // If we are deleting a composite package for all users, keep track
14851        // of result for each child.
14852        if (ps.childPackageNames != null && outInfo != null) {
14853            synchronized (mPackages) {
14854                final int childCount = ps.childPackageNames.size();
14855                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14856                for (int i = 0; i < childCount; i++) {
14857                    String childPackageName = ps.childPackageNames.get(i);
14858                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14859                    childInfo.removedPackage = childPackageName;
14860                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14861                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14862                    if (childPs != null) {
14863                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14864                    }
14865                }
14866            }
14867        }
14868
14869        boolean ret = false;
14870        if (isSystemApp(ps)) {
14871            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14872            // When an updated system application is deleted we delete the existing resources
14873            // as well and fall back to existing code in system partition
14874            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14875        } else {
14876            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14877            // Kill application pre-emptively especially for apps on sd.
14878            killApplication(packageName, ps.appId, "uninstall pkg");
14879            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
14880                    outInfo, writeSettings, replacingPackage);
14881        }
14882
14883        // Take a note whether we deleted the package for all users
14884        if (outInfo != null) {
14885            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14886            if (outInfo.removedChildPackages != null) {
14887                synchronized (mPackages) {
14888                    final int childCount = outInfo.removedChildPackages.size();
14889                    for (int i = 0; i < childCount; i++) {
14890                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14891                        if (childInfo != null) {
14892                            childInfo.removedForAllUsers = mPackages.get(
14893                                    childInfo.removedPackage) == null;
14894                        }
14895                    }
14896                }
14897            }
14898            // If we uninstalled an update to a system app there may be some
14899            // child packages that appeared as they are declared in the system
14900            // app but were not declared in the update.
14901            if (isSystemApp(ps)) {
14902                synchronized (mPackages) {
14903                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14904                    final int childCount = (updatedPs.childPackageNames != null)
14905                            ? updatedPs.childPackageNames.size() : 0;
14906                    for (int i = 0; i < childCount; i++) {
14907                        String childPackageName = updatedPs.childPackageNames.get(i);
14908                        if (outInfo.removedChildPackages == null
14909                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14910                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14911                            if (childPs == null) {
14912                                continue;
14913                            }
14914                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14915                            installRes.name = childPackageName;
14916                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14917                            installRes.pkg = mPackages.get(childPackageName);
14918                            installRes.uid = childPs.pkg.applicationInfo.uid;
14919                            if (outInfo.appearedChildPackages == null) {
14920                                outInfo.appearedChildPackages = new ArrayMap<>();
14921                            }
14922                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14923                        }
14924                    }
14925                }
14926            }
14927        }
14928
14929        return ret;
14930    }
14931
14932    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14933        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14934                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14935        for (int nextUserId : userIds) {
14936            if (DEBUG_REMOVE) {
14937                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14938            }
14939            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14940                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14941                    false /*hidden*/, false /*suspended*/, null, null, null,
14942                    false /*blockUninstall*/,
14943                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14944        }
14945    }
14946
14947    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14948            PackageRemovedInfo outInfo) {
14949        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14950                : new int[] {userId};
14951        for (int nextUserId : userIds) {
14952            if (DEBUG_REMOVE) {
14953                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14954                        + nextUserId);
14955            }
14956            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14957            try {
14958                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14959            } catch (InstallerException e) {
14960                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14961                return false;
14962            }
14963            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14964            schedulePackageCleaning(ps.name, nextUserId, false);
14965            synchronized (mPackages) {
14966                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14967                    scheduleWritePackageRestrictionsLocked(nextUserId);
14968                }
14969                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14970            }
14971        }
14972
14973        if (outInfo != null) {
14974            outInfo.removedPackage = ps.name;
14975            outInfo.removedAppId = ps.appId;
14976            outInfo.removedUsers = userIds;
14977        }
14978
14979        return true;
14980    }
14981
14982    private final class ClearStorageConnection implements ServiceConnection {
14983        IMediaContainerService mContainerService;
14984
14985        @Override
14986        public void onServiceConnected(ComponentName name, IBinder service) {
14987            synchronized (this) {
14988                mContainerService = IMediaContainerService.Stub.asInterface(service);
14989                notifyAll();
14990            }
14991        }
14992
14993        @Override
14994        public void onServiceDisconnected(ComponentName name) {
14995        }
14996    }
14997
14998    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14999        final boolean mounted;
15000        if (Environment.isExternalStorageEmulated()) {
15001            mounted = true;
15002        } else {
15003            final String status = Environment.getExternalStorageState();
15004
15005            mounted = status.equals(Environment.MEDIA_MOUNTED)
15006                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15007        }
15008
15009        if (!mounted) {
15010            return;
15011        }
15012
15013        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15014        int[] users;
15015        if (userId == UserHandle.USER_ALL) {
15016            users = sUserManager.getUserIds();
15017        } else {
15018            users = new int[] { userId };
15019        }
15020        final ClearStorageConnection conn = new ClearStorageConnection();
15021        if (mContext.bindServiceAsUser(
15022                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15023            try {
15024                for (int curUser : users) {
15025                    long timeout = SystemClock.uptimeMillis() + 5000;
15026                    synchronized (conn) {
15027                        long now = SystemClock.uptimeMillis();
15028                        while (conn.mContainerService == null && now < timeout) {
15029                            try {
15030                                conn.wait(timeout - now);
15031                            } catch (InterruptedException e) {
15032                            }
15033                        }
15034                    }
15035                    if (conn.mContainerService == null) {
15036                        return;
15037                    }
15038
15039                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15040                    clearDirectory(conn.mContainerService,
15041                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15042                    if (allData) {
15043                        clearDirectory(conn.mContainerService,
15044                                userEnv.buildExternalStorageAppDataDirs(packageName));
15045                        clearDirectory(conn.mContainerService,
15046                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15047                    }
15048                }
15049            } finally {
15050                mContext.unbindService(conn);
15051            }
15052        }
15053    }
15054
15055    @Override
15056    public void clearApplicationUserData(final String packageName,
15057            final IPackageDataObserver observer, final int userId) {
15058        mContext.enforceCallingOrSelfPermission(
15059                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15061                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15062        // Queue up an async operation since the package deletion may take a little while.
15063        mHandler.post(new Runnable() {
15064            public void run() {
15065                mHandler.removeCallbacks(this);
15066                final boolean succeeded;
15067                synchronized (mInstallLock) {
15068                    succeeded = clearApplicationUserDataLI(packageName, userId);
15069                }
15070                clearExternalStorageDataSync(packageName, userId, true);
15071                if (succeeded) {
15072                    // invoke DeviceStorageMonitor's update method to clear any notifications
15073                    DeviceStorageMonitorInternal
15074                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15075                    if (dsm != null) {
15076                        dsm.checkMemory();
15077                    }
15078                }
15079                if(observer != null) {
15080                    try {
15081                        observer.onRemoveCompleted(packageName, succeeded);
15082                    } catch (RemoteException e) {
15083                        Log.i(TAG, "Observer no longer exists.");
15084                    }
15085                } //end if observer
15086            } //end run
15087        });
15088    }
15089
15090    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15091        if (packageName == null) {
15092            Slog.w(TAG, "Attempt to delete null packageName.");
15093            return false;
15094        }
15095
15096        // Try finding details about the requested package
15097        PackageParser.Package pkg;
15098        synchronized (mPackages) {
15099            pkg = mPackages.get(packageName);
15100            if (pkg == null) {
15101                final PackageSetting ps = mSettings.mPackages.get(packageName);
15102                if (ps != null) {
15103                    pkg = ps.pkg;
15104                }
15105            }
15106
15107            if (pkg == null) {
15108                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15109                return false;
15110            }
15111
15112            PackageSetting ps = (PackageSetting) pkg.mExtras;
15113            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15114        }
15115
15116        // Always delete data directories for package, even if we found no other
15117        // record of app. This helps users recover from UID mismatches without
15118        // resorting to a full data wipe.
15119        // TODO: triage flags as part of 26466827
15120        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15121        try {
15122            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15123        } catch (InstallerException e) {
15124            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15125            return false;
15126        }
15127
15128        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15129        removeKeystoreDataIfNeeded(userId, appId);
15130
15131        // Create a native library symlink only if we have native libraries
15132        // and if the native libraries are 32 bit libraries. We do not provide
15133        // this symlink for 64 bit libraries.
15134        if (pkg.applicationInfo.primaryCpuAbi != null &&
15135                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15136            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15137            try {
15138                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15139                        nativeLibPath, userId);
15140            } catch (InstallerException e) {
15141                Slog.w(TAG, "Failed linking native library dir", e);
15142                return false;
15143            }
15144        }
15145
15146        return true;
15147    }
15148
15149    /**
15150     * Reverts user permission state changes (permissions and flags) in
15151     * all packages for a given user.
15152     *
15153     * @param userId The device user for which to do a reset.
15154     */
15155    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15156        final int packageCount = mPackages.size();
15157        for (int i = 0; i < packageCount; i++) {
15158            PackageParser.Package pkg = mPackages.valueAt(i);
15159            PackageSetting ps = (PackageSetting) pkg.mExtras;
15160            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15161        }
15162    }
15163
15164    /**
15165     * Reverts user permission state changes (permissions and flags).
15166     *
15167     * @param ps The package for which to reset.
15168     * @param userId The device user for which to do a reset.
15169     */
15170    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15171            final PackageSetting ps, final int userId) {
15172        if (ps.pkg == null) {
15173            return;
15174        }
15175
15176        // These are flags that can change base on user actions.
15177        final int userSettableMask = FLAG_PERMISSION_USER_SET
15178                | FLAG_PERMISSION_USER_FIXED
15179                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15180                | FLAG_PERMISSION_REVIEW_REQUIRED;
15181
15182        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15183                | FLAG_PERMISSION_POLICY_FIXED;
15184
15185        boolean writeInstallPermissions = false;
15186        boolean writeRuntimePermissions = false;
15187
15188        final int permissionCount = ps.pkg.requestedPermissions.size();
15189        for (int i = 0; i < permissionCount; i++) {
15190            String permission = ps.pkg.requestedPermissions.get(i);
15191
15192            BasePermission bp = mSettings.mPermissions.get(permission);
15193            if (bp == null) {
15194                continue;
15195            }
15196
15197            // If shared user we just reset the state to which only this app contributed.
15198            if (ps.sharedUser != null) {
15199                boolean used = false;
15200                final int packageCount = ps.sharedUser.packages.size();
15201                for (int j = 0; j < packageCount; j++) {
15202                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15203                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15204                            && pkg.pkg.requestedPermissions.contains(permission)) {
15205                        used = true;
15206                        break;
15207                    }
15208                }
15209                if (used) {
15210                    continue;
15211                }
15212            }
15213
15214            PermissionsState permissionsState = ps.getPermissionsState();
15215
15216            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15217
15218            // Always clear the user settable flags.
15219            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15220                    bp.name) != null;
15221            // If permission review is enabled and this is a legacy app, mark the
15222            // permission as requiring a review as this is the initial state.
15223            int flags = 0;
15224            if (Build.PERMISSIONS_REVIEW_REQUIRED
15225                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15226                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15227            }
15228            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15229                if (hasInstallState) {
15230                    writeInstallPermissions = true;
15231                } else {
15232                    writeRuntimePermissions = true;
15233                }
15234            }
15235
15236            // Below is only runtime permission handling.
15237            if (!bp.isRuntime()) {
15238                continue;
15239            }
15240
15241            // Never clobber system or policy.
15242            if ((oldFlags & policyOrSystemFlags) != 0) {
15243                continue;
15244            }
15245
15246            // If this permission was granted by default, make sure it is.
15247            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15248                if (permissionsState.grantRuntimePermission(bp, userId)
15249                        != PERMISSION_OPERATION_FAILURE) {
15250                    writeRuntimePermissions = true;
15251                }
15252            // If permission review is enabled the permissions for a legacy apps
15253            // are represented as constantly granted runtime ones, so don't revoke.
15254            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15255                // Otherwise, reset the permission.
15256                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15257                switch (revokeResult) {
15258                    case PERMISSION_OPERATION_SUCCESS: {
15259                        writeRuntimePermissions = true;
15260                    } break;
15261
15262                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15263                        writeRuntimePermissions = true;
15264                        final int appId = ps.appId;
15265                        mHandler.post(new Runnable() {
15266                            @Override
15267                            public void run() {
15268                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15269                            }
15270                        });
15271                    } break;
15272                }
15273            }
15274        }
15275
15276        // Synchronously write as we are taking permissions away.
15277        if (writeRuntimePermissions) {
15278            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15279        }
15280
15281        // Synchronously write as we are taking permissions away.
15282        if (writeInstallPermissions) {
15283            mSettings.writeLPr();
15284        }
15285    }
15286
15287    /**
15288     * Remove entries from the keystore daemon. Will only remove it if the
15289     * {@code appId} is valid.
15290     */
15291    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15292        if (appId < 0) {
15293            return;
15294        }
15295
15296        final KeyStore keyStore = KeyStore.getInstance();
15297        if (keyStore != null) {
15298            if (userId == UserHandle.USER_ALL) {
15299                for (final int individual : sUserManager.getUserIds()) {
15300                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15301                }
15302            } else {
15303                keyStore.clearUid(UserHandle.getUid(userId, appId));
15304            }
15305        } else {
15306            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15307        }
15308    }
15309
15310    @Override
15311    public void deleteApplicationCacheFiles(final String packageName,
15312            final IPackageDataObserver observer) {
15313        mContext.enforceCallingOrSelfPermission(
15314                android.Manifest.permission.DELETE_CACHE_FILES, null);
15315        // Queue up an async operation since the package deletion may take a little while.
15316        final int userId = UserHandle.getCallingUserId();
15317        mHandler.post(new Runnable() {
15318            public void run() {
15319                mHandler.removeCallbacks(this);
15320                final boolean succeded;
15321                synchronized (mInstallLock) {
15322                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15323                }
15324                clearExternalStorageDataSync(packageName, userId, false);
15325                if (observer != null) {
15326                    try {
15327                        observer.onRemoveCompleted(packageName, succeded);
15328                    } catch (RemoteException e) {
15329                        Log.i(TAG, "Observer no longer exists.");
15330                    }
15331                } //end if observer
15332            } //end run
15333        });
15334    }
15335
15336    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15337        if (packageName == null) {
15338            Slog.w(TAG, "Attempt to delete null packageName.");
15339            return false;
15340        }
15341        PackageParser.Package p;
15342        synchronized (mPackages) {
15343            p = mPackages.get(packageName);
15344        }
15345        if (p == null) {
15346            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15347            return false;
15348        }
15349        final ApplicationInfo applicationInfo = p.applicationInfo;
15350        if (applicationInfo == null) {
15351            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15352            return false;
15353        }
15354        // TODO: triage flags as part of 26466827
15355        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15356        try {
15357            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15358                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15359        } catch (InstallerException e) {
15360            Slog.w(TAG, "Couldn't remove cache files for package "
15361                    + packageName + " u" + userId, e);
15362            return false;
15363        }
15364        return true;
15365    }
15366
15367    @Override
15368    public void getPackageSizeInfo(final String packageName, int userHandle,
15369            final IPackageStatsObserver observer) {
15370        mContext.enforceCallingOrSelfPermission(
15371                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15372        if (packageName == null) {
15373            throw new IllegalArgumentException("Attempt to get size of null packageName");
15374        }
15375
15376        PackageStats stats = new PackageStats(packageName, userHandle);
15377
15378        /*
15379         * Queue up an async operation since the package measurement may take a
15380         * little while.
15381         */
15382        Message msg = mHandler.obtainMessage(INIT_COPY);
15383        msg.obj = new MeasureParams(stats, observer);
15384        mHandler.sendMessage(msg);
15385    }
15386
15387    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15388            PackageStats pStats) {
15389        if (packageName == null) {
15390            Slog.w(TAG, "Attempt to get size of null packageName.");
15391            return false;
15392        }
15393        PackageParser.Package p;
15394        boolean dataOnly = false;
15395        String libDirRoot = null;
15396        String asecPath = null;
15397        PackageSetting ps = null;
15398        synchronized (mPackages) {
15399            p = mPackages.get(packageName);
15400            ps = mSettings.mPackages.get(packageName);
15401            if(p == null) {
15402                dataOnly = true;
15403                if((ps == null) || (ps.pkg == null)) {
15404                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15405                    return false;
15406                }
15407                p = ps.pkg;
15408            }
15409            if (ps != null) {
15410                libDirRoot = ps.legacyNativeLibraryPathString;
15411            }
15412            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15413                final long token = Binder.clearCallingIdentity();
15414                try {
15415                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15416                    if (secureContainerId != null) {
15417                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15418                    }
15419                } finally {
15420                    Binder.restoreCallingIdentity(token);
15421                }
15422            }
15423        }
15424        String publicSrcDir = null;
15425        if(!dataOnly) {
15426            final ApplicationInfo applicationInfo = p.applicationInfo;
15427            if (applicationInfo == null) {
15428                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15429                return false;
15430            }
15431            if (p.isForwardLocked()) {
15432                publicSrcDir = applicationInfo.getBaseResourcePath();
15433            }
15434        }
15435        // TODO: extend to measure size of split APKs
15436        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15437        // not just the first level.
15438        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15439        // just the primary.
15440        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15441
15442        String apkPath;
15443        File packageDir = new File(p.codePath);
15444
15445        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15446            apkPath = packageDir.getAbsolutePath();
15447            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15448            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15449                libDirRoot = null;
15450            }
15451        } else {
15452            apkPath = p.baseCodePath;
15453        }
15454
15455        // TODO: triage flags as part of 26466827
15456        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15457        try {
15458            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15459                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15460        } catch (InstallerException e) {
15461            return false;
15462        }
15463
15464        // Fix-up for forward-locked applications in ASEC containers.
15465        if (!isExternal(p)) {
15466            pStats.codeSize += pStats.externalCodeSize;
15467            pStats.externalCodeSize = 0L;
15468        }
15469
15470        return true;
15471    }
15472
15473
15474    @Override
15475    public void addPackageToPreferred(String packageName) {
15476        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15477    }
15478
15479    @Override
15480    public void removePackageFromPreferred(String packageName) {
15481        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15482    }
15483
15484    @Override
15485    public List<PackageInfo> getPreferredPackages(int flags) {
15486        return new ArrayList<PackageInfo>();
15487    }
15488
15489    private int getUidTargetSdkVersionLockedLPr(int uid) {
15490        Object obj = mSettings.getUserIdLPr(uid);
15491        if (obj instanceof SharedUserSetting) {
15492            final SharedUserSetting sus = (SharedUserSetting) obj;
15493            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15494            final Iterator<PackageSetting> it = sus.packages.iterator();
15495            while (it.hasNext()) {
15496                final PackageSetting ps = it.next();
15497                if (ps.pkg != null) {
15498                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15499                    if (v < vers) vers = v;
15500                }
15501            }
15502            return vers;
15503        } else if (obj instanceof PackageSetting) {
15504            final PackageSetting ps = (PackageSetting) obj;
15505            if (ps.pkg != null) {
15506                return ps.pkg.applicationInfo.targetSdkVersion;
15507            }
15508        }
15509        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15510    }
15511
15512    @Override
15513    public void addPreferredActivity(IntentFilter filter, int match,
15514            ComponentName[] set, ComponentName activity, int userId) {
15515        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15516                "Adding preferred");
15517    }
15518
15519    private void addPreferredActivityInternal(IntentFilter filter, int match,
15520            ComponentName[] set, ComponentName activity, boolean always, int userId,
15521            String opname) {
15522        // writer
15523        int callingUid = Binder.getCallingUid();
15524        enforceCrossUserPermission(callingUid, userId,
15525                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15526        if (filter.countActions() == 0) {
15527            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15528            return;
15529        }
15530        synchronized (mPackages) {
15531            if (mContext.checkCallingOrSelfPermission(
15532                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15533                    != PackageManager.PERMISSION_GRANTED) {
15534                if (getUidTargetSdkVersionLockedLPr(callingUid)
15535                        < Build.VERSION_CODES.FROYO) {
15536                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15537                            + callingUid);
15538                    return;
15539                }
15540                mContext.enforceCallingOrSelfPermission(
15541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15542            }
15543
15544            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15545            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15546                    + userId + ":");
15547            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15548            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15549            scheduleWritePackageRestrictionsLocked(userId);
15550        }
15551    }
15552
15553    @Override
15554    public void replacePreferredActivity(IntentFilter filter, int match,
15555            ComponentName[] set, ComponentName activity, int userId) {
15556        if (filter.countActions() != 1) {
15557            throw new IllegalArgumentException(
15558                    "replacePreferredActivity expects filter to have only 1 action.");
15559        }
15560        if (filter.countDataAuthorities() != 0
15561                || filter.countDataPaths() != 0
15562                || filter.countDataSchemes() > 1
15563                || filter.countDataTypes() != 0) {
15564            throw new IllegalArgumentException(
15565                    "replacePreferredActivity expects filter to have no data authorities, " +
15566                    "paths, or types; and at most one scheme.");
15567        }
15568
15569        final int callingUid = Binder.getCallingUid();
15570        enforceCrossUserPermission(callingUid, userId,
15571                true /* requireFullPermission */, false /* checkShell */,
15572                "replace preferred activity");
15573        synchronized (mPackages) {
15574            if (mContext.checkCallingOrSelfPermission(
15575                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15576                    != PackageManager.PERMISSION_GRANTED) {
15577                if (getUidTargetSdkVersionLockedLPr(callingUid)
15578                        < Build.VERSION_CODES.FROYO) {
15579                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15580                            + Binder.getCallingUid());
15581                    return;
15582                }
15583                mContext.enforceCallingOrSelfPermission(
15584                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15585            }
15586
15587            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15588            if (pir != null) {
15589                // Get all of the existing entries that exactly match this filter.
15590                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15591                if (existing != null && existing.size() == 1) {
15592                    PreferredActivity cur = existing.get(0);
15593                    if (DEBUG_PREFERRED) {
15594                        Slog.i(TAG, "Checking replace of preferred:");
15595                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15596                        if (!cur.mPref.mAlways) {
15597                            Slog.i(TAG, "  -- CUR; not mAlways!");
15598                        } else {
15599                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15600                            Slog.i(TAG, "  -- CUR: mSet="
15601                                    + Arrays.toString(cur.mPref.mSetComponents));
15602                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15603                            Slog.i(TAG, "  -- NEW: mMatch="
15604                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15605                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15606                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15607                        }
15608                    }
15609                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15610                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15611                            && cur.mPref.sameSet(set)) {
15612                        // Setting the preferred activity to what it happens to be already
15613                        if (DEBUG_PREFERRED) {
15614                            Slog.i(TAG, "Replacing with same preferred activity "
15615                                    + cur.mPref.mShortComponent + " for user "
15616                                    + userId + ":");
15617                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15618                        }
15619                        return;
15620                    }
15621                }
15622
15623                if (existing != null) {
15624                    if (DEBUG_PREFERRED) {
15625                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15626                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15627                    }
15628                    for (int i = 0; i < existing.size(); i++) {
15629                        PreferredActivity pa = existing.get(i);
15630                        if (DEBUG_PREFERRED) {
15631                            Slog.i(TAG, "Removing existing preferred activity "
15632                                    + pa.mPref.mComponent + ":");
15633                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15634                        }
15635                        pir.removeFilter(pa);
15636                    }
15637                }
15638            }
15639            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15640                    "Replacing preferred");
15641        }
15642    }
15643
15644    @Override
15645    public void clearPackagePreferredActivities(String packageName) {
15646        final int uid = Binder.getCallingUid();
15647        // writer
15648        synchronized (mPackages) {
15649            PackageParser.Package pkg = mPackages.get(packageName);
15650            if (pkg == null || pkg.applicationInfo.uid != uid) {
15651                if (mContext.checkCallingOrSelfPermission(
15652                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15653                        != PackageManager.PERMISSION_GRANTED) {
15654                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15655                            < Build.VERSION_CODES.FROYO) {
15656                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15657                                + Binder.getCallingUid());
15658                        return;
15659                    }
15660                    mContext.enforceCallingOrSelfPermission(
15661                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15662                }
15663            }
15664
15665            int user = UserHandle.getCallingUserId();
15666            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15667                scheduleWritePackageRestrictionsLocked(user);
15668            }
15669        }
15670    }
15671
15672    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15673    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15674        ArrayList<PreferredActivity> removed = null;
15675        boolean changed = false;
15676        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15677            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15678            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15679            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15680                continue;
15681            }
15682            Iterator<PreferredActivity> it = pir.filterIterator();
15683            while (it.hasNext()) {
15684                PreferredActivity pa = it.next();
15685                // Mark entry for removal only if it matches the package name
15686                // and the entry is of type "always".
15687                if (packageName == null ||
15688                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15689                                && pa.mPref.mAlways)) {
15690                    if (removed == null) {
15691                        removed = new ArrayList<PreferredActivity>();
15692                    }
15693                    removed.add(pa);
15694                }
15695            }
15696            if (removed != null) {
15697                for (int j=0; j<removed.size(); j++) {
15698                    PreferredActivity pa = removed.get(j);
15699                    pir.removeFilter(pa);
15700                }
15701                changed = true;
15702            }
15703        }
15704        return changed;
15705    }
15706
15707    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15708    private void clearIntentFilterVerificationsLPw(int userId) {
15709        final int packageCount = mPackages.size();
15710        for (int i = 0; i < packageCount; i++) {
15711            PackageParser.Package pkg = mPackages.valueAt(i);
15712            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15713        }
15714    }
15715
15716    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15717    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15718        if (userId == UserHandle.USER_ALL) {
15719            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15720                    sUserManager.getUserIds())) {
15721                for (int oneUserId : sUserManager.getUserIds()) {
15722                    scheduleWritePackageRestrictionsLocked(oneUserId);
15723                }
15724            }
15725        } else {
15726            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15727                scheduleWritePackageRestrictionsLocked(userId);
15728            }
15729        }
15730    }
15731
15732    void clearDefaultBrowserIfNeeded(String packageName) {
15733        for (int oneUserId : sUserManager.getUserIds()) {
15734            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15735            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15736            if (packageName.equals(defaultBrowserPackageName)) {
15737                setDefaultBrowserPackageName(null, oneUserId);
15738            }
15739        }
15740    }
15741
15742    @Override
15743    public void resetApplicationPreferences(int userId) {
15744        mContext.enforceCallingOrSelfPermission(
15745                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15746        // writer
15747        synchronized (mPackages) {
15748            final long identity = Binder.clearCallingIdentity();
15749            try {
15750                clearPackagePreferredActivitiesLPw(null, userId);
15751                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15752                // TODO: We have to reset the default SMS and Phone. This requires
15753                // significant refactoring to keep all default apps in the package
15754                // manager (cleaner but more work) or have the services provide
15755                // callbacks to the package manager to request a default app reset.
15756                applyFactoryDefaultBrowserLPw(userId);
15757                clearIntentFilterVerificationsLPw(userId);
15758                primeDomainVerificationsLPw(userId);
15759                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15760                scheduleWritePackageRestrictionsLocked(userId);
15761            } finally {
15762                Binder.restoreCallingIdentity(identity);
15763            }
15764        }
15765    }
15766
15767    @Override
15768    public int getPreferredActivities(List<IntentFilter> outFilters,
15769            List<ComponentName> outActivities, String packageName) {
15770
15771        int num = 0;
15772        final int userId = UserHandle.getCallingUserId();
15773        // reader
15774        synchronized (mPackages) {
15775            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15776            if (pir != null) {
15777                final Iterator<PreferredActivity> it = pir.filterIterator();
15778                while (it.hasNext()) {
15779                    final PreferredActivity pa = it.next();
15780                    if (packageName == null
15781                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15782                                    && pa.mPref.mAlways)) {
15783                        if (outFilters != null) {
15784                            outFilters.add(new IntentFilter(pa));
15785                        }
15786                        if (outActivities != null) {
15787                            outActivities.add(pa.mPref.mComponent);
15788                        }
15789                    }
15790                }
15791            }
15792        }
15793
15794        return num;
15795    }
15796
15797    @Override
15798    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15799            int userId) {
15800        int callingUid = Binder.getCallingUid();
15801        if (callingUid != Process.SYSTEM_UID) {
15802            throw new SecurityException(
15803                    "addPersistentPreferredActivity can only be run by the system");
15804        }
15805        if (filter.countActions() == 0) {
15806            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15807            return;
15808        }
15809        synchronized (mPackages) {
15810            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15811                    ":");
15812            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15813            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15814                    new PersistentPreferredActivity(filter, activity));
15815            scheduleWritePackageRestrictionsLocked(userId);
15816        }
15817    }
15818
15819    @Override
15820    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15821        int callingUid = Binder.getCallingUid();
15822        if (callingUid != Process.SYSTEM_UID) {
15823            throw new SecurityException(
15824                    "clearPackagePersistentPreferredActivities can only be run by the system");
15825        }
15826        ArrayList<PersistentPreferredActivity> removed = null;
15827        boolean changed = false;
15828        synchronized (mPackages) {
15829            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15830                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15831                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15832                        .valueAt(i);
15833                if (userId != thisUserId) {
15834                    continue;
15835                }
15836                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15837                while (it.hasNext()) {
15838                    PersistentPreferredActivity ppa = it.next();
15839                    // Mark entry for removal only if it matches the package name.
15840                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15841                        if (removed == null) {
15842                            removed = new ArrayList<PersistentPreferredActivity>();
15843                        }
15844                        removed.add(ppa);
15845                    }
15846                }
15847                if (removed != null) {
15848                    for (int j=0; j<removed.size(); j++) {
15849                        PersistentPreferredActivity ppa = removed.get(j);
15850                        ppir.removeFilter(ppa);
15851                    }
15852                    changed = true;
15853                }
15854            }
15855
15856            if (changed) {
15857                scheduleWritePackageRestrictionsLocked(userId);
15858            }
15859        }
15860    }
15861
15862    /**
15863     * Common machinery for picking apart a restored XML blob and passing
15864     * it to a caller-supplied functor to be applied to the running system.
15865     */
15866    private void restoreFromXml(XmlPullParser parser, int userId,
15867            String expectedStartTag, BlobXmlRestorer functor)
15868            throws IOException, XmlPullParserException {
15869        int type;
15870        while ((type = parser.next()) != XmlPullParser.START_TAG
15871                && type != XmlPullParser.END_DOCUMENT) {
15872        }
15873        if (type != XmlPullParser.START_TAG) {
15874            // oops didn't find a start tag?!
15875            if (DEBUG_BACKUP) {
15876                Slog.e(TAG, "Didn't find start tag during restore");
15877            }
15878            return;
15879        }
15880Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15881        // this is supposed to be TAG_PREFERRED_BACKUP
15882        if (!expectedStartTag.equals(parser.getName())) {
15883            if (DEBUG_BACKUP) {
15884                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15885            }
15886            return;
15887        }
15888
15889        // skip interfering stuff, then we're aligned with the backing implementation
15890        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15891Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15892        functor.apply(parser, userId);
15893    }
15894
15895    private interface BlobXmlRestorer {
15896        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15897    }
15898
15899    /**
15900     * Non-Binder method, support for the backup/restore mechanism: write the
15901     * full set of preferred activities in its canonical XML format.  Returns the
15902     * XML output as a byte array, or null if there is none.
15903     */
15904    @Override
15905    public byte[] getPreferredActivityBackup(int userId) {
15906        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15907            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15908        }
15909
15910        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15911        try {
15912            final XmlSerializer serializer = new FastXmlSerializer();
15913            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15914            serializer.startDocument(null, true);
15915            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15916
15917            synchronized (mPackages) {
15918                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15919            }
15920
15921            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15922            serializer.endDocument();
15923            serializer.flush();
15924        } catch (Exception e) {
15925            if (DEBUG_BACKUP) {
15926                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15927            }
15928            return null;
15929        }
15930
15931        return dataStream.toByteArray();
15932    }
15933
15934    @Override
15935    public void restorePreferredActivities(byte[] backup, int userId) {
15936        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15937            throw new SecurityException("Only the system may call restorePreferredActivities()");
15938        }
15939
15940        try {
15941            final XmlPullParser parser = Xml.newPullParser();
15942            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15943            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15944                    new BlobXmlRestorer() {
15945                        @Override
15946                        public void apply(XmlPullParser parser, int userId)
15947                                throws XmlPullParserException, IOException {
15948                            synchronized (mPackages) {
15949                                mSettings.readPreferredActivitiesLPw(parser, userId);
15950                            }
15951                        }
15952                    } );
15953        } catch (Exception e) {
15954            if (DEBUG_BACKUP) {
15955                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15956            }
15957        }
15958    }
15959
15960    /**
15961     * Non-Binder method, support for the backup/restore mechanism: write the
15962     * default browser (etc) settings in its canonical XML format.  Returns the default
15963     * browser XML representation as a byte array, or null if there is none.
15964     */
15965    @Override
15966    public byte[] getDefaultAppsBackup(int userId) {
15967        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15968            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15969        }
15970
15971        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15972        try {
15973            final XmlSerializer serializer = new FastXmlSerializer();
15974            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15975            serializer.startDocument(null, true);
15976            serializer.startTag(null, TAG_DEFAULT_APPS);
15977
15978            synchronized (mPackages) {
15979                mSettings.writeDefaultAppsLPr(serializer, userId);
15980            }
15981
15982            serializer.endTag(null, TAG_DEFAULT_APPS);
15983            serializer.endDocument();
15984            serializer.flush();
15985        } catch (Exception e) {
15986            if (DEBUG_BACKUP) {
15987                Slog.e(TAG, "Unable to write default apps for backup", e);
15988            }
15989            return null;
15990        }
15991
15992        return dataStream.toByteArray();
15993    }
15994
15995    @Override
15996    public void restoreDefaultApps(byte[] backup, int userId) {
15997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15998            throw new SecurityException("Only the system may call restoreDefaultApps()");
15999        }
16000
16001        try {
16002            final XmlPullParser parser = Xml.newPullParser();
16003            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16004            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16005                    new BlobXmlRestorer() {
16006                        @Override
16007                        public void apply(XmlPullParser parser, int userId)
16008                                throws XmlPullParserException, IOException {
16009                            synchronized (mPackages) {
16010                                mSettings.readDefaultAppsLPw(parser, userId);
16011                            }
16012                        }
16013                    } );
16014        } catch (Exception e) {
16015            if (DEBUG_BACKUP) {
16016                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16017            }
16018        }
16019    }
16020
16021    @Override
16022    public byte[] getIntentFilterVerificationBackup(int userId) {
16023        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16024            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16025        }
16026
16027        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16028        try {
16029            final XmlSerializer serializer = new FastXmlSerializer();
16030            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16031            serializer.startDocument(null, true);
16032            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16033
16034            synchronized (mPackages) {
16035                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16036            }
16037
16038            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16039            serializer.endDocument();
16040            serializer.flush();
16041        } catch (Exception e) {
16042            if (DEBUG_BACKUP) {
16043                Slog.e(TAG, "Unable to write default apps for backup", e);
16044            }
16045            return null;
16046        }
16047
16048        return dataStream.toByteArray();
16049    }
16050
16051    @Override
16052    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16053        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16054            throw new SecurityException("Only the system may call restorePreferredActivities()");
16055        }
16056
16057        try {
16058            final XmlPullParser parser = Xml.newPullParser();
16059            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16060            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16061                    new BlobXmlRestorer() {
16062                        @Override
16063                        public void apply(XmlPullParser parser, int userId)
16064                                throws XmlPullParserException, IOException {
16065                            synchronized (mPackages) {
16066                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16067                                mSettings.writeLPr();
16068                            }
16069                        }
16070                    } );
16071        } catch (Exception e) {
16072            if (DEBUG_BACKUP) {
16073                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16074            }
16075        }
16076    }
16077
16078    @Override
16079    public byte[] getPermissionGrantBackup(int userId) {
16080        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16081            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16082        }
16083
16084        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16085        try {
16086            final XmlSerializer serializer = new FastXmlSerializer();
16087            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16088            serializer.startDocument(null, true);
16089            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16090
16091            synchronized (mPackages) {
16092                serializeRuntimePermissionGrantsLPr(serializer, userId);
16093            }
16094
16095            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16096            serializer.endDocument();
16097            serializer.flush();
16098        } catch (Exception e) {
16099            if (DEBUG_BACKUP) {
16100                Slog.e(TAG, "Unable to write default apps for backup", e);
16101            }
16102            return null;
16103        }
16104
16105        return dataStream.toByteArray();
16106    }
16107
16108    @Override
16109    public void restorePermissionGrants(byte[] backup, int userId) {
16110        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16111            throw new SecurityException("Only the system may call restorePermissionGrants()");
16112        }
16113
16114        try {
16115            final XmlPullParser parser = Xml.newPullParser();
16116            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16117            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16118                    new BlobXmlRestorer() {
16119                        @Override
16120                        public void apply(XmlPullParser parser, int userId)
16121                                throws XmlPullParserException, IOException {
16122                            synchronized (mPackages) {
16123                                processRestoredPermissionGrantsLPr(parser, userId);
16124                            }
16125                        }
16126                    } );
16127        } catch (Exception e) {
16128            if (DEBUG_BACKUP) {
16129                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16130            }
16131        }
16132    }
16133
16134    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16135            throws IOException {
16136        serializer.startTag(null, TAG_ALL_GRANTS);
16137
16138        final int N = mSettings.mPackages.size();
16139        for (int i = 0; i < N; i++) {
16140            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16141            boolean pkgGrantsKnown = false;
16142
16143            PermissionsState packagePerms = ps.getPermissionsState();
16144
16145            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16146                final int grantFlags = state.getFlags();
16147                // only look at grants that are not system/policy fixed
16148                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16149                    final boolean isGranted = state.isGranted();
16150                    // And only back up the user-twiddled state bits
16151                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16152                        final String packageName = mSettings.mPackages.keyAt(i);
16153                        if (!pkgGrantsKnown) {
16154                            serializer.startTag(null, TAG_GRANT);
16155                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16156                            pkgGrantsKnown = true;
16157                        }
16158
16159                        final boolean userSet =
16160                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16161                        final boolean userFixed =
16162                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16163                        final boolean revoke =
16164                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16165
16166                        serializer.startTag(null, TAG_PERMISSION);
16167                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16168                        if (isGranted) {
16169                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16170                        }
16171                        if (userSet) {
16172                            serializer.attribute(null, ATTR_USER_SET, "true");
16173                        }
16174                        if (userFixed) {
16175                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16176                        }
16177                        if (revoke) {
16178                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16179                        }
16180                        serializer.endTag(null, TAG_PERMISSION);
16181                    }
16182                }
16183            }
16184
16185            if (pkgGrantsKnown) {
16186                serializer.endTag(null, TAG_GRANT);
16187            }
16188        }
16189
16190        serializer.endTag(null, TAG_ALL_GRANTS);
16191    }
16192
16193    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16194            throws XmlPullParserException, IOException {
16195        String pkgName = null;
16196        int outerDepth = parser.getDepth();
16197        int type;
16198        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16199                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16200            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16201                continue;
16202            }
16203
16204            final String tagName = parser.getName();
16205            if (tagName.equals(TAG_GRANT)) {
16206                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16207                if (DEBUG_BACKUP) {
16208                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16209                }
16210            } else if (tagName.equals(TAG_PERMISSION)) {
16211
16212                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16213                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16214
16215                int newFlagSet = 0;
16216                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16217                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16218                }
16219                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16220                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16221                }
16222                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16223                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16224                }
16225                if (DEBUG_BACKUP) {
16226                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16227                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16228                }
16229                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16230                if (ps != null) {
16231                    // Already installed so we apply the grant immediately
16232                    if (DEBUG_BACKUP) {
16233                        Slog.v(TAG, "        + already installed; applying");
16234                    }
16235                    PermissionsState perms = ps.getPermissionsState();
16236                    BasePermission bp = mSettings.mPermissions.get(permName);
16237                    if (bp != null) {
16238                        if (isGranted) {
16239                            perms.grantRuntimePermission(bp, userId);
16240                        }
16241                        if (newFlagSet != 0) {
16242                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16243                        }
16244                    }
16245                } else {
16246                    // Need to wait for post-restore install to apply the grant
16247                    if (DEBUG_BACKUP) {
16248                        Slog.v(TAG, "        - not yet installed; saving for later");
16249                    }
16250                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16251                            isGranted, newFlagSet, userId);
16252                }
16253            } else {
16254                PackageManagerService.reportSettingsProblem(Log.WARN,
16255                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16256                XmlUtils.skipCurrentTag(parser);
16257            }
16258        }
16259
16260        scheduleWriteSettingsLocked();
16261        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16262    }
16263
16264    @Override
16265    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16266            int sourceUserId, int targetUserId, int flags) {
16267        mContext.enforceCallingOrSelfPermission(
16268                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16269        int callingUid = Binder.getCallingUid();
16270        enforceOwnerRights(ownerPackage, callingUid);
16271        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16272        if (intentFilter.countActions() == 0) {
16273            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16274            return;
16275        }
16276        synchronized (mPackages) {
16277            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16278                    ownerPackage, targetUserId, flags);
16279            CrossProfileIntentResolver resolver =
16280                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16281            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16282            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16283            if (existing != null) {
16284                int size = existing.size();
16285                for (int i = 0; i < size; i++) {
16286                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16287                        return;
16288                    }
16289                }
16290            }
16291            resolver.addFilter(newFilter);
16292            scheduleWritePackageRestrictionsLocked(sourceUserId);
16293        }
16294    }
16295
16296    @Override
16297    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16298        mContext.enforceCallingOrSelfPermission(
16299                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16300        int callingUid = Binder.getCallingUid();
16301        enforceOwnerRights(ownerPackage, callingUid);
16302        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16303        synchronized (mPackages) {
16304            CrossProfileIntentResolver resolver =
16305                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16306            ArraySet<CrossProfileIntentFilter> set =
16307                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16308            for (CrossProfileIntentFilter filter : set) {
16309                if (filter.getOwnerPackage().equals(ownerPackage)) {
16310                    resolver.removeFilter(filter);
16311                }
16312            }
16313            scheduleWritePackageRestrictionsLocked(sourceUserId);
16314        }
16315    }
16316
16317    // Enforcing that callingUid is owning pkg on userId
16318    private void enforceOwnerRights(String pkg, int callingUid) {
16319        // The system owns everything.
16320        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16321            return;
16322        }
16323        int callingUserId = UserHandle.getUserId(callingUid);
16324        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16325        if (pi == null) {
16326            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16327                    + callingUserId);
16328        }
16329        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16330            throw new SecurityException("Calling uid " + callingUid
16331                    + " does not own package " + pkg);
16332        }
16333    }
16334
16335    @Override
16336    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16337        Intent intent = new Intent(Intent.ACTION_MAIN);
16338        intent.addCategory(Intent.CATEGORY_HOME);
16339
16340        final int callingUserId = UserHandle.getCallingUserId();
16341        List<ResolveInfo> list = queryIntentActivities(intent, null,
16342                PackageManager.GET_META_DATA, callingUserId);
16343        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16344                true, false, false, callingUserId);
16345
16346        allHomeCandidates.clear();
16347        if (list != null) {
16348            for (ResolveInfo ri : list) {
16349                allHomeCandidates.add(ri);
16350            }
16351        }
16352        return (preferred == null || preferred.activityInfo == null)
16353                ? null
16354                : new ComponentName(preferred.activityInfo.packageName,
16355                        preferred.activityInfo.name);
16356    }
16357
16358    @Override
16359    public void setApplicationEnabledSetting(String appPackageName,
16360            int newState, int flags, int userId, String callingPackage) {
16361        if (!sUserManager.exists(userId)) return;
16362        if (callingPackage == null) {
16363            callingPackage = Integer.toString(Binder.getCallingUid());
16364        }
16365        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16366    }
16367
16368    @Override
16369    public void setComponentEnabledSetting(ComponentName componentName,
16370            int newState, int flags, int userId) {
16371        if (!sUserManager.exists(userId)) return;
16372        setEnabledSetting(componentName.getPackageName(),
16373                componentName.getClassName(), newState, flags, userId, null);
16374    }
16375
16376    private void setEnabledSetting(final String packageName, String className, int newState,
16377            final int flags, int userId, String callingPackage) {
16378        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16379              || newState == COMPONENT_ENABLED_STATE_ENABLED
16380              || newState == COMPONENT_ENABLED_STATE_DISABLED
16381              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16382              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16383            throw new IllegalArgumentException("Invalid new component state: "
16384                    + newState);
16385        }
16386        PackageSetting pkgSetting;
16387        final int uid = Binder.getCallingUid();
16388        final int permission = mContext.checkCallingOrSelfPermission(
16389                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16390        enforceCrossUserPermission(uid, userId,
16391                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16392        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16393        boolean sendNow = false;
16394        boolean isApp = (className == null);
16395        String componentName = isApp ? packageName : className;
16396        int packageUid = -1;
16397        ArrayList<String> components;
16398
16399        // writer
16400        synchronized (mPackages) {
16401            pkgSetting = mSettings.mPackages.get(packageName);
16402            if (pkgSetting == null) {
16403                if (className == null) {
16404                    throw new IllegalArgumentException("Unknown package: " + packageName);
16405                }
16406                throw new IllegalArgumentException(
16407                        "Unknown component: " + packageName + "/" + className);
16408            }
16409            // Allow root and verify that userId is not being specified by a different user
16410            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16411                throw new SecurityException(
16412                        "Permission Denial: attempt to change component state from pid="
16413                        + Binder.getCallingPid()
16414                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16415            }
16416            if (className == null) {
16417                // We're dealing with an application/package level state change
16418                if (pkgSetting.getEnabled(userId) == newState) {
16419                    // Nothing to do
16420                    return;
16421                }
16422                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16423                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16424                    // Don't care about who enables an app.
16425                    callingPackage = null;
16426                }
16427                pkgSetting.setEnabled(newState, userId, callingPackage);
16428                // pkgSetting.pkg.mSetEnabled = newState;
16429            } else {
16430                // We're dealing with a component level state change
16431                // First, verify that this is a valid class name.
16432                PackageParser.Package pkg = pkgSetting.pkg;
16433                if (pkg == null || !pkg.hasComponentClassName(className)) {
16434                    if (pkg != null &&
16435                            pkg.applicationInfo.targetSdkVersion >=
16436                                    Build.VERSION_CODES.JELLY_BEAN) {
16437                        throw new IllegalArgumentException("Component class " + className
16438                                + " does not exist in " + packageName);
16439                    } else {
16440                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16441                                + className + " does not exist in " + packageName);
16442                    }
16443                }
16444                switch (newState) {
16445                case COMPONENT_ENABLED_STATE_ENABLED:
16446                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16447                        return;
16448                    }
16449                    break;
16450                case COMPONENT_ENABLED_STATE_DISABLED:
16451                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16452                        return;
16453                    }
16454                    break;
16455                case COMPONENT_ENABLED_STATE_DEFAULT:
16456                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16457                        return;
16458                    }
16459                    break;
16460                default:
16461                    Slog.e(TAG, "Invalid new component state: " + newState);
16462                    return;
16463                }
16464            }
16465            scheduleWritePackageRestrictionsLocked(userId);
16466            components = mPendingBroadcasts.get(userId, packageName);
16467            final boolean newPackage = components == null;
16468            if (newPackage) {
16469                components = new ArrayList<String>();
16470            }
16471            if (!components.contains(componentName)) {
16472                components.add(componentName);
16473            }
16474            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16475                sendNow = true;
16476                // Purge entry from pending broadcast list if another one exists already
16477                // since we are sending one right away.
16478                mPendingBroadcasts.remove(userId, packageName);
16479            } else {
16480                if (newPackage) {
16481                    mPendingBroadcasts.put(userId, packageName, components);
16482                }
16483                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16484                    // Schedule a message
16485                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16486                }
16487            }
16488        }
16489
16490        long callingId = Binder.clearCallingIdentity();
16491        try {
16492            if (sendNow) {
16493                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16494                sendPackageChangedBroadcast(packageName,
16495                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16496            }
16497        } finally {
16498            Binder.restoreCallingIdentity(callingId);
16499        }
16500    }
16501
16502    private void sendPackageChangedBroadcast(String packageName,
16503            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16504        if (DEBUG_INSTALL)
16505            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16506                    + componentNames);
16507        Bundle extras = new Bundle(4);
16508        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16509        String nameList[] = new String[componentNames.size()];
16510        componentNames.toArray(nameList);
16511        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16512        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16513        extras.putInt(Intent.EXTRA_UID, packageUid);
16514        // If this is not reporting a change of the overall package, then only send it
16515        // to registered receivers.  We don't want to launch a swath of apps for every
16516        // little component state change.
16517        final int flags = !componentNames.contains(packageName)
16518                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16519        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16520                new int[] {UserHandle.getUserId(packageUid)});
16521    }
16522
16523    @Override
16524    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16525        if (!sUserManager.exists(userId)) return;
16526        final int uid = Binder.getCallingUid();
16527        final int permission = mContext.checkCallingOrSelfPermission(
16528                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16529        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16530        enforceCrossUserPermission(uid, userId,
16531                true /* requireFullPermission */, true /* checkShell */, "stop package");
16532        // writer
16533        synchronized (mPackages) {
16534            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16535                    allowedByPermission, uid, userId)) {
16536                scheduleWritePackageRestrictionsLocked(userId);
16537            }
16538        }
16539    }
16540
16541    @Override
16542    public String getInstallerPackageName(String packageName) {
16543        // reader
16544        synchronized (mPackages) {
16545            return mSettings.getInstallerPackageNameLPr(packageName);
16546        }
16547    }
16548
16549    @Override
16550    public int getApplicationEnabledSetting(String packageName, int userId) {
16551        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16552        int uid = Binder.getCallingUid();
16553        enforceCrossUserPermission(uid, userId,
16554                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16555        // reader
16556        synchronized (mPackages) {
16557            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16558        }
16559    }
16560
16561    @Override
16562    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16563        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16564        int uid = Binder.getCallingUid();
16565        enforceCrossUserPermission(uid, userId,
16566                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16567        // reader
16568        synchronized (mPackages) {
16569            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16570        }
16571    }
16572
16573    @Override
16574    public void enterSafeMode() {
16575        enforceSystemOrRoot("Only the system can request entering safe mode");
16576
16577        if (!mSystemReady) {
16578            mSafeMode = true;
16579        }
16580    }
16581
16582    @Override
16583    public void systemReady() {
16584        mSystemReady = true;
16585
16586        // Read the compatibilty setting when the system is ready.
16587        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16588                mContext.getContentResolver(),
16589                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16590        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16591        if (DEBUG_SETTINGS) {
16592            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16593        }
16594
16595        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16596
16597        synchronized (mPackages) {
16598            // Verify that all of the preferred activity components actually
16599            // exist.  It is possible for applications to be updated and at
16600            // that point remove a previously declared activity component that
16601            // had been set as a preferred activity.  We try to clean this up
16602            // the next time we encounter that preferred activity, but it is
16603            // possible for the user flow to never be able to return to that
16604            // situation so here we do a sanity check to make sure we haven't
16605            // left any junk around.
16606            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16607            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16608                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16609                removed.clear();
16610                for (PreferredActivity pa : pir.filterSet()) {
16611                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16612                        removed.add(pa);
16613                    }
16614                }
16615                if (removed.size() > 0) {
16616                    for (int r=0; r<removed.size(); r++) {
16617                        PreferredActivity pa = removed.get(r);
16618                        Slog.w(TAG, "Removing dangling preferred activity: "
16619                                + pa.mPref.mComponent);
16620                        pir.removeFilter(pa);
16621                    }
16622                    mSettings.writePackageRestrictionsLPr(
16623                            mSettings.mPreferredActivities.keyAt(i));
16624                }
16625            }
16626
16627            for (int userId : UserManagerService.getInstance().getUserIds()) {
16628                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16629                    grantPermissionsUserIds = ArrayUtils.appendInt(
16630                            grantPermissionsUserIds, userId);
16631                }
16632            }
16633        }
16634        sUserManager.systemReady();
16635
16636        // If we upgraded grant all default permissions before kicking off.
16637        for (int userId : grantPermissionsUserIds) {
16638            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16639        }
16640
16641        // Kick off any messages waiting for system ready
16642        if (mPostSystemReadyMessages != null) {
16643            for (Message msg : mPostSystemReadyMessages) {
16644                msg.sendToTarget();
16645            }
16646            mPostSystemReadyMessages = null;
16647        }
16648
16649        // Watch for external volumes that come and go over time
16650        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16651        storage.registerListener(mStorageListener);
16652
16653        mInstallerService.systemReady();
16654        mPackageDexOptimizer.systemReady();
16655
16656        MountServiceInternal mountServiceInternal = LocalServices.getService(
16657                MountServiceInternal.class);
16658        mountServiceInternal.addExternalStoragePolicy(
16659                new MountServiceInternal.ExternalStorageMountPolicy() {
16660            @Override
16661            public int getMountMode(int uid, String packageName) {
16662                if (Process.isIsolated(uid)) {
16663                    return Zygote.MOUNT_EXTERNAL_NONE;
16664                }
16665                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16666                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16667                }
16668                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16669                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16670                }
16671                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16672                    return Zygote.MOUNT_EXTERNAL_READ;
16673                }
16674                return Zygote.MOUNT_EXTERNAL_WRITE;
16675            }
16676
16677            @Override
16678            public boolean hasExternalStorage(int uid, String packageName) {
16679                return true;
16680            }
16681        });
16682    }
16683
16684    @Override
16685    public boolean isSafeMode() {
16686        return mSafeMode;
16687    }
16688
16689    @Override
16690    public boolean hasSystemUidErrors() {
16691        return mHasSystemUidErrors;
16692    }
16693
16694    static String arrayToString(int[] array) {
16695        StringBuffer buf = new StringBuffer(128);
16696        buf.append('[');
16697        if (array != null) {
16698            for (int i=0; i<array.length; i++) {
16699                if (i > 0) buf.append(", ");
16700                buf.append(array[i]);
16701            }
16702        }
16703        buf.append(']');
16704        return buf.toString();
16705    }
16706
16707    static class DumpState {
16708        public static final int DUMP_LIBS = 1 << 0;
16709        public static final int DUMP_FEATURES = 1 << 1;
16710        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16711        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16712        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16713        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16714        public static final int DUMP_PERMISSIONS = 1 << 6;
16715        public static final int DUMP_PACKAGES = 1 << 7;
16716        public static final int DUMP_SHARED_USERS = 1 << 8;
16717        public static final int DUMP_MESSAGES = 1 << 9;
16718        public static final int DUMP_PROVIDERS = 1 << 10;
16719        public static final int DUMP_VERIFIERS = 1 << 11;
16720        public static final int DUMP_PREFERRED = 1 << 12;
16721        public static final int DUMP_PREFERRED_XML = 1 << 13;
16722        public static final int DUMP_KEYSETS = 1 << 14;
16723        public static final int DUMP_VERSION = 1 << 15;
16724        public static final int DUMP_INSTALLS = 1 << 16;
16725        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16726        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16727
16728        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16729
16730        private int mTypes;
16731
16732        private int mOptions;
16733
16734        private boolean mTitlePrinted;
16735
16736        private SharedUserSetting mSharedUser;
16737
16738        public boolean isDumping(int type) {
16739            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16740                return true;
16741            }
16742
16743            return (mTypes & type) != 0;
16744        }
16745
16746        public void setDump(int type) {
16747            mTypes |= type;
16748        }
16749
16750        public boolean isOptionEnabled(int option) {
16751            return (mOptions & option) != 0;
16752        }
16753
16754        public void setOptionEnabled(int option) {
16755            mOptions |= option;
16756        }
16757
16758        public boolean onTitlePrinted() {
16759            final boolean printed = mTitlePrinted;
16760            mTitlePrinted = true;
16761            return printed;
16762        }
16763
16764        public boolean getTitlePrinted() {
16765            return mTitlePrinted;
16766        }
16767
16768        public void setTitlePrinted(boolean enabled) {
16769            mTitlePrinted = enabled;
16770        }
16771
16772        public SharedUserSetting getSharedUser() {
16773            return mSharedUser;
16774        }
16775
16776        public void setSharedUser(SharedUserSetting user) {
16777            mSharedUser = user;
16778        }
16779    }
16780
16781    @Override
16782    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16783            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16784        (new PackageManagerShellCommand(this)).exec(
16785                this, in, out, err, args, resultReceiver);
16786    }
16787
16788    @Override
16789    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16790        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16791                != PackageManager.PERMISSION_GRANTED) {
16792            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16793                    + Binder.getCallingPid()
16794                    + ", uid=" + Binder.getCallingUid()
16795                    + " without permission "
16796                    + android.Manifest.permission.DUMP);
16797            return;
16798        }
16799
16800        DumpState dumpState = new DumpState();
16801        boolean fullPreferred = false;
16802        boolean checkin = false;
16803
16804        String packageName = null;
16805        ArraySet<String> permissionNames = null;
16806
16807        int opti = 0;
16808        while (opti < args.length) {
16809            String opt = args[opti];
16810            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16811                break;
16812            }
16813            opti++;
16814
16815            if ("-a".equals(opt)) {
16816                // Right now we only know how to print all.
16817            } else if ("-h".equals(opt)) {
16818                pw.println("Package manager dump options:");
16819                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16820                pw.println("    --checkin: dump for a checkin");
16821                pw.println("    -f: print details of intent filters");
16822                pw.println("    -h: print this help");
16823                pw.println("  cmd may be one of:");
16824                pw.println("    l[ibraries]: list known shared libraries");
16825                pw.println("    f[eatures]: list device features");
16826                pw.println("    k[eysets]: print known keysets");
16827                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16828                pw.println("    perm[issions]: dump permissions");
16829                pw.println("    permission [name ...]: dump declaration and use of given permission");
16830                pw.println("    pref[erred]: print preferred package settings");
16831                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16832                pw.println("    prov[iders]: dump content providers");
16833                pw.println("    p[ackages]: dump installed packages");
16834                pw.println("    s[hared-users]: dump shared user IDs");
16835                pw.println("    m[essages]: print collected runtime messages");
16836                pw.println("    v[erifiers]: print package verifier info");
16837                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16838                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16839                pw.println("    version: print database version info");
16840                pw.println("    write: write current settings now");
16841                pw.println("    installs: details about install sessions");
16842                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16843                pw.println("    <package.name>: info about given package");
16844                return;
16845            } else if ("--checkin".equals(opt)) {
16846                checkin = true;
16847            } else if ("-f".equals(opt)) {
16848                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16849            } else {
16850                pw.println("Unknown argument: " + opt + "; use -h for help");
16851            }
16852        }
16853
16854        // Is the caller requesting to dump a particular piece of data?
16855        if (opti < args.length) {
16856            String cmd = args[opti];
16857            opti++;
16858            // Is this a package name?
16859            if ("android".equals(cmd) || cmd.contains(".")) {
16860                packageName = cmd;
16861                // When dumping a single package, we always dump all of its
16862                // filter information since the amount of data will be reasonable.
16863                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16864            } else if ("check-permission".equals(cmd)) {
16865                if (opti >= args.length) {
16866                    pw.println("Error: check-permission missing permission argument");
16867                    return;
16868                }
16869                String perm = args[opti];
16870                opti++;
16871                if (opti >= args.length) {
16872                    pw.println("Error: check-permission missing package argument");
16873                    return;
16874                }
16875                String pkg = args[opti];
16876                opti++;
16877                int user = UserHandle.getUserId(Binder.getCallingUid());
16878                if (opti < args.length) {
16879                    try {
16880                        user = Integer.parseInt(args[opti]);
16881                    } catch (NumberFormatException e) {
16882                        pw.println("Error: check-permission user argument is not a number: "
16883                                + args[opti]);
16884                        return;
16885                    }
16886                }
16887                pw.println(checkPermission(perm, pkg, user));
16888                return;
16889            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16890                dumpState.setDump(DumpState.DUMP_LIBS);
16891            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16892                dumpState.setDump(DumpState.DUMP_FEATURES);
16893            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16894                if (opti >= args.length) {
16895                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16896                            | DumpState.DUMP_SERVICE_RESOLVERS
16897                            | DumpState.DUMP_RECEIVER_RESOLVERS
16898                            | DumpState.DUMP_CONTENT_RESOLVERS);
16899                } else {
16900                    while (opti < args.length) {
16901                        String name = args[opti];
16902                        if ("a".equals(name) || "activity".equals(name)) {
16903                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16904                        } else if ("s".equals(name) || "service".equals(name)) {
16905                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16906                        } else if ("r".equals(name) || "receiver".equals(name)) {
16907                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16908                        } else if ("c".equals(name) || "content".equals(name)) {
16909                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16910                        } else {
16911                            pw.println("Error: unknown resolver table type: " + name);
16912                            return;
16913                        }
16914                        opti++;
16915                    }
16916                }
16917            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16918                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16919            } else if ("permission".equals(cmd)) {
16920                if (opti >= args.length) {
16921                    pw.println("Error: permission requires permission name");
16922                    return;
16923                }
16924                permissionNames = new ArraySet<>();
16925                while (opti < args.length) {
16926                    permissionNames.add(args[opti]);
16927                    opti++;
16928                }
16929                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16930                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16931            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16932                dumpState.setDump(DumpState.DUMP_PREFERRED);
16933            } else if ("preferred-xml".equals(cmd)) {
16934                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16935                if (opti < args.length && "--full".equals(args[opti])) {
16936                    fullPreferred = true;
16937                    opti++;
16938                }
16939            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16940                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16941            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16942                dumpState.setDump(DumpState.DUMP_PACKAGES);
16943            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16944                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16945            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16946                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16947            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16948                dumpState.setDump(DumpState.DUMP_MESSAGES);
16949            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16950                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16951            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16952                    || "intent-filter-verifiers".equals(cmd)) {
16953                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16954            } else if ("version".equals(cmd)) {
16955                dumpState.setDump(DumpState.DUMP_VERSION);
16956            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16957                dumpState.setDump(DumpState.DUMP_KEYSETS);
16958            } else if ("installs".equals(cmd)) {
16959                dumpState.setDump(DumpState.DUMP_INSTALLS);
16960            } else if ("write".equals(cmd)) {
16961                synchronized (mPackages) {
16962                    mSettings.writeLPr();
16963                    pw.println("Settings written.");
16964                    return;
16965                }
16966            }
16967        }
16968
16969        if (checkin) {
16970            pw.println("vers,1");
16971        }
16972
16973        // reader
16974        synchronized (mPackages) {
16975            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16976                if (!checkin) {
16977                    if (dumpState.onTitlePrinted())
16978                        pw.println();
16979                    pw.println("Database versions:");
16980                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16981                }
16982            }
16983
16984            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16985                if (!checkin) {
16986                    if (dumpState.onTitlePrinted())
16987                        pw.println();
16988                    pw.println("Verifiers:");
16989                    pw.print("  Required: ");
16990                    pw.print(mRequiredVerifierPackage);
16991                    pw.print(" (uid=");
16992                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16993                            UserHandle.USER_SYSTEM));
16994                    pw.println(")");
16995                } else if (mRequiredVerifierPackage != null) {
16996                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16997                    pw.print(",");
16998                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16999                            UserHandle.USER_SYSTEM));
17000                }
17001            }
17002
17003            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17004                    packageName == null) {
17005                if (mIntentFilterVerifierComponent != null) {
17006                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17007                    if (!checkin) {
17008                        if (dumpState.onTitlePrinted())
17009                            pw.println();
17010                        pw.println("Intent Filter Verifier:");
17011                        pw.print("  Using: ");
17012                        pw.print(verifierPackageName);
17013                        pw.print(" (uid=");
17014                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17015                                UserHandle.USER_SYSTEM));
17016                        pw.println(")");
17017                    } else if (verifierPackageName != null) {
17018                        pw.print("ifv,"); pw.print(verifierPackageName);
17019                        pw.print(",");
17020                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17021                                UserHandle.USER_SYSTEM));
17022                    }
17023                } else {
17024                    pw.println();
17025                    pw.println("No Intent Filter Verifier available!");
17026                }
17027            }
17028
17029            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17030                boolean printedHeader = false;
17031                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17032                while (it.hasNext()) {
17033                    String name = it.next();
17034                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17035                    if (!checkin) {
17036                        if (!printedHeader) {
17037                            if (dumpState.onTitlePrinted())
17038                                pw.println();
17039                            pw.println("Libraries:");
17040                            printedHeader = true;
17041                        }
17042                        pw.print("  ");
17043                    } else {
17044                        pw.print("lib,");
17045                    }
17046                    pw.print(name);
17047                    if (!checkin) {
17048                        pw.print(" -> ");
17049                    }
17050                    if (ent.path != null) {
17051                        if (!checkin) {
17052                            pw.print("(jar) ");
17053                            pw.print(ent.path);
17054                        } else {
17055                            pw.print(",jar,");
17056                            pw.print(ent.path);
17057                        }
17058                    } else {
17059                        if (!checkin) {
17060                            pw.print("(apk) ");
17061                            pw.print(ent.apk);
17062                        } else {
17063                            pw.print(",apk,");
17064                            pw.print(ent.apk);
17065                        }
17066                    }
17067                    pw.println();
17068                }
17069            }
17070
17071            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17072                if (dumpState.onTitlePrinted())
17073                    pw.println();
17074                if (!checkin) {
17075                    pw.println("Features:");
17076                }
17077
17078                for (FeatureInfo feat : mAvailableFeatures.values()) {
17079                    if (checkin) {
17080                        pw.print("feat,");
17081                        pw.print(feat.name);
17082                        pw.print(",");
17083                        pw.println(feat.version);
17084                    } else {
17085                        pw.print("  ");
17086                        pw.print(feat.name);
17087                        if (feat.version > 0) {
17088                            pw.print(" version=");
17089                            pw.print(feat.version);
17090                        }
17091                        pw.println();
17092                    }
17093                }
17094            }
17095
17096            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17097                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17098                        : "Activity Resolver Table:", "  ", packageName,
17099                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17100                    dumpState.setTitlePrinted(true);
17101                }
17102            }
17103            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17104                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17105                        : "Receiver Resolver Table:", "  ", packageName,
17106                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17107                    dumpState.setTitlePrinted(true);
17108                }
17109            }
17110            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17111                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17112                        : "Service Resolver Table:", "  ", packageName,
17113                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17114                    dumpState.setTitlePrinted(true);
17115                }
17116            }
17117            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17118                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17119                        : "Provider Resolver Table:", "  ", packageName,
17120                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17121                    dumpState.setTitlePrinted(true);
17122                }
17123            }
17124
17125            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17126                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17127                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17128                    int user = mSettings.mPreferredActivities.keyAt(i);
17129                    if (pir.dump(pw,
17130                            dumpState.getTitlePrinted()
17131                                ? "\nPreferred Activities User " + user + ":"
17132                                : "Preferred Activities User " + user + ":", "  ",
17133                            packageName, true, false)) {
17134                        dumpState.setTitlePrinted(true);
17135                    }
17136                }
17137            }
17138
17139            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17140                pw.flush();
17141                FileOutputStream fout = new FileOutputStream(fd);
17142                BufferedOutputStream str = new BufferedOutputStream(fout);
17143                XmlSerializer serializer = new FastXmlSerializer();
17144                try {
17145                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17146                    serializer.startDocument(null, true);
17147                    serializer.setFeature(
17148                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17149                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17150                    serializer.endDocument();
17151                    serializer.flush();
17152                } catch (IllegalArgumentException e) {
17153                    pw.println("Failed writing: " + e);
17154                } catch (IllegalStateException e) {
17155                    pw.println("Failed writing: " + e);
17156                } catch (IOException e) {
17157                    pw.println("Failed writing: " + e);
17158                }
17159            }
17160
17161            if (!checkin
17162                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17163                    && packageName == null) {
17164                pw.println();
17165                int count = mSettings.mPackages.size();
17166                if (count == 0) {
17167                    pw.println("No applications!");
17168                    pw.println();
17169                } else {
17170                    final String prefix = "  ";
17171                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17172                    if (allPackageSettings.size() == 0) {
17173                        pw.println("No domain preferred apps!");
17174                        pw.println();
17175                    } else {
17176                        pw.println("App verification status:");
17177                        pw.println();
17178                        count = 0;
17179                        for (PackageSetting ps : allPackageSettings) {
17180                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17181                            if (ivi == null || ivi.getPackageName() == null) continue;
17182                            pw.println(prefix + "Package: " + ivi.getPackageName());
17183                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17184                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17185                            pw.println();
17186                            count++;
17187                        }
17188                        if (count == 0) {
17189                            pw.println(prefix + "No app verification established.");
17190                            pw.println();
17191                        }
17192                        for (int userId : sUserManager.getUserIds()) {
17193                            pw.println("App linkages for user " + userId + ":");
17194                            pw.println();
17195                            count = 0;
17196                            for (PackageSetting ps : allPackageSettings) {
17197                                final long status = ps.getDomainVerificationStatusForUser(userId);
17198                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17199                                    continue;
17200                                }
17201                                pw.println(prefix + "Package: " + ps.name);
17202                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17203                                String statusStr = IntentFilterVerificationInfo.
17204                                        getStatusStringFromValue(status);
17205                                pw.println(prefix + "Status:  " + statusStr);
17206                                pw.println();
17207                                count++;
17208                            }
17209                            if (count == 0) {
17210                                pw.println(prefix + "No configured app linkages.");
17211                                pw.println();
17212                            }
17213                        }
17214                    }
17215                }
17216            }
17217
17218            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17219                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17220                if (packageName == null && permissionNames == null) {
17221                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17222                        if (iperm == 0) {
17223                            if (dumpState.onTitlePrinted())
17224                                pw.println();
17225                            pw.println("AppOp Permissions:");
17226                        }
17227                        pw.print("  AppOp Permission ");
17228                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17229                        pw.println(":");
17230                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17231                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17232                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17233                        }
17234                    }
17235                }
17236            }
17237
17238            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17239                boolean printedSomething = false;
17240                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17241                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17242                        continue;
17243                    }
17244                    if (!printedSomething) {
17245                        if (dumpState.onTitlePrinted())
17246                            pw.println();
17247                        pw.println("Registered ContentProviders:");
17248                        printedSomething = true;
17249                    }
17250                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17251                    pw.print("    "); pw.println(p.toString());
17252                }
17253                printedSomething = false;
17254                for (Map.Entry<String, PackageParser.Provider> entry :
17255                        mProvidersByAuthority.entrySet()) {
17256                    PackageParser.Provider p = entry.getValue();
17257                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17258                        continue;
17259                    }
17260                    if (!printedSomething) {
17261                        if (dumpState.onTitlePrinted())
17262                            pw.println();
17263                        pw.println("ContentProvider Authorities:");
17264                        printedSomething = true;
17265                    }
17266                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17267                    pw.print("    "); pw.println(p.toString());
17268                    if (p.info != null && p.info.applicationInfo != null) {
17269                        final String appInfo = p.info.applicationInfo.toString();
17270                        pw.print("      applicationInfo="); pw.println(appInfo);
17271                    }
17272                }
17273            }
17274
17275            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17276                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17277            }
17278
17279            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17280                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17281            }
17282
17283            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17284                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17285            }
17286
17287            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17288                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17289            }
17290
17291            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17292                // XXX should handle packageName != null by dumping only install data that
17293                // the given package is involved with.
17294                if (dumpState.onTitlePrinted()) pw.println();
17295                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17296            }
17297
17298            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17299                if (dumpState.onTitlePrinted()) pw.println();
17300                mSettings.dumpReadMessagesLPr(pw, dumpState);
17301
17302                pw.println();
17303                pw.println("Package warning messages:");
17304                BufferedReader in = null;
17305                String line = null;
17306                try {
17307                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17308                    while ((line = in.readLine()) != null) {
17309                        if (line.contains("ignored: updated version")) continue;
17310                        pw.println(line);
17311                    }
17312                } catch (IOException ignored) {
17313                } finally {
17314                    IoUtils.closeQuietly(in);
17315                }
17316            }
17317
17318            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17319                BufferedReader in = null;
17320                String line = null;
17321                try {
17322                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17323                    while ((line = in.readLine()) != null) {
17324                        if (line.contains("ignored: updated version")) continue;
17325                        pw.print("msg,");
17326                        pw.println(line);
17327                    }
17328                } catch (IOException ignored) {
17329                } finally {
17330                    IoUtils.closeQuietly(in);
17331                }
17332            }
17333        }
17334    }
17335
17336    private String dumpDomainString(String packageName) {
17337        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17338        List<IntentFilter> filters = getAllIntentFilters(packageName);
17339
17340        ArraySet<String> result = new ArraySet<>();
17341        if (iviList.size() > 0) {
17342            for (IntentFilterVerificationInfo ivi : iviList) {
17343                for (String host : ivi.getDomains()) {
17344                    result.add(host);
17345                }
17346            }
17347        }
17348        if (filters != null && filters.size() > 0) {
17349            for (IntentFilter filter : filters) {
17350                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17351                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17352                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17353                    result.addAll(filter.getHostsList());
17354                }
17355            }
17356        }
17357
17358        StringBuilder sb = new StringBuilder(result.size() * 16);
17359        for (String domain : result) {
17360            if (sb.length() > 0) sb.append(" ");
17361            sb.append(domain);
17362        }
17363        return sb.toString();
17364    }
17365
17366    // ------- apps on sdcard specific code -------
17367    static final boolean DEBUG_SD_INSTALL = false;
17368
17369    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17370
17371    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17372
17373    private boolean mMediaMounted = false;
17374
17375    static String getEncryptKey() {
17376        try {
17377            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17378                    SD_ENCRYPTION_KEYSTORE_NAME);
17379            if (sdEncKey == null) {
17380                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17381                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17382                if (sdEncKey == null) {
17383                    Slog.e(TAG, "Failed to create encryption keys");
17384                    return null;
17385                }
17386            }
17387            return sdEncKey;
17388        } catch (NoSuchAlgorithmException nsae) {
17389            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17390            return null;
17391        } catch (IOException ioe) {
17392            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17393            return null;
17394        }
17395    }
17396
17397    /*
17398     * Update media status on PackageManager.
17399     */
17400    @Override
17401    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17402        int callingUid = Binder.getCallingUid();
17403        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17404            throw new SecurityException("Media status can only be updated by the system");
17405        }
17406        // reader; this apparently protects mMediaMounted, but should probably
17407        // be a different lock in that case.
17408        synchronized (mPackages) {
17409            Log.i(TAG, "Updating external media status from "
17410                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17411                    + (mediaStatus ? "mounted" : "unmounted"));
17412            if (DEBUG_SD_INSTALL)
17413                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17414                        + ", mMediaMounted=" + mMediaMounted);
17415            if (mediaStatus == mMediaMounted) {
17416                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17417                        : 0, -1);
17418                mHandler.sendMessage(msg);
17419                return;
17420            }
17421            mMediaMounted = mediaStatus;
17422        }
17423        // Queue up an async operation since the package installation may take a
17424        // little while.
17425        mHandler.post(new Runnable() {
17426            public void run() {
17427                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17428            }
17429        });
17430    }
17431
17432    /**
17433     * Called by MountService when the initial ASECs to scan are available.
17434     * Should block until all the ASEC containers are finished being scanned.
17435     */
17436    public void scanAvailableAsecs() {
17437        updateExternalMediaStatusInner(true, false, false);
17438    }
17439
17440    /*
17441     * Collect information of applications on external media, map them against
17442     * existing containers and update information based on current mount status.
17443     * Please note that we always have to report status if reportStatus has been
17444     * set to true especially when unloading packages.
17445     */
17446    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17447            boolean externalStorage) {
17448        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17449        int[] uidArr = EmptyArray.INT;
17450
17451        final String[] list = PackageHelper.getSecureContainerList();
17452        if (ArrayUtils.isEmpty(list)) {
17453            Log.i(TAG, "No secure containers found");
17454        } else {
17455            // Process list of secure containers and categorize them
17456            // as active or stale based on their package internal state.
17457
17458            // reader
17459            synchronized (mPackages) {
17460                for (String cid : list) {
17461                    // Leave stages untouched for now; installer service owns them
17462                    if (PackageInstallerService.isStageName(cid)) continue;
17463
17464                    if (DEBUG_SD_INSTALL)
17465                        Log.i(TAG, "Processing container " + cid);
17466                    String pkgName = getAsecPackageName(cid);
17467                    if (pkgName == null) {
17468                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17469                        continue;
17470                    }
17471                    if (DEBUG_SD_INSTALL)
17472                        Log.i(TAG, "Looking for pkg : " + pkgName);
17473
17474                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17475                    if (ps == null) {
17476                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17477                        continue;
17478                    }
17479
17480                    /*
17481                     * Skip packages that are not external if we're unmounting
17482                     * external storage.
17483                     */
17484                    if (externalStorage && !isMounted && !isExternal(ps)) {
17485                        continue;
17486                    }
17487
17488                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17489                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17490                    // The package status is changed only if the code path
17491                    // matches between settings and the container id.
17492                    if (ps.codePathString != null
17493                            && ps.codePathString.startsWith(args.getCodePath())) {
17494                        if (DEBUG_SD_INSTALL) {
17495                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17496                                    + " at code path: " + ps.codePathString);
17497                        }
17498
17499                        // We do have a valid package installed on sdcard
17500                        processCids.put(args, ps.codePathString);
17501                        final int uid = ps.appId;
17502                        if (uid != -1) {
17503                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17504                        }
17505                    } else {
17506                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17507                                + ps.codePathString);
17508                    }
17509                }
17510            }
17511
17512            Arrays.sort(uidArr);
17513        }
17514
17515        // Process packages with valid entries.
17516        if (isMounted) {
17517            if (DEBUG_SD_INSTALL)
17518                Log.i(TAG, "Loading packages");
17519            loadMediaPackages(processCids, uidArr, externalStorage);
17520            startCleaningPackages();
17521            mInstallerService.onSecureContainersAvailable();
17522        } else {
17523            if (DEBUG_SD_INSTALL)
17524                Log.i(TAG, "Unloading packages");
17525            unloadMediaPackages(processCids, uidArr, reportStatus);
17526        }
17527    }
17528
17529    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17530            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17531        final int size = infos.size();
17532        final String[] packageNames = new String[size];
17533        final int[] packageUids = new int[size];
17534        for (int i = 0; i < size; i++) {
17535            final ApplicationInfo info = infos.get(i);
17536            packageNames[i] = info.packageName;
17537            packageUids[i] = info.uid;
17538        }
17539        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17540                finishedReceiver);
17541    }
17542
17543    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17544            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17545        sendResourcesChangedBroadcast(mediaStatus, replacing,
17546                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17547    }
17548
17549    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17550            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17551        int size = pkgList.length;
17552        if (size > 0) {
17553            // Send broadcasts here
17554            Bundle extras = new Bundle();
17555            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17556            if (uidArr != null) {
17557                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17558            }
17559            if (replacing) {
17560                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17561            }
17562            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17563                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17564            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17565        }
17566    }
17567
17568   /*
17569     * Look at potentially valid container ids from processCids If package
17570     * information doesn't match the one on record or package scanning fails,
17571     * the cid is added to list of removeCids. We currently don't delete stale
17572     * containers.
17573     */
17574    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17575            boolean externalStorage) {
17576        ArrayList<String> pkgList = new ArrayList<String>();
17577        Set<AsecInstallArgs> keys = processCids.keySet();
17578
17579        for (AsecInstallArgs args : keys) {
17580            String codePath = processCids.get(args);
17581            if (DEBUG_SD_INSTALL)
17582                Log.i(TAG, "Loading container : " + args.cid);
17583            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17584            try {
17585                // Make sure there are no container errors first.
17586                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17587                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17588                            + " when installing from sdcard");
17589                    continue;
17590                }
17591                // Check code path here.
17592                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17593                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17594                            + " does not match one in settings " + codePath);
17595                    continue;
17596                }
17597                // Parse package
17598                int parseFlags = mDefParseFlags;
17599                if (args.isExternalAsec()) {
17600                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17601                }
17602                if (args.isFwdLocked()) {
17603                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17604                }
17605
17606                synchronized (mInstallLock) {
17607                    PackageParser.Package pkg = null;
17608                    try {
17609                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17610                    } catch (PackageManagerException e) {
17611                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17612                    }
17613                    // Scan the package
17614                    if (pkg != null) {
17615                        /*
17616                         * TODO why is the lock being held? doPostInstall is
17617                         * called in other places without the lock. This needs
17618                         * to be straightened out.
17619                         */
17620                        // writer
17621                        synchronized (mPackages) {
17622                            retCode = PackageManager.INSTALL_SUCCEEDED;
17623                            pkgList.add(pkg.packageName);
17624                            // Post process args
17625                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17626                                    pkg.applicationInfo.uid);
17627                        }
17628                    } else {
17629                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17630                    }
17631                }
17632
17633            } finally {
17634                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17635                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17636                }
17637            }
17638        }
17639        // writer
17640        synchronized (mPackages) {
17641            // If the platform SDK has changed since the last time we booted,
17642            // we need to re-grant app permission to catch any new ones that
17643            // appear. This is really a hack, and means that apps can in some
17644            // cases get permissions that the user didn't initially explicitly
17645            // allow... it would be nice to have some better way to handle
17646            // this situation.
17647            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17648                    : mSettings.getInternalVersion();
17649            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17650                    : StorageManager.UUID_PRIVATE_INTERNAL;
17651
17652            int updateFlags = UPDATE_PERMISSIONS_ALL;
17653            if (ver.sdkVersion != mSdkVersion) {
17654                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17655                        + mSdkVersion + "; regranting permissions for external");
17656                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17657            }
17658            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17659
17660            // Yay, everything is now upgraded
17661            ver.forceCurrent();
17662
17663            // can downgrade to reader
17664            // Persist settings
17665            mSettings.writeLPr();
17666        }
17667        // Send a broadcast to let everyone know we are done processing
17668        if (pkgList.size() > 0) {
17669            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17670        }
17671    }
17672
17673   /*
17674     * Utility method to unload a list of specified containers
17675     */
17676    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17677        // Just unmount all valid containers.
17678        for (AsecInstallArgs arg : cidArgs) {
17679            synchronized (mInstallLock) {
17680                arg.doPostDeleteLI(false);
17681           }
17682       }
17683   }
17684
17685    /*
17686     * Unload packages mounted on external media. This involves deleting package
17687     * data from internal structures, sending broadcasts about disabled packages,
17688     * gc'ing to free up references, unmounting all secure containers
17689     * corresponding to packages on external media, and posting a
17690     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17691     * that we always have to post this message if status has been requested no
17692     * matter what.
17693     */
17694    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17695            final boolean reportStatus) {
17696        if (DEBUG_SD_INSTALL)
17697            Log.i(TAG, "unloading media packages");
17698        ArrayList<String> pkgList = new ArrayList<String>();
17699        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17700        final Set<AsecInstallArgs> keys = processCids.keySet();
17701        for (AsecInstallArgs args : keys) {
17702            String pkgName = args.getPackageName();
17703            if (DEBUG_SD_INSTALL)
17704                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17705            // Delete package internally
17706            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17707            synchronized (mInstallLock) {
17708                boolean res = deletePackageLI(pkgName, null, false, null,
17709                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17710                if (res) {
17711                    pkgList.add(pkgName);
17712                } else {
17713                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17714                    failedList.add(args);
17715                }
17716            }
17717        }
17718
17719        // reader
17720        synchronized (mPackages) {
17721            // We didn't update the settings after removing each package;
17722            // write them now for all packages.
17723            mSettings.writeLPr();
17724        }
17725
17726        // We have to absolutely send UPDATED_MEDIA_STATUS only
17727        // after confirming that all the receivers processed the ordered
17728        // broadcast when packages get disabled, force a gc to clean things up.
17729        // and unload all the containers.
17730        if (pkgList.size() > 0) {
17731            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17732                    new IIntentReceiver.Stub() {
17733                public void performReceive(Intent intent, int resultCode, String data,
17734                        Bundle extras, boolean ordered, boolean sticky,
17735                        int sendingUser) throws RemoteException {
17736                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17737                            reportStatus ? 1 : 0, 1, keys);
17738                    mHandler.sendMessage(msg);
17739                }
17740            });
17741        } else {
17742            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17743                    keys);
17744            mHandler.sendMessage(msg);
17745        }
17746    }
17747
17748    private void loadPrivatePackages(final VolumeInfo vol) {
17749        mHandler.post(new Runnable() {
17750            @Override
17751            public void run() {
17752                loadPrivatePackagesInner(vol);
17753            }
17754        });
17755    }
17756
17757    private void loadPrivatePackagesInner(VolumeInfo vol) {
17758        final String volumeUuid = vol.fsUuid;
17759        if (TextUtils.isEmpty(volumeUuid)) {
17760            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17761            return;
17762        }
17763
17764        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17765        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17766
17767        final VersionInfo ver;
17768        final List<PackageSetting> packages;
17769        synchronized (mPackages) {
17770            ver = mSettings.findOrCreateVersion(volumeUuid);
17771            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17772        }
17773
17774        // TODO: introduce a new concept similar to "frozen" to prevent these
17775        // apps from being launched until after data has been fully reconciled
17776        for (PackageSetting ps : packages) {
17777            synchronized (mInstallLock) {
17778                final PackageParser.Package pkg;
17779                try {
17780                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17781                    loaded.add(pkg.applicationInfo);
17782
17783                } catch (PackageManagerException e) {
17784                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17785                }
17786
17787                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17788                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17789                }
17790            }
17791        }
17792
17793        // Reconcile app data for all started/unlocked users
17794        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17795        final UserManager um = mContext.getSystemService(UserManager.class);
17796        for (UserInfo user : um.getUsers()) {
17797            final int flags;
17798            if (um.isUserUnlocked(user.id)) {
17799                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17800            } else if (um.isUserRunning(user.id)) {
17801                flags = StorageManager.FLAG_STORAGE_DE;
17802            } else {
17803                continue;
17804            }
17805
17806            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17807            reconcileAppsData(volumeUuid, user.id, flags);
17808        }
17809
17810        synchronized (mPackages) {
17811            int updateFlags = UPDATE_PERMISSIONS_ALL;
17812            if (ver.sdkVersion != mSdkVersion) {
17813                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17814                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17815                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17816            }
17817            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17818
17819            // Yay, everything is now upgraded
17820            ver.forceCurrent();
17821
17822            mSettings.writeLPr();
17823        }
17824
17825        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17826        sendResourcesChangedBroadcast(true, false, loaded, null);
17827    }
17828
17829    private void unloadPrivatePackages(final VolumeInfo vol) {
17830        mHandler.post(new Runnable() {
17831            @Override
17832            public void run() {
17833                unloadPrivatePackagesInner(vol);
17834            }
17835        });
17836    }
17837
17838    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17839        final String volumeUuid = vol.fsUuid;
17840        if (TextUtils.isEmpty(volumeUuid)) {
17841            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17842            return;
17843        }
17844
17845        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17846        synchronized (mInstallLock) {
17847        synchronized (mPackages) {
17848            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17849            for (PackageSetting ps : packages) {
17850                if (ps.pkg == null) continue;
17851
17852                final ApplicationInfo info = ps.pkg.applicationInfo;
17853                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17854                if (deletePackageLI(ps.name, null, false, null,
17855                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17856                    unloaded.add(info);
17857                } else {
17858                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17859                }
17860            }
17861
17862            mSettings.writeLPr();
17863        }
17864        }
17865
17866        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17867        sendResourcesChangedBroadcast(false, false, unloaded, null);
17868    }
17869
17870    /**
17871     * Examine all users present on given mounted volume, and destroy data
17872     * belonging to users that are no longer valid, or whose user ID has been
17873     * recycled.
17874     */
17875    private void reconcileUsers(String volumeUuid) {
17876        // TODO: also reconcile DE directories
17877        final File[] files = FileUtils
17878                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17879        for (File file : files) {
17880            if (!file.isDirectory()) continue;
17881
17882            final int userId;
17883            final UserInfo info;
17884            try {
17885                userId = Integer.parseInt(file.getName());
17886                info = sUserManager.getUserInfo(userId);
17887            } catch (NumberFormatException e) {
17888                Slog.w(TAG, "Invalid user directory " + file);
17889                continue;
17890            }
17891
17892            boolean destroyUser = false;
17893            if (info == null) {
17894                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17895                        + " because no matching user was found");
17896                destroyUser = true;
17897            } else {
17898                try {
17899                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17900                } catch (IOException e) {
17901                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17902                            + " because we failed to enforce serial number: " + e);
17903                    destroyUser = true;
17904                }
17905            }
17906
17907            if (destroyUser) {
17908                synchronized (mInstallLock) {
17909                    try {
17910                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17911                    } catch (InstallerException e) {
17912                        Slog.w(TAG, "Failed to clean up user dirs", e);
17913                    }
17914                }
17915            }
17916        }
17917    }
17918
17919    private void assertPackageKnown(String volumeUuid, String packageName)
17920            throws PackageManagerException {
17921        synchronized (mPackages) {
17922            final PackageSetting ps = mSettings.mPackages.get(packageName);
17923            if (ps == null) {
17924                throw new PackageManagerException("Package " + packageName + " is unknown");
17925            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17926                throw new PackageManagerException(
17927                        "Package " + packageName + " found on unknown volume " + volumeUuid
17928                                + "; expected volume " + ps.volumeUuid);
17929            }
17930        }
17931    }
17932
17933    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17934            throws PackageManagerException {
17935        synchronized (mPackages) {
17936            final PackageSetting ps = mSettings.mPackages.get(packageName);
17937            if (ps == null) {
17938                throw new PackageManagerException("Package " + packageName + " is unknown");
17939            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17940                throw new PackageManagerException(
17941                        "Package " + packageName + " found on unknown volume " + volumeUuid
17942                                + "; expected volume " + ps.volumeUuid);
17943            } else if (!ps.getInstalled(userId)) {
17944                throw new PackageManagerException(
17945                        "Package " + packageName + " not installed for user " + userId);
17946            }
17947        }
17948    }
17949
17950    /**
17951     * Examine all apps present on given mounted volume, and destroy apps that
17952     * aren't expected, either due to uninstallation or reinstallation on
17953     * another volume.
17954     */
17955    private void reconcileApps(String volumeUuid) {
17956        final File[] files = FileUtils
17957                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17958        for (File file : files) {
17959            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17960                    && !PackageInstallerService.isStageName(file.getName());
17961            if (!isPackage) {
17962                // Ignore entries which are not packages
17963                continue;
17964            }
17965
17966            try {
17967                final PackageLite pkg = PackageParser.parsePackageLite(file,
17968                        PackageParser.PARSE_MUST_BE_APK);
17969                assertPackageKnown(volumeUuid, pkg.packageName);
17970
17971            } catch (PackageParserException | PackageManagerException e) {
17972                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17973                synchronized (mInstallLock) {
17974                    removeCodePathLI(file);
17975                }
17976            }
17977        }
17978    }
17979
17980    /**
17981     * Reconcile all app data for the given user.
17982     * <p>
17983     * Verifies that directories exist and that ownership and labeling is
17984     * correct for all installed apps on all mounted volumes.
17985     */
17986    void reconcileAppsData(int userId, int flags) {
17987        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17988        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17989            final String volumeUuid = vol.getFsUuid();
17990            reconcileAppsData(volumeUuid, userId, flags);
17991        }
17992    }
17993
17994    /**
17995     * Reconcile all app data on given mounted volume.
17996     * <p>
17997     * Destroys app data that isn't expected, either due to uninstallation or
17998     * reinstallation on another volume.
17999     * <p>
18000     * Verifies that directories exist and that ownership and labeling is
18001     * correct for all installed apps.
18002     */
18003    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18004        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18005                + Integer.toHexString(flags));
18006
18007        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18008        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18009
18010        boolean restoreconNeeded = false;
18011
18012        // First look for stale data that doesn't belong, and check if things
18013        // have changed since we did our last restorecon
18014        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18015            if (!isUserKeyUnlocked(userId)) {
18016                throw new RuntimeException(
18017                        "Yikes, someone asked us to reconcile CE storage while " + userId
18018                                + " was still locked; this would have caused massive data loss!");
18019            }
18020
18021            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18022
18023            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18024            for (File file : files) {
18025                final String packageName = file.getName();
18026                try {
18027                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18028                } catch (PackageManagerException e) {
18029                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18030                    synchronized (mInstallLock) {
18031                        destroyAppDataLI(volumeUuid, packageName, userId,
18032                                StorageManager.FLAG_STORAGE_CE);
18033                    }
18034                }
18035            }
18036        }
18037        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18038            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18039
18040            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18041            for (File file : files) {
18042                final String packageName = file.getName();
18043                try {
18044                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18045                } catch (PackageManagerException e) {
18046                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18047                    synchronized (mInstallLock) {
18048                        destroyAppDataLI(volumeUuid, packageName, userId,
18049                                StorageManager.FLAG_STORAGE_DE);
18050                    }
18051                }
18052            }
18053        }
18054
18055        // Ensure that data directories are ready to roll for all packages
18056        // installed for this volume and user
18057        final List<PackageSetting> packages;
18058        synchronized (mPackages) {
18059            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18060        }
18061        int preparedCount = 0;
18062        for (PackageSetting ps : packages) {
18063            final String packageName = ps.name;
18064            if (ps.pkg == null) {
18065                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18066                // TODO: might be due to legacy ASEC apps; we should circle back
18067                // and reconcile again once they're scanned
18068                continue;
18069            }
18070
18071            if (ps.getInstalled(userId)) {
18072                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18073
18074                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18075                    // We may have just shuffled around app data directories, so
18076                    // prepare them one more time
18077                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18078                }
18079
18080                preparedCount++;
18081            }
18082        }
18083
18084        if (restoreconNeeded) {
18085            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18086                SELinuxMMAC.setRestoreconDone(ceDir);
18087            }
18088            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18089                SELinuxMMAC.setRestoreconDone(deDir);
18090            }
18091        }
18092
18093        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18094                + " packages; restoreconNeeded was " + restoreconNeeded);
18095    }
18096
18097    /**
18098     * Prepare app data for the given app just after it was installed or
18099     * upgraded. This method carefully only touches users that it's installed
18100     * for, and it forces a restorecon to handle any seinfo changes.
18101     * <p>
18102     * Verifies that directories exist and that ownership and labeling is
18103     * correct for all installed apps. If there is an ownership mismatch, it
18104     * will try recovering system apps by wiping data; third-party app data is
18105     * left intact.
18106     * <p>
18107     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18108     */
18109    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18110        prepareAppDataAfterInstallInternal(pkg);
18111        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18112        for (int i = 0; i < childCount; i++) {
18113            PackageParser.Package childPackage = pkg.childPackages.get(i);
18114            prepareAppDataAfterInstallInternal(childPackage);
18115        }
18116    }
18117
18118    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18119        final PackageSetting ps;
18120        synchronized (mPackages) {
18121            ps = mSettings.mPackages.get(pkg.packageName);
18122            mSettings.writeKernelMappingLPr(ps);
18123        }
18124
18125        final UserManager um = mContext.getSystemService(UserManager.class);
18126        for (UserInfo user : um.getUsers()) {
18127            final int flags;
18128            if (um.isUserUnlocked(user.id)) {
18129                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18130            } else if (um.isUserRunning(user.id)) {
18131                flags = StorageManager.FLAG_STORAGE_DE;
18132            } else {
18133                continue;
18134            }
18135
18136            if (ps.getInstalled(user.id)) {
18137                // Whenever an app changes, force a restorecon of its data
18138                // TODO: when user data is locked, mark that we're still dirty
18139                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18140            }
18141        }
18142    }
18143
18144    /**
18145     * Prepare app data for the given app.
18146     * <p>
18147     * Verifies that directories exist and that ownership and labeling is
18148     * correct for all installed apps. If there is an ownership mismatch, this
18149     * will try recovering system apps by wiping data; third-party app data is
18150     * left intact.
18151     */
18152    private void prepareAppData(String volumeUuid, int userId, int flags,
18153            PackageParser.Package pkg, boolean restoreconNeeded) {
18154        if (DEBUG_APP_DATA) {
18155            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18156                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18157        }
18158
18159        final String packageName = pkg.packageName;
18160        final ApplicationInfo app = pkg.applicationInfo;
18161        final int appId = UserHandle.getAppId(app.uid);
18162
18163        Preconditions.checkNotNull(app.seinfo);
18164
18165        synchronized (mInstallLock) {
18166            try {
18167                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18168                        appId, app.seinfo, app.targetSdkVersion);
18169            } catch (InstallerException e) {
18170                if (app.isSystemApp()) {
18171                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18172                            + ", but trying to recover: " + e);
18173                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18174                    try {
18175                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18176                                appId, app.seinfo, app.targetSdkVersion);
18177                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18178                    } catch (InstallerException e2) {
18179                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18180                    }
18181                } else {
18182                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18183                }
18184            }
18185
18186            if (restoreconNeeded) {
18187                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18188            }
18189
18190            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18191                // Create a native library symlink only if we have native libraries
18192                // and if the native libraries are 32 bit libraries. We do not provide
18193                // this symlink for 64 bit libraries.
18194                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18195                    final String nativeLibPath = app.nativeLibraryDir;
18196                    try {
18197                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18198                                nativeLibPath, userId);
18199                    } catch (InstallerException e) {
18200                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18201                    }
18202                }
18203            }
18204        }
18205    }
18206
18207    /**
18208     * For system apps on non-FBE devices, this method migrates any existing
18209     * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by
18210     * the app.
18211     */
18212    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18213        if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled()
18214                && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
18215            final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted()
18216                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18217            synchronized (mInstallLock) {
18218                try {
18219                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18220                } catch (InstallerException e) {
18221                    logCriticalInfo(Log.WARN,
18222                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18223                }
18224            }
18225            return true;
18226        } else {
18227            return false;
18228        }
18229    }
18230
18231    private void unfreezePackage(String packageName) {
18232        synchronized (mPackages) {
18233            final PackageSetting ps = mSettings.mPackages.get(packageName);
18234            if (ps != null) {
18235                ps.frozen = false;
18236            }
18237        }
18238    }
18239
18240    @Override
18241    public int movePackage(final String packageName, final String volumeUuid) {
18242        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18243
18244        final int moveId = mNextMoveId.getAndIncrement();
18245        mHandler.post(new Runnable() {
18246            @Override
18247            public void run() {
18248                try {
18249                    movePackageInternal(packageName, volumeUuid, moveId);
18250                } catch (PackageManagerException e) {
18251                    Slog.w(TAG, "Failed to move " + packageName, e);
18252                    mMoveCallbacks.notifyStatusChanged(moveId,
18253                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18254                }
18255            }
18256        });
18257        return moveId;
18258    }
18259
18260    private void movePackageInternal(final String packageName, final String volumeUuid,
18261            final int moveId) throws PackageManagerException {
18262        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18263        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18264        final PackageManager pm = mContext.getPackageManager();
18265
18266        final boolean currentAsec;
18267        final String currentVolumeUuid;
18268        final File codeFile;
18269        final String installerPackageName;
18270        final String packageAbiOverride;
18271        final int appId;
18272        final String seinfo;
18273        final String label;
18274        final int targetSdkVersion;
18275
18276        // reader
18277        synchronized (mPackages) {
18278            final PackageParser.Package pkg = mPackages.get(packageName);
18279            final PackageSetting ps = mSettings.mPackages.get(packageName);
18280            if (pkg == null || ps == null) {
18281                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18282            }
18283
18284            if (pkg.applicationInfo.isSystemApp()) {
18285                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18286                        "Cannot move system application");
18287            }
18288
18289            if (pkg.applicationInfo.isExternalAsec()) {
18290                currentAsec = true;
18291                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18292            } else if (pkg.applicationInfo.isForwardLocked()) {
18293                currentAsec = true;
18294                currentVolumeUuid = "forward_locked";
18295            } else {
18296                currentAsec = false;
18297                currentVolumeUuid = ps.volumeUuid;
18298
18299                final File probe = new File(pkg.codePath);
18300                final File probeOat = new File(probe, "oat");
18301                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18302                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18303                            "Move only supported for modern cluster style installs");
18304                }
18305            }
18306
18307            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18308                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18309                        "Package already moved to " + volumeUuid);
18310            }
18311            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18312                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18313                        "Device admin cannot be moved");
18314            }
18315
18316            if (ps.frozen) {
18317                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18318                        "Failed to move already frozen package");
18319            }
18320            ps.frozen = true;
18321
18322            codeFile = new File(pkg.codePath);
18323            installerPackageName = ps.installerPackageName;
18324            packageAbiOverride = ps.cpuAbiOverrideString;
18325            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18326            seinfo = pkg.applicationInfo.seinfo;
18327            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18328            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18329        }
18330
18331        // Now that we're guarded by frozen state, kill app during move
18332        final long token = Binder.clearCallingIdentity();
18333        try {
18334            killApplication(packageName, appId, "move pkg");
18335        } finally {
18336            Binder.restoreCallingIdentity(token);
18337        }
18338
18339        final Bundle extras = new Bundle();
18340        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18341        extras.putString(Intent.EXTRA_TITLE, label);
18342        mMoveCallbacks.notifyCreated(moveId, extras);
18343
18344        int installFlags;
18345        final boolean moveCompleteApp;
18346        final File measurePath;
18347
18348        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18349            installFlags = INSTALL_INTERNAL;
18350            moveCompleteApp = !currentAsec;
18351            measurePath = Environment.getDataAppDirectory(volumeUuid);
18352        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18353            installFlags = INSTALL_EXTERNAL;
18354            moveCompleteApp = false;
18355            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18356        } else {
18357            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18358            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18359                    || !volume.isMountedWritable()) {
18360                unfreezePackage(packageName);
18361                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18362                        "Move location not mounted private volume");
18363            }
18364
18365            Preconditions.checkState(!currentAsec);
18366
18367            installFlags = INSTALL_INTERNAL;
18368            moveCompleteApp = true;
18369            measurePath = Environment.getDataAppDirectory(volumeUuid);
18370        }
18371
18372        final PackageStats stats = new PackageStats(null, -1);
18373        synchronized (mInstaller) {
18374            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18375                unfreezePackage(packageName);
18376                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18377                        "Failed to measure package size");
18378            }
18379        }
18380
18381        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18382                + stats.dataSize);
18383
18384        final long startFreeBytes = measurePath.getFreeSpace();
18385        final long sizeBytes;
18386        if (moveCompleteApp) {
18387            sizeBytes = stats.codeSize + stats.dataSize;
18388        } else {
18389            sizeBytes = stats.codeSize;
18390        }
18391
18392        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18393            unfreezePackage(packageName);
18394            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18395                    "Not enough free space to move");
18396        }
18397
18398        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18399
18400        final CountDownLatch installedLatch = new CountDownLatch(1);
18401        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18402            @Override
18403            public void onUserActionRequired(Intent intent) throws RemoteException {
18404                throw new IllegalStateException();
18405            }
18406
18407            @Override
18408            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18409                    Bundle extras) throws RemoteException {
18410                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18411                        + PackageManager.installStatusToString(returnCode, msg));
18412
18413                installedLatch.countDown();
18414
18415                // Regardless of success or failure of the move operation,
18416                // always unfreeze the package
18417                unfreezePackage(packageName);
18418
18419                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18420                switch (status) {
18421                    case PackageInstaller.STATUS_SUCCESS:
18422                        mMoveCallbacks.notifyStatusChanged(moveId,
18423                                PackageManager.MOVE_SUCCEEDED);
18424                        break;
18425                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18426                        mMoveCallbacks.notifyStatusChanged(moveId,
18427                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18428                        break;
18429                    default:
18430                        mMoveCallbacks.notifyStatusChanged(moveId,
18431                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18432                        break;
18433                }
18434            }
18435        };
18436
18437        final MoveInfo move;
18438        if (moveCompleteApp) {
18439            // Kick off a thread to report progress estimates
18440            new Thread() {
18441                @Override
18442                public void run() {
18443                    while (true) {
18444                        try {
18445                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18446                                break;
18447                            }
18448                        } catch (InterruptedException ignored) {
18449                        }
18450
18451                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18452                        final int progress = 10 + (int) MathUtils.constrain(
18453                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18454                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18455                    }
18456                }
18457            }.start();
18458
18459            final String dataAppName = codeFile.getName();
18460            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18461                    dataAppName, appId, seinfo, targetSdkVersion);
18462        } else {
18463            move = null;
18464        }
18465
18466        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18467
18468        final Message msg = mHandler.obtainMessage(INIT_COPY);
18469        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18470        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18471                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18472                packageAbiOverride, null);
18473        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18474        msg.obj = params;
18475
18476        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18477                System.identityHashCode(msg.obj));
18478        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18479                System.identityHashCode(msg.obj));
18480
18481        mHandler.sendMessage(msg);
18482    }
18483
18484    @Override
18485    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18486        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18487
18488        final int realMoveId = mNextMoveId.getAndIncrement();
18489        final Bundle extras = new Bundle();
18490        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18491        mMoveCallbacks.notifyCreated(realMoveId, extras);
18492
18493        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18494            @Override
18495            public void onCreated(int moveId, Bundle extras) {
18496                // Ignored
18497            }
18498
18499            @Override
18500            public void onStatusChanged(int moveId, int status, long estMillis) {
18501                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18502            }
18503        };
18504
18505        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18506        storage.setPrimaryStorageUuid(volumeUuid, callback);
18507        return realMoveId;
18508    }
18509
18510    @Override
18511    public int getMoveStatus(int moveId) {
18512        mContext.enforceCallingOrSelfPermission(
18513                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18514        return mMoveCallbacks.mLastStatus.get(moveId);
18515    }
18516
18517    @Override
18518    public void registerMoveCallback(IPackageMoveObserver callback) {
18519        mContext.enforceCallingOrSelfPermission(
18520                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18521        mMoveCallbacks.register(callback);
18522    }
18523
18524    @Override
18525    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18526        mContext.enforceCallingOrSelfPermission(
18527                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18528        mMoveCallbacks.unregister(callback);
18529    }
18530
18531    @Override
18532    public boolean setInstallLocation(int loc) {
18533        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18534                null);
18535        if (getInstallLocation() == loc) {
18536            return true;
18537        }
18538        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18539                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18540            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18541                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18542            return true;
18543        }
18544        return false;
18545   }
18546
18547    @Override
18548    public int getInstallLocation() {
18549        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18550                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18551                PackageHelper.APP_INSTALL_AUTO);
18552    }
18553
18554    /** Called by UserManagerService */
18555    void cleanUpUser(UserManagerService userManager, int userHandle) {
18556        synchronized (mPackages) {
18557            mDirtyUsers.remove(userHandle);
18558            mUserNeedsBadging.delete(userHandle);
18559            mSettings.removeUserLPw(userHandle);
18560            mPendingBroadcasts.remove(userHandle);
18561            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18562        }
18563        synchronized (mInstallLock) {
18564            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18565            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18566                final String volumeUuid = vol.getFsUuid();
18567                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18568                try {
18569                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18570                } catch (InstallerException e) {
18571                    Slog.w(TAG, "Failed to remove user data", e);
18572                }
18573            }
18574            synchronized (mPackages) {
18575                removeUnusedPackagesLILPw(userManager, userHandle);
18576            }
18577        }
18578    }
18579
18580    /**
18581     * We're removing userHandle and would like to remove any downloaded packages
18582     * that are no longer in use by any other user.
18583     * @param userHandle the user being removed
18584     */
18585    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18586        final boolean DEBUG_CLEAN_APKS = false;
18587        int [] users = userManager.getUserIds();
18588        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18589        while (psit.hasNext()) {
18590            PackageSetting ps = psit.next();
18591            if (ps.pkg == null) {
18592                continue;
18593            }
18594            final String packageName = ps.pkg.packageName;
18595            // Skip over if system app
18596            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18597                continue;
18598            }
18599            if (DEBUG_CLEAN_APKS) {
18600                Slog.i(TAG, "Checking package " + packageName);
18601            }
18602            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18603            if (keep) {
18604                if (DEBUG_CLEAN_APKS) {
18605                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18606                }
18607            } else {
18608                for (int i = 0; i < users.length; i++) {
18609                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18610                        keep = true;
18611                        if (DEBUG_CLEAN_APKS) {
18612                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18613                                    + users[i]);
18614                        }
18615                        break;
18616                    }
18617                }
18618            }
18619            if (!keep) {
18620                if (DEBUG_CLEAN_APKS) {
18621                    Slog.i(TAG, "  Removing package " + packageName);
18622                }
18623                mHandler.post(new Runnable() {
18624                    public void run() {
18625                        deletePackageX(packageName, userHandle, 0);
18626                    } //end run
18627                });
18628            }
18629        }
18630    }
18631
18632    /** Called by UserManagerService */
18633    void createNewUser(int userHandle) {
18634        synchronized (mInstallLock) {
18635            try {
18636                mInstaller.createUserConfig(userHandle);
18637            } catch (InstallerException e) {
18638                Slog.w(TAG, "Failed to create user config", e);
18639            }
18640            mSettings.createNewUserLI(this, mInstaller, userHandle);
18641        }
18642        synchronized (mPackages) {
18643            applyFactoryDefaultBrowserLPw(userHandle);
18644            primeDomainVerificationsLPw(userHandle);
18645        }
18646    }
18647
18648    void newUserCreated(final int userHandle) {
18649        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18650        // If permission review for legacy apps is required, we represent
18651        // dagerous permissions for such apps as always granted runtime
18652        // permissions to keep per user flag state whether review is needed.
18653        // Hence, if a new user is added we have to propagate dangerous
18654        // permission grants for these legacy apps.
18655        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18656            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18657                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18658        }
18659    }
18660
18661    @Override
18662    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18663        mContext.enforceCallingOrSelfPermission(
18664                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18665                "Only package verification agents can read the verifier device identity");
18666
18667        synchronized (mPackages) {
18668            return mSettings.getVerifierDeviceIdentityLPw();
18669        }
18670    }
18671
18672    @Override
18673    public void setPermissionEnforced(String permission, boolean enforced) {
18674        // TODO: Now that we no longer change GID for storage, this should to away.
18675        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18676                "setPermissionEnforced");
18677        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18678            synchronized (mPackages) {
18679                if (mSettings.mReadExternalStorageEnforced == null
18680                        || mSettings.mReadExternalStorageEnforced != enforced) {
18681                    mSettings.mReadExternalStorageEnforced = enforced;
18682                    mSettings.writeLPr();
18683                }
18684            }
18685            // kill any non-foreground processes so we restart them and
18686            // grant/revoke the GID.
18687            final IActivityManager am = ActivityManagerNative.getDefault();
18688            if (am != null) {
18689                final long token = Binder.clearCallingIdentity();
18690                try {
18691                    am.killProcessesBelowForeground("setPermissionEnforcement");
18692                } catch (RemoteException e) {
18693                } finally {
18694                    Binder.restoreCallingIdentity(token);
18695                }
18696            }
18697        } else {
18698            throw new IllegalArgumentException("No selective enforcement for " + permission);
18699        }
18700    }
18701
18702    @Override
18703    @Deprecated
18704    public boolean isPermissionEnforced(String permission) {
18705        return true;
18706    }
18707
18708    @Override
18709    public boolean isStorageLow() {
18710        final long token = Binder.clearCallingIdentity();
18711        try {
18712            final DeviceStorageMonitorInternal
18713                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18714            if (dsm != null) {
18715                return dsm.isMemoryLow();
18716            } else {
18717                return false;
18718            }
18719        } finally {
18720            Binder.restoreCallingIdentity(token);
18721        }
18722    }
18723
18724    @Override
18725    public IPackageInstaller getPackageInstaller() {
18726        return mInstallerService;
18727    }
18728
18729    private boolean userNeedsBadging(int userId) {
18730        int index = mUserNeedsBadging.indexOfKey(userId);
18731        if (index < 0) {
18732            final UserInfo userInfo;
18733            final long token = Binder.clearCallingIdentity();
18734            try {
18735                userInfo = sUserManager.getUserInfo(userId);
18736            } finally {
18737                Binder.restoreCallingIdentity(token);
18738            }
18739            final boolean b;
18740            if (userInfo != null && userInfo.isManagedProfile()) {
18741                b = true;
18742            } else {
18743                b = false;
18744            }
18745            mUserNeedsBadging.put(userId, b);
18746            return b;
18747        }
18748        return mUserNeedsBadging.valueAt(index);
18749    }
18750
18751    @Override
18752    public KeySet getKeySetByAlias(String packageName, String alias) {
18753        if (packageName == null || alias == null) {
18754            return null;
18755        }
18756        synchronized(mPackages) {
18757            final PackageParser.Package pkg = mPackages.get(packageName);
18758            if (pkg == null) {
18759                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18760                throw new IllegalArgumentException("Unknown package: " + packageName);
18761            }
18762            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18763            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18764        }
18765    }
18766
18767    @Override
18768    public KeySet getSigningKeySet(String packageName) {
18769        if (packageName == null) {
18770            return null;
18771        }
18772        synchronized(mPackages) {
18773            final PackageParser.Package pkg = mPackages.get(packageName);
18774            if (pkg == null) {
18775                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18776                throw new IllegalArgumentException("Unknown package: " + packageName);
18777            }
18778            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18779                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18780                throw new SecurityException("May not access signing KeySet of other apps.");
18781            }
18782            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18783            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18784        }
18785    }
18786
18787    @Override
18788    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18789        if (packageName == null || ks == null) {
18790            return false;
18791        }
18792        synchronized(mPackages) {
18793            final PackageParser.Package pkg = mPackages.get(packageName);
18794            if (pkg == null) {
18795                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18796                throw new IllegalArgumentException("Unknown package: " + packageName);
18797            }
18798            IBinder ksh = ks.getToken();
18799            if (ksh instanceof KeySetHandle) {
18800                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18801                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18802            }
18803            return false;
18804        }
18805    }
18806
18807    @Override
18808    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18809        if (packageName == null || ks == null) {
18810            return false;
18811        }
18812        synchronized(mPackages) {
18813            final PackageParser.Package pkg = mPackages.get(packageName);
18814            if (pkg == null) {
18815                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18816                throw new IllegalArgumentException("Unknown package: " + packageName);
18817            }
18818            IBinder ksh = ks.getToken();
18819            if (ksh instanceof KeySetHandle) {
18820                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18821                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18822            }
18823            return false;
18824        }
18825    }
18826
18827    private void deletePackageIfUnusedLPr(final String packageName) {
18828        PackageSetting ps = mSettings.mPackages.get(packageName);
18829        if (ps == null) {
18830            return;
18831        }
18832        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18833            // TODO Implement atomic delete if package is unused
18834            // It is currently possible that the package will be deleted even if it is installed
18835            // after this method returns.
18836            mHandler.post(new Runnable() {
18837                public void run() {
18838                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18839                }
18840            });
18841        }
18842    }
18843
18844    /**
18845     * Check and throw if the given before/after packages would be considered a
18846     * downgrade.
18847     */
18848    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18849            throws PackageManagerException {
18850        if (after.versionCode < before.mVersionCode) {
18851            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18852                    "Update version code " + after.versionCode + " is older than current "
18853                    + before.mVersionCode);
18854        } else if (after.versionCode == before.mVersionCode) {
18855            if (after.baseRevisionCode < before.baseRevisionCode) {
18856                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18857                        "Update base revision code " + after.baseRevisionCode
18858                        + " is older than current " + before.baseRevisionCode);
18859            }
18860
18861            if (!ArrayUtils.isEmpty(after.splitNames)) {
18862                for (int i = 0; i < after.splitNames.length; i++) {
18863                    final String splitName = after.splitNames[i];
18864                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18865                    if (j != -1) {
18866                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18867                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18868                                    "Update split " + splitName + " revision code "
18869                                    + after.splitRevisionCodes[i] + " is older than current "
18870                                    + before.splitRevisionCodes[j]);
18871                        }
18872                    }
18873                }
18874            }
18875        }
18876    }
18877
18878    private static class MoveCallbacks extends Handler {
18879        private static final int MSG_CREATED = 1;
18880        private static final int MSG_STATUS_CHANGED = 2;
18881
18882        private final RemoteCallbackList<IPackageMoveObserver>
18883                mCallbacks = new RemoteCallbackList<>();
18884
18885        private final SparseIntArray mLastStatus = new SparseIntArray();
18886
18887        public MoveCallbacks(Looper looper) {
18888            super(looper);
18889        }
18890
18891        public void register(IPackageMoveObserver callback) {
18892            mCallbacks.register(callback);
18893        }
18894
18895        public void unregister(IPackageMoveObserver callback) {
18896            mCallbacks.unregister(callback);
18897        }
18898
18899        @Override
18900        public void handleMessage(Message msg) {
18901            final SomeArgs args = (SomeArgs) msg.obj;
18902            final int n = mCallbacks.beginBroadcast();
18903            for (int i = 0; i < n; i++) {
18904                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18905                try {
18906                    invokeCallback(callback, msg.what, args);
18907                } catch (RemoteException ignored) {
18908                }
18909            }
18910            mCallbacks.finishBroadcast();
18911            args.recycle();
18912        }
18913
18914        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18915                throws RemoteException {
18916            switch (what) {
18917                case MSG_CREATED: {
18918                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18919                    break;
18920                }
18921                case MSG_STATUS_CHANGED: {
18922                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18923                    break;
18924                }
18925            }
18926        }
18927
18928        private void notifyCreated(int moveId, Bundle extras) {
18929            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18930
18931            final SomeArgs args = SomeArgs.obtain();
18932            args.argi1 = moveId;
18933            args.arg2 = extras;
18934            obtainMessage(MSG_CREATED, args).sendToTarget();
18935        }
18936
18937        private void notifyStatusChanged(int moveId, int status) {
18938            notifyStatusChanged(moveId, status, -1);
18939        }
18940
18941        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18942            Slog.v(TAG, "Move " + moveId + " status " + status);
18943
18944            final SomeArgs args = SomeArgs.obtain();
18945            args.argi1 = moveId;
18946            args.argi2 = status;
18947            args.arg3 = estMillis;
18948            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18949
18950            synchronized (mLastStatus) {
18951                mLastStatus.put(moveId, status);
18952            }
18953        }
18954    }
18955
18956    private final static class OnPermissionChangeListeners extends Handler {
18957        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18958
18959        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18960                new RemoteCallbackList<>();
18961
18962        public OnPermissionChangeListeners(Looper looper) {
18963            super(looper);
18964        }
18965
18966        @Override
18967        public void handleMessage(Message msg) {
18968            switch (msg.what) {
18969                case MSG_ON_PERMISSIONS_CHANGED: {
18970                    final int uid = msg.arg1;
18971                    handleOnPermissionsChanged(uid);
18972                } break;
18973            }
18974        }
18975
18976        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18977            mPermissionListeners.register(listener);
18978
18979        }
18980
18981        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18982            mPermissionListeners.unregister(listener);
18983        }
18984
18985        public void onPermissionsChanged(int uid) {
18986            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18987                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18988            }
18989        }
18990
18991        private void handleOnPermissionsChanged(int uid) {
18992            final int count = mPermissionListeners.beginBroadcast();
18993            try {
18994                for (int i = 0; i < count; i++) {
18995                    IOnPermissionsChangeListener callback = mPermissionListeners
18996                            .getBroadcastItem(i);
18997                    try {
18998                        callback.onPermissionsChanged(uid);
18999                    } catch (RemoteException e) {
19000                        Log.e(TAG, "Permission listener is dead", e);
19001                    }
19002                }
19003            } finally {
19004                mPermissionListeners.finishBroadcast();
19005            }
19006        }
19007    }
19008
19009    private class PackageManagerInternalImpl extends PackageManagerInternal {
19010        @Override
19011        public void setLocationPackagesProvider(PackagesProvider provider) {
19012            synchronized (mPackages) {
19013                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19014            }
19015        }
19016
19017        @Override
19018        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19019            synchronized (mPackages) {
19020                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19021            }
19022        }
19023
19024        @Override
19025        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19026            synchronized (mPackages) {
19027                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19028            }
19029        }
19030
19031        @Override
19032        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19033            synchronized (mPackages) {
19034                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19035            }
19036        }
19037
19038        @Override
19039        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19040            synchronized (mPackages) {
19041                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19042            }
19043        }
19044
19045        @Override
19046        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19047            synchronized (mPackages) {
19048                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19049            }
19050        }
19051
19052        @Override
19053        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19054            synchronized (mPackages) {
19055                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19056                        packageName, userId);
19057            }
19058        }
19059
19060        @Override
19061        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19062            synchronized (mPackages) {
19063                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19064                        packageName, userId);
19065            }
19066        }
19067
19068        @Override
19069        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19070            synchronized (mPackages) {
19071                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19072                        packageName, userId);
19073            }
19074        }
19075
19076        @Override
19077        public void setKeepUninstalledPackages(final List<String> packageList) {
19078            Preconditions.checkNotNull(packageList);
19079            List<String> removedFromList = null;
19080            synchronized (mPackages) {
19081                if (mKeepUninstalledPackages != null) {
19082                    final int packagesCount = mKeepUninstalledPackages.size();
19083                    for (int i = 0; i < packagesCount; i++) {
19084                        String oldPackage = mKeepUninstalledPackages.get(i);
19085                        if (packageList != null && packageList.contains(oldPackage)) {
19086                            continue;
19087                        }
19088                        if (removedFromList == null) {
19089                            removedFromList = new ArrayList<>();
19090                        }
19091                        removedFromList.add(oldPackage);
19092                    }
19093                }
19094                mKeepUninstalledPackages = new ArrayList<>(packageList);
19095                if (removedFromList != null) {
19096                    final int removedCount = removedFromList.size();
19097                    for (int i = 0; i < removedCount; i++) {
19098                        deletePackageIfUnusedLPr(removedFromList.get(i));
19099                    }
19100                }
19101            }
19102        }
19103
19104        @Override
19105        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19106            synchronized (mPackages) {
19107                // If we do not support permission review, done.
19108                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19109                    return false;
19110                }
19111
19112                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19113                if (packageSetting == null) {
19114                    return false;
19115                }
19116
19117                // Permission review applies only to apps not supporting the new permission model.
19118                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19119                    return false;
19120                }
19121
19122                // Legacy apps have the permission and get user consent on launch.
19123                PermissionsState permissionsState = packageSetting.getPermissionsState();
19124                return permissionsState.isPermissionReviewRequired(userId);
19125            }
19126        }
19127    }
19128
19129    @Override
19130    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19131        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19132        synchronized (mPackages) {
19133            final long identity = Binder.clearCallingIdentity();
19134            try {
19135                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19136                        packageNames, userId);
19137            } finally {
19138                Binder.restoreCallingIdentity(identity);
19139            }
19140        }
19141    }
19142
19143    private static void enforceSystemOrPhoneCaller(String tag) {
19144        int callingUid = Binder.getCallingUid();
19145        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19146            throw new SecurityException(
19147                    "Cannot call " + tag + " from UID " + callingUid);
19148        }
19149    }
19150
19151    boolean isHistoricalPackageUsageAvailable() {
19152        return mPackageUsage.isHistoricalPackageUsageAvailable();
19153    }
19154
19155    /**
19156     * Return a <b>copy</b> of the collection of packages known to the package manager.
19157     * @return A copy of the values of mPackages.
19158     */
19159    Collection<PackageParser.Package> getPackages() {
19160        synchronized (mPackages) {
19161            return new ArrayList<>(mPackages.values());
19162        }
19163    }
19164}
19165