PackageManagerService.java revision d7b1f41109abee60ec8529369a85d84300b1d678
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_AND_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
72import static android.content.pm.PackageManager.PERMISSION_DENIED;
73import static android.content.pm.PackageManager.PERMISSION_GRANTED;
74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
75import static android.content.pm.PackageParser.isApkFile;
76import static android.os.Process.PACKAGE_INFO_GID;
77import static android.os.Process.SYSTEM_UID;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
96
97import android.Manifest;
98import android.annotation.NonNull;
99import android.annotation.Nullable;
100import android.app.ActivityManager;
101import android.app.ActivityManagerNative;
102import android.app.AppGlobals;
103import android.app.IActivityManager;
104import android.app.admin.IDevicePolicyManager;
105import android.app.backup.IBackupManager;
106import android.content.BroadcastReceiver;
107import android.content.ComponentName;
108import android.content.Context;
109import android.content.IIntentReceiver;
110import android.content.Intent;
111import android.content.IntentFilter;
112import android.content.IntentSender;
113import android.content.IntentSender.SendIntentException;
114import android.content.ServiceConnection;
115import android.content.pm.ActivityInfo;
116import android.content.pm.ApplicationInfo;
117import android.content.pm.AppsQueryHelper;
118import android.content.pm.ComponentInfo;
119import android.content.pm.EphemeralApplicationInfo;
120import android.content.pm.EphemeralResolveInfo;
121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
122import android.content.pm.FeatureInfo;
123import android.content.pm.IOnPermissionsChangeListener;
124import android.content.pm.IPackageDataObserver;
125import android.content.pm.IPackageDeleteObserver;
126import android.content.pm.IPackageDeleteObserver2;
127import android.content.pm.IPackageInstallObserver2;
128import android.content.pm.IPackageInstaller;
129import android.content.pm.IPackageManager;
130import android.content.pm.IPackageMoveObserver;
131import android.content.pm.IPackageStatsObserver;
132import android.content.pm.InstrumentationInfo;
133import android.content.pm.IntentFilterVerificationInfo;
134import android.content.pm.KeySet;
135import android.content.pm.PackageCleanItem;
136import android.content.pm.PackageInfo;
137import android.content.pm.PackageInfoLite;
138import android.content.pm.PackageInstaller;
139import android.content.pm.PackageManager;
140import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
141import android.content.pm.PackageManagerInternal;
142import android.content.pm.PackageParser;
143import android.content.pm.PackageParser.ActivityIntentInfo;
144import android.content.pm.PackageParser.Package;
145import android.content.pm.PackageParser.PackageLite;
146import android.content.pm.PackageParser.PackageParserException;
147import android.content.pm.PackageStats;
148import android.content.pm.PackageUserState;
149import android.content.pm.ParceledListSlice;
150import android.content.pm.PermissionGroupInfo;
151import android.content.pm.PermissionInfo;
152import android.content.pm.ProviderInfo;
153import android.content.pm.ResolveInfo;
154import android.content.pm.ServiceInfo;
155import android.content.pm.Signature;
156import android.content.pm.UserInfo;
157import android.content.pm.VerificationParams;
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.Process;
178import android.os.RemoteCallbackList;
179import android.os.RemoteException;
180import android.os.ResultReceiver;
181import android.os.SELinux;
182import android.os.ServiceManager;
183import android.os.SystemClock;
184import android.os.SystemProperties;
185import android.os.Trace;
186import android.os.UserHandle;
187import android.os.UserManager;
188import android.os.storage.IMountService;
189import android.os.storage.MountServiceInternal;
190import android.os.storage.StorageEventListener;
191import android.os.storage.StorageManager;
192import android.os.storage.VolumeInfo;
193import android.os.storage.VolumeRecord;
194import android.security.KeyStore;
195import android.security.SystemKeyStore;
196import android.system.ErrnoException;
197import android.system.Os;
198import android.text.TextUtils;
199import android.text.format.DateUtils;
200import android.util.ArrayMap;
201import android.util.ArraySet;
202import android.util.AtomicFile;
203import android.util.DisplayMetrics;
204import android.util.EventLog;
205import android.util.ExceptionUtils;
206import android.util.Log;
207import android.util.LogPrinter;
208import android.util.MathUtils;
209import android.util.PrintStreamPrinter;
210import android.util.Slog;
211import android.util.SparseArray;
212import android.util.SparseBooleanArray;
213import android.util.SparseIntArray;
214import android.util.Xml;
215import android.view.Display;
216
217import com.android.internal.R;
218import com.android.internal.annotations.GuardedBy;
219import com.android.internal.app.IMediaContainerService;
220import com.android.internal.app.ResolverActivity;
221import com.android.internal.content.NativeLibraryHelper;
222import com.android.internal.content.PackageHelper;
223import com.android.internal.os.IParcelFileDescriptorFactory;
224import com.android.internal.os.InstallerConnection.InstallerException;
225import com.android.internal.os.SomeArgs;
226import com.android.internal.os.Zygote;
227import com.android.internal.util.ArrayUtils;
228import com.android.internal.util.FastPrintWriter;
229import com.android.internal.util.FastXmlSerializer;
230import com.android.internal.util.IndentingPrintWriter;
231import com.android.internal.util.Preconditions;
232import com.android.internal.util.XmlUtils;
233import com.android.server.EventLogTags;
234import com.android.server.FgThread;
235import com.android.server.IntentResolver;
236import com.android.server.LocalServices;
237import com.android.server.ServiceThread;
238import com.android.server.SystemConfig;
239import com.android.server.Watchdog;
240import com.android.server.pm.PermissionsState.PermissionState;
241import com.android.server.pm.Settings.DatabaseVersion;
242import com.android.server.pm.Settings.VersionInfo;
243import com.android.server.storage.DeviceStorageMonitorInternal;
244
245import dalvik.system.DexFile;
246import dalvik.system.VMRuntime;
247
248import libcore.io.IoUtils;
249import libcore.util.EmptyArray;
250
251import org.xmlpull.v1.XmlPullParser;
252import org.xmlpull.v1.XmlPullParserException;
253import org.xmlpull.v1.XmlSerializer;
254
255import java.io.BufferedInputStream;
256import java.io.BufferedOutputStream;
257import java.io.BufferedReader;
258import java.io.ByteArrayInputStream;
259import java.io.ByteArrayOutputStream;
260import java.io.File;
261import java.io.FileDescriptor;
262import java.io.FileNotFoundException;
263import java.io.FileOutputStream;
264import java.io.FileReader;
265import java.io.FilenameFilter;
266import java.io.IOException;
267import java.io.InputStream;
268import java.io.PrintStream;
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 boolean mUseJitProfiles =
643            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
644
645    private static class IFVerificationParams {
646        PackageParser.Package pkg;
647        boolean replacing;
648        int userId;
649        int verifierUid;
650
651        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
652                int _userId, int _verifierUid) {
653            pkg = _pkg;
654            replacing = _replacing;
655            userId = _userId;
656            replacing = _replacing;
657            verifierUid = _verifierUid;
658        }
659    }
660
661    private interface IntentFilterVerifier<T extends IntentFilter> {
662        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
663                                               T filter, String packageName);
664        void startVerifications(int userId);
665        void receiveVerificationResponse(int verificationId);
666    }
667
668    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
669        private Context mContext;
670        private ComponentName mIntentFilterVerifierComponent;
671        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
672
673        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
674            mContext = context;
675            mIntentFilterVerifierComponent = verifierComponent;
676        }
677
678        private String getDefaultScheme() {
679            return IntentFilter.SCHEME_HTTPS;
680        }
681
682        @Override
683        public void startVerifications(int userId) {
684            // Launch verifications requests
685            int count = mCurrentIntentFilterVerifications.size();
686            for (int n=0; n<count; n++) {
687                int verificationId = mCurrentIntentFilterVerifications.get(n);
688                final IntentFilterVerificationState ivs =
689                        mIntentFilterVerificationStates.get(verificationId);
690
691                String packageName = ivs.getPackageName();
692
693                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
694                final int filterCount = filters.size();
695                ArraySet<String> domainsSet = new ArraySet<>();
696                for (int m=0; m<filterCount; m++) {
697                    PackageParser.ActivityIntentInfo filter = filters.get(m);
698                    domainsSet.addAll(filter.getHostsList());
699                }
700                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
701                synchronized (mPackages) {
702                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
703                            packageName, domainsList) != null) {
704                        scheduleWriteSettingsLocked();
705                    }
706                }
707                sendVerificationRequest(userId, verificationId, ivs);
708            }
709            mCurrentIntentFilterVerifications.clear();
710        }
711
712        private void sendVerificationRequest(int userId, int verificationId,
713                IntentFilterVerificationState ivs) {
714
715            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
718                    verificationId);
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
721                    getDefaultScheme());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
724                    ivs.getHostsString());
725            verificationIntent.putExtra(
726                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
727                    ivs.getPackageName());
728            verificationIntent.setComponent(mIntentFilterVerifierComponent);
729            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
730
731            UserHandle user = new UserHandle(userId);
732            mContext.sendBroadcastAsUser(verificationIntent, user);
733            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
734                    "Sending IntentFilter verification broadcast");
735        }
736
737        public void receiveVerificationResponse(int verificationId) {
738            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
739
740            final boolean verified = ivs.isVerified();
741
742            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
743            final int count = filters.size();
744            if (DEBUG_DOMAIN_VERIFICATION) {
745                Slog.i(TAG, "Received verification response " + verificationId
746                        + " for " + count + " filters, verified=" + verified);
747            }
748            for (int n=0; n<count; n++) {
749                PackageParser.ActivityIntentInfo filter = filters.get(n);
750                filter.setVerified(verified);
751
752                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
753                        + " verified with result:" + verified + " and hosts:"
754                        + ivs.getHostsString());
755            }
756
757            mIntentFilterVerificationStates.remove(verificationId);
758
759            final String packageName = ivs.getPackageName();
760            IntentFilterVerificationInfo ivi = null;
761
762            synchronized (mPackages) {
763                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
764            }
765            if (ivi == null) {
766                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
767                        + verificationId + " packageName:" + packageName);
768                return;
769            }
770            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
771                    "Updating IntentFilterVerificationInfo for package " + packageName
772                            +" verificationId:" + verificationId);
773
774            synchronized (mPackages) {
775                if (verified) {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
777                } else {
778                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
779                }
780                scheduleWriteSettingsLocked();
781
782                final int userId = ivs.getUserId();
783                if (userId != UserHandle.USER_ALL) {
784                    final int userStatus =
785                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
786
787                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
788                    boolean needUpdate = false;
789
790                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
791                    // already been set by the User thru the Disambiguation dialog
792                    switch (userStatus) {
793                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
794                            if (verified) {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
796                            } else {
797                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
798                            }
799                            needUpdate = true;
800                            break;
801
802                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
803                            if (verified) {
804                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
805                                needUpdate = true;
806                            }
807                            break;
808
809                        default:
810                            // Nothing to do
811                    }
812
813                    if (needUpdate) {
814                        mSettings.updateIntentFilterVerificationStatusLPw(
815                                packageName, updatedStatus, userId);
816                        scheduleWritePackageRestrictionsLocked(userId);
817                    }
818                }
819            }
820        }
821
822        @Override
823        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
824                    ActivityIntentInfo filter, String packageName) {
825            if (!hasValidDomains(filter)) {
826                return false;
827            }
828            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
829            if (ivs == null) {
830                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
831                        packageName);
832            }
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
835            }
836            ivs.addFilter(filter);
837            return true;
838        }
839
840        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
841                int userId, int verificationId, String packageName) {
842            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
843                    verifierUid, userId, packageName);
844            ivs.setPendingState();
845            synchronized (mPackages) {
846                mIntentFilterVerificationStates.append(verificationId, ivs);
847                mCurrentIntentFilterVerifications.add(verificationId);
848            }
849            return ivs;
850        }
851    }
852
853    private static boolean hasValidDomains(ActivityIntentInfo filter) {
854        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
855                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
856                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
857    }
858
859    // Set of pending broadcasts for aggregating enable/disable of components.
860    static class PendingPackageBroadcasts {
861        // for each user id, a map of <package name -> components within that package>
862        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
863
864        public PendingPackageBroadcasts() {
865            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
866        }
867
868        public ArrayList<String> get(int userId, String packageName) {
869            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
870            return packages.get(packageName);
871        }
872
873        public void put(int userId, String packageName, ArrayList<String> components) {
874            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
875            packages.put(packageName, components);
876        }
877
878        public void remove(int userId, String packageName) {
879            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
880            if (packages != null) {
881                packages.remove(packageName);
882            }
883        }
884
885        public void remove(int userId) {
886            mUidMap.remove(userId);
887        }
888
889        public int userIdCount() {
890            return mUidMap.size();
891        }
892
893        public int userIdAt(int n) {
894            return mUidMap.keyAt(n);
895        }
896
897        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
898            return mUidMap.get(userId);
899        }
900
901        public int size() {
902            // total number of pending broadcast entries across all userIds
903            int num = 0;
904            for (int i = 0; i< mUidMap.size(); i++) {
905                num += mUidMap.valueAt(i).size();
906            }
907            return num;
908        }
909
910        public void clear() {
911            mUidMap.clear();
912        }
913
914        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
915            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
916            if (map == null) {
917                map = new ArrayMap<String, ArrayList<String>>();
918                mUidMap.put(userId, map);
919            }
920            return map;
921        }
922    }
923    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
924
925    // Service Connection to remote media container service to copy
926    // package uri's from external media onto secure containers
927    // or internal storage.
928    private IMediaContainerService mContainerService = null;
929
930    static final int SEND_PENDING_BROADCAST = 1;
931    static final int MCS_BOUND = 3;
932    static final int END_COPY = 4;
933    static final int INIT_COPY = 5;
934    static final int MCS_UNBIND = 6;
935    static final int START_CLEANING_PACKAGE = 7;
936    static final int FIND_INSTALL_LOC = 8;
937    static final int POST_INSTALL = 9;
938    static final int MCS_RECONNECT = 10;
939    static final int MCS_GIVE_UP = 11;
940    static final int UPDATED_MEDIA_STATUS = 12;
941    static final int WRITE_SETTINGS = 13;
942    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
943    static final int PACKAGE_VERIFIED = 15;
944    static final int CHECK_PENDING_VERIFICATION = 16;
945    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
946    static final int INTENT_FILTER_VERIFIED = 18;
947
948    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
949
950    // Delay time in millisecs
951    static final int BROADCAST_DELAY = 10 * 1000;
952
953    static UserManagerService sUserManager;
954
955    // Stores a list of users whose package restrictions file needs to be updated
956    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
957
958    final private DefaultContainerConnection mDefContainerConn =
959            new DefaultContainerConnection();
960    class DefaultContainerConnection implements ServiceConnection {
961        public void onServiceConnected(ComponentName name, IBinder service) {
962            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
963            IMediaContainerService imcs =
964                IMediaContainerService.Stub.asInterface(service);
965            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
966        }
967
968        public void onServiceDisconnected(ComponentName name) {
969            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
970        }
971    }
972
973    // Recordkeeping of restore-after-install operations that are currently in flight
974    // between the Package Manager and the Backup Manager
975    static class PostInstallData {
976        public InstallArgs args;
977        public PackageInstalledInfo res;
978
979        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
980            args = _a;
981            res = _r;
982        }
983    }
984
985    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
986    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
987
988    // XML tags for backup/restore of various bits of state
989    private static final String TAG_PREFERRED_BACKUP = "pa";
990    private static final String TAG_DEFAULT_APPS = "da";
991    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
992
993    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
994    private static final String TAG_ALL_GRANTS = "rt-grants";
995    private static final String TAG_GRANT = "grant";
996    private static final String ATTR_PACKAGE_NAME = "pkg";
997
998    private static final String TAG_PERMISSION = "perm";
999    private static final String ATTR_PERMISSION_NAME = "name";
1000    private static final String ATTR_IS_GRANTED = "g";
1001    private static final String ATTR_USER_SET = "set";
1002    private static final String ATTR_USER_FIXED = "fixed";
1003    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1004
1005    // System/policy permission grants are not backed up
1006    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1007            FLAG_PERMISSION_POLICY_FIXED
1008            | FLAG_PERMISSION_SYSTEM_FIXED
1009            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1010
1011    // And we back up these user-adjusted states
1012    private static final int USER_RUNTIME_GRANT_MASK =
1013            FLAG_PERMISSION_USER_SET
1014            | FLAG_PERMISSION_USER_FIXED
1015            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1016
1017    final @Nullable String mRequiredVerifierPackage;
1018    final @Nullable String mRequiredInstallerPackage;
1019
1020    private final PackageUsage mPackageUsage = new PackageUsage();
1021
1022    private class PackageUsage {
1023        private static final int WRITE_INTERVAL
1024            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1025
1026        private final Object mFileLock = new Object();
1027        private final AtomicLong mLastWritten = new AtomicLong(0);
1028        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1029
1030        private boolean mIsHistoricalPackageUsageAvailable = true;
1031
1032        boolean isHistoricalPackageUsageAvailable() {
1033            return mIsHistoricalPackageUsageAvailable;
1034        }
1035
1036        void write(boolean force) {
1037            if (force) {
1038                writeInternal();
1039                return;
1040            }
1041            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1042                && !DEBUG_DEXOPT) {
1043                return;
1044            }
1045            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1046                new Thread("PackageUsage_DiskWriter") {
1047                    @Override
1048                    public void run() {
1049                        try {
1050                            writeInternal();
1051                        } finally {
1052                            mBackgroundWriteRunning.set(false);
1053                        }
1054                    }
1055                }.start();
1056            }
1057        }
1058
1059        private void writeInternal() {
1060            synchronized (mPackages) {
1061                synchronized (mFileLock) {
1062                    AtomicFile file = getFile();
1063                    FileOutputStream f = null;
1064                    try {
1065                        f = file.startWrite();
1066                        BufferedOutputStream out = new BufferedOutputStream(f);
1067                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1068                        StringBuilder sb = new StringBuilder();
1069                        for (PackageParser.Package pkg : mPackages.values()) {
1070                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1071                                continue;
1072                            }
1073                            sb.setLength(0);
1074                            sb.append(pkg.packageName);
1075                            sb.append(' ');
1076                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1077                            sb.append('\n');
1078                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1079                        }
1080                        out.flush();
1081                        file.finishWrite(f);
1082                    } catch (IOException e) {
1083                        if (f != null) {
1084                            file.failWrite(f);
1085                        }
1086                        Log.e(TAG, "Failed to write package usage times", e);
1087                    }
1088                }
1089            }
1090            mLastWritten.set(SystemClock.elapsedRealtime());
1091        }
1092
1093        void readLP() {
1094            synchronized (mFileLock) {
1095                AtomicFile file = getFile();
1096                BufferedInputStream in = null;
1097                try {
1098                    in = new BufferedInputStream(file.openRead());
1099                    StringBuffer sb = new StringBuffer();
1100                    while (true) {
1101                        String packageName = readToken(in, sb, ' ');
1102                        if (packageName == null) {
1103                            break;
1104                        }
1105                        String timeInMillisString = readToken(in, sb, '\n');
1106                        if (timeInMillisString == null) {
1107                            throw new IOException("Failed to find last usage time for package "
1108                                                  + packageName);
1109                        }
1110                        PackageParser.Package pkg = mPackages.get(packageName);
1111                        if (pkg == null) {
1112                            continue;
1113                        }
1114                        long timeInMillis;
1115                        try {
1116                            timeInMillis = Long.parseLong(timeInMillisString);
1117                        } catch (NumberFormatException e) {
1118                            throw new IOException("Failed to parse " + timeInMillisString
1119                                                  + " as a long.", e);
1120                        }
1121                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1122                    }
1123                } catch (FileNotFoundException expected) {
1124                    mIsHistoricalPackageUsageAvailable = false;
1125                } catch (IOException e) {
1126                    Log.w(TAG, "Failed to read package usage times", e);
1127                } finally {
1128                    IoUtils.closeQuietly(in);
1129                }
1130            }
1131            mLastWritten.set(SystemClock.elapsedRealtime());
1132        }
1133
1134        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1135                throws IOException {
1136            sb.setLength(0);
1137            while (true) {
1138                int ch = in.read();
1139                if (ch == -1) {
1140                    if (sb.length() == 0) {
1141                        return null;
1142                    }
1143                    throw new IOException("Unexpected EOF");
1144                }
1145                if (ch == endOfToken) {
1146                    return sb.toString();
1147                }
1148                sb.append((char)ch);
1149            }
1150        }
1151
1152        private AtomicFile getFile() {
1153            File dataDir = Environment.getDataDirectory();
1154            File systemDir = new File(dataDir, "system");
1155            File fname = new File(systemDir, "package-usage.list");
1156            return new AtomicFile(fname);
1157        }
1158    }
1159
1160    class PackageHandler extends Handler {
1161        private boolean mBound = false;
1162        final ArrayList<HandlerParams> mPendingInstalls =
1163            new ArrayList<HandlerParams>();
1164
1165        private boolean connectToService() {
1166            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1167                    " DefaultContainerService");
1168            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1170            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1171                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1172                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1173                mBound = true;
1174                return true;
1175            }
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1177            return false;
1178        }
1179
1180        private void disconnectService() {
1181            mContainerService = null;
1182            mBound = false;
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1184            mContext.unbindService(mDefContainerConn);
1185            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186        }
1187
1188        PackageHandler(Looper looper) {
1189            super(looper);
1190        }
1191
1192        public void handleMessage(Message msg) {
1193            try {
1194                doHandleMessage(msg);
1195            } finally {
1196                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1197            }
1198        }
1199
1200        void doHandleMessage(Message msg) {
1201            switch (msg.what) {
1202                case INIT_COPY: {
1203                    HandlerParams params = (HandlerParams) msg.obj;
1204                    int idx = mPendingInstalls.size();
1205                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1206                    // If a bind was already initiated we dont really
1207                    // need to do anything. The pending install
1208                    // will be processed later on.
1209                    if (!mBound) {
1210                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                System.identityHashCode(mHandler));
1212                        // If this is the only one pending we might
1213                        // have to bind to the service again.
1214                        if (!connectToService()) {
1215                            Slog.e(TAG, "Failed to bind to media container service");
1216                            params.serviceError();
1217                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1218                                    System.identityHashCode(mHandler));
1219                            if (params.traceMethod != null) {
1220                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1221                                        params.traceCookie);
1222                            }
1223                            return;
1224                        } else {
1225                            // Once we bind to the service, the first
1226                            // pending request will be processed.
1227                            mPendingInstalls.add(idx, params);
1228                        }
1229                    } else {
1230                        mPendingInstalls.add(idx, params);
1231                        // Already bound to the service. Just make
1232                        // sure we trigger off processing the first request.
1233                        if (idx == 0) {
1234                            mHandler.sendEmptyMessage(MCS_BOUND);
1235                        }
1236                    }
1237                    break;
1238                }
1239                case MCS_BOUND: {
1240                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1241                    if (msg.obj != null) {
1242                        mContainerService = (IMediaContainerService) msg.obj;
1243                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1244                                System.identityHashCode(mHandler));
1245                    }
1246                    if (mContainerService == null) {
1247                        if (!mBound) {
1248                            // Something seriously wrong since we are not bound and we are not
1249                            // waiting for connection. Bail out.
1250                            Slog.e(TAG, "Cannot bind to media container service");
1251                            for (HandlerParams params : mPendingInstalls) {
1252                                // Indicate service bind error
1253                                params.serviceError();
1254                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1255                                        System.identityHashCode(params));
1256                                if (params.traceMethod != null) {
1257                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1258                                            params.traceMethod, params.traceCookie);
1259                                }
1260                                return;
1261                            }
1262                            mPendingInstalls.clear();
1263                        } else {
1264                            Slog.w(TAG, "Waiting to connect to media container service");
1265                        }
1266                    } else if (mPendingInstalls.size() > 0) {
1267                        HandlerParams params = mPendingInstalls.get(0);
1268                        if (params != null) {
1269                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1270                                    System.identityHashCode(params));
1271                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1272                            if (params.startCopy()) {
1273                                // We are done...  look for more work or to
1274                                // go idle.
1275                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1276                                        "Checking for more work or unbind...");
1277                                // Delete pending install
1278                                if (mPendingInstalls.size() > 0) {
1279                                    mPendingInstalls.remove(0);
1280                                }
1281                                if (mPendingInstalls.size() == 0) {
1282                                    if (mBound) {
1283                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1284                                                "Posting delayed MCS_UNBIND");
1285                                        removeMessages(MCS_UNBIND);
1286                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1287                                        // Unbind after a little delay, to avoid
1288                                        // continual thrashing.
1289                                        sendMessageDelayed(ubmsg, 10000);
1290                                    }
1291                                } else {
1292                                    // There are more pending requests in queue.
1293                                    // Just post MCS_BOUND message to trigger processing
1294                                    // of next pending install.
1295                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1296                                            "Posting MCS_BOUND for next work");
1297                                    mHandler.sendEmptyMessage(MCS_BOUND);
1298                                }
1299                            }
1300                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1301                        }
1302                    } else {
1303                        // Should never happen ideally.
1304                        Slog.w(TAG, "Empty queue");
1305                    }
1306                    break;
1307                }
1308                case MCS_RECONNECT: {
1309                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1310                    if (mPendingInstalls.size() > 0) {
1311                        if (mBound) {
1312                            disconnectService();
1313                        }
1314                        if (!connectToService()) {
1315                            Slog.e(TAG, "Failed to bind to media container service");
1316                            for (HandlerParams params : mPendingInstalls) {
1317                                // Indicate service bind error
1318                                params.serviceError();
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                        System.identityHashCode(params));
1321                            }
1322                            mPendingInstalls.clear();
1323                        }
1324                    }
1325                    break;
1326                }
1327                case MCS_UNBIND: {
1328                    // If there is no actual work left, then time to unbind.
1329                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1330
1331                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1332                        if (mBound) {
1333                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1334
1335                            disconnectService();
1336                        }
1337                    } else if (mPendingInstalls.size() > 0) {
1338                        // There are more pending requests in queue.
1339                        // Just post MCS_BOUND message to trigger processing
1340                        // of next pending install.
1341                        mHandler.sendEmptyMessage(MCS_BOUND);
1342                    }
1343
1344                    break;
1345                }
1346                case MCS_GIVE_UP: {
1347                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1348                    HandlerParams params = mPendingInstalls.remove(0);
1349                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1350                            System.identityHashCode(params));
1351                    break;
1352                }
1353                case SEND_PENDING_BROADCAST: {
1354                    String packages[];
1355                    ArrayList<String> components[];
1356                    int size = 0;
1357                    int uids[];
1358                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1359                    synchronized (mPackages) {
1360                        if (mPendingBroadcasts == null) {
1361                            return;
1362                        }
1363                        size = mPendingBroadcasts.size();
1364                        if (size <= 0) {
1365                            // Nothing to be done. Just return
1366                            return;
1367                        }
1368                        packages = new String[size];
1369                        components = new ArrayList[size];
1370                        uids = new int[size];
1371                        int i = 0;  // filling out the above arrays
1372
1373                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1374                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1375                            Iterator<Map.Entry<String, ArrayList<String>>> it
1376                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1377                                            .entrySet().iterator();
1378                            while (it.hasNext() && i < size) {
1379                                Map.Entry<String, ArrayList<String>> ent = it.next();
1380                                packages[i] = ent.getKey();
1381                                components[i] = ent.getValue();
1382                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1383                                uids[i] = (ps != null)
1384                                        ? UserHandle.getUid(packageUserId, ps.appId)
1385                                        : -1;
1386                                i++;
1387                            }
1388                        }
1389                        size = i;
1390                        mPendingBroadcasts.clear();
1391                    }
1392                    // Send broadcasts
1393                    for (int i = 0; i < size; i++) {
1394                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1395                    }
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1397                    break;
1398                }
1399                case START_CLEANING_PACKAGE: {
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401                    final String packageName = (String)msg.obj;
1402                    final int userId = msg.arg1;
1403                    final boolean andCode = msg.arg2 != 0;
1404                    synchronized (mPackages) {
1405                        if (userId == UserHandle.USER_ALL) {
1406                            int[] users = sUserManager.getUserIds();
1407                            for (int user : users) {
1408                                mSettings.addPackageToCleanLPw(
1409                                        new PackageCleanItem(user, packageName, andCode));
1410                            }
1411                        } else {
1412                            mSettings.addPackageToCleanLPw(
1413                                    new PackageCleanItem(userId, packageName, andCode));
1414                        }
1415                    }
1416                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417                    startCleaningPackages();
1418                } break;
1419                case POST_INSTALL: {
1420                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1421
1422                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1423                    mRunningInstalls.delete(msg.arg1);
1424                    boolean deleteOld = false;
1425
1426                    if (data != null) {
1427                        InstallArgs args = data.args;
1428                        PackageInstalledInfo res = data.res;
1429
1430                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1431                            //TODO: Broadcast for child packages too
1432                            final String packageName = res.pkg.applicationInfo.packageName;
1433                            res.removedInfo.sendBroadcast(false, true, false);
1434                            Bundle extras = new Bundle(1);
1435                            extras.putInt(Intent.EXTRA_UID, res.uid);
1436
1437                            // Now that we successfully installed the package, grant runtime
1438                            // permissions if requested before broadcasting the install.
1439                            if ((args.installFlags
1440                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1441                                    && res.pkg.applicationInfo.targetSdkVersion
1442                                            >= Build.VERSION_CODES.M) {
1443                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1444                                        args.installGrantPermissions);
1445                            }
1446
1447                            synchronized (mPackages) {
1448                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1449                            }
1450
1451                            // Determine the set of users who are adding this
1452                            // package for the first time vs. those who are seeing
1453                            // an update.
1454                            int[] firstUsers;
1455                            int[] updateUsers = new int[0];
1456                            if (res.origUsers == null || res.origUsers.length == 0) {
1457                                firstUsers = res.newUsers;
1458                            } else {
1459                                firstUsers = new int[0];
1460                                for (int i=0; i<res.newUsers.length; i++) {
1461                                    int user = res.newUsers[i];
1462                                    boolean isNew = true;
1463                                    for (int j=0; j<res.origUsers.length; j++) {
1464                                        if (res.origUsers[j] == user) {
1465                                            isNew = false;
1466                                            break;
1467                                        }
1468                                    }
1469                                    if (isNew) {
1470                                        int[] newFirst = new int[firstUsers.length+1];
1471                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1472                                                firstUsers.length);
1473                                        newFirst[firstUsers.length] = user;
1474                                        firstUsers = newFirst;
1475                                    } else {
1476                                        int[] newUpdate = new int[updateUsers.length+1];
1477                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1478                                                updateUsers.length);
1479                                        newUpdate[updateUsers.length] = user;
1480                                        updateUsers = newUpdate;
1481                                    }
1482                                }
1483                            }
1484                            // don't broadcast for ephemeral installs/updates
1485                            final boolean isEphemeral = isEphemeral(res.pkg);
1486                            if (!isEphemeral) {
1487                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1488                                        extras, 0 /*flags*/, null /*targetPackage*/,
1489                                        null /*finishedReceiver*/, firstUsers);
1490                            }
1491                            final boolean update = res.removedInfo.removedPackage != null;
1492                            if (update) {
1493                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1494                            }
1495                            if (!isEphemeral) {
1496                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1497                                        extras, 0 /*flags*/, null /*targetPackage*/,
1498                                        null /*finishedReceiver*/, updateUsers);
1499                            }
1500                            if (update) {
1501                                if (!isEphemeral) {
1502                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1503                                            packageName, extras, 0 /*flags*/,
1504                                            null /*targetPackage*/, null /*finishedReceiver*/,
1505                                            updateUsers);
1506                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1507                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1508                                            packageName /*targetPackage*/,
1509                                            null /*finishedReceiver*/, updateUsers);
1510                                }
1511
1512                                // treat asec-hosted packages like removable media on upgrade
1513                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1514                                    if (DEBUG_INSTALL) {
1515                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1516                                                + " is ASEC-hosted -> AVAILABLE");
1517                                    }
1518                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1519                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1520                                    pkgList.add(packageName);
1521                                    sendResourcesChangedBroadcast(true, true,
1522                                            pkgList,uidArray, null);
1523                                }
1524                            }
1525                            if (res.removedInfo.args != null) {
1526                                // Remove the replaced package's older resources safely now
1527                                deleteOld = true;
1528                            }
1529
1530
1531                            // Work that needs to happen on first install within each user
1532                            if (firstUsers.length > 0) {
1533                                for (int userId : firstUsers) {
1534                                    synchronized (mPackages) {
1535                                        // If this app is a browser and it's newly-installed for
1536                                        // some users, clear any default-browser state in those
1537                                        // users.  The app's nature doesn't depend on the user,
1538                                        // so we can just check its browser nature in any user
1539                                        // and generalize.
1540                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1541                                            mSettings.setDefaultBrowserPackageNameLPw(
1542                                                    null, userId);
1543                                        }
1544
1545                                        // We may also need to apply pending (restored) runtime
1546                                        // permission grants within these users.
1547                                        mSettings.applyPendingPermissionGrantsLPw(
1548                                                packageName, userId);
1549                                    }
1550                                }
1551                            }
1552                            // Log current value of "unknown sources" setting
1553                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1554                                getUnknownSourcesSettings());
1555                        }
1556                        // Force a gc to clear up things
1557                        Runtime.getRuntime().gc();
1558                        // We delete after a gc for applications  on sdcard.
1559                        if (deleteOld) {
1560                            synchronized (mInstallLock) {
1561                                res.removedInfo.args.doPostDeleteLI(true);
1562                            }
1563                        }
1564                        if (args.observer != null) {
1565                            try {
1566                                Bundle extras = extrasForInstallResult(res);
1567                                args.observer.onPackageInstalled(res.name, res.returnCode,
1568                                        res.returnMsg, extras);
1569                            } catch (RemoteException e) {
1570                                Slog.i(TAG, "Observer no longer exists.");
1571                            }
1572                        }
1573                        if (args.traceMethod != null) {
1574                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1575                                    args.traceCookie);
1576                        }
1577                        return;
1578                    } else {
1579                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1580                    }
1581
1582                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1583                } break;
1584                case UPDATED_MEDIA_STATUS: {
1585                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1586                    boolean reportStatus = msg.arg1 == 1;
1587                    boolean doGc = msg.arg2 == 1;
1588                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1589                    if (doGc) {
1590                        // Force a gc to clear up stale containers.
1591                        Runtime.getRuntime().gc();
1592                    }
1593                    if (msg.obj != null) {
1594                        @SuppressWarnings("unchecked")
1595                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1596                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1597                        // Unload containers
1598                        unloadAllContainers(args);
1599                    }
1600                    if (reportStatus) {
1601                        try {
1602                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1603                            PackageHelper.getMountService().finishMediaUpdate();
1604                        } catch (RemoteException e) {
1605                            Log.e(TAG, "MountService not running?");
1606                        }
1607                    }
1608                } break;
1609                case WRITE_SETTINGS: {
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        removeMessages(WRITE_SETTINGS);
1613                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1614                        mSettings.writeLPr();
1615                        mDirtyUsers.clear();
1616                    }
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1618                } break;
1619                case WRITE_PACKAGE_RESTRICTIONS: {
1620                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1621                    synchronized (mPackages) {
1622                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1623                        for (int userId : mDirtyUsers) {
1624                            mSettings.writePackageRestrictionsLPr(userId);
1625                        }
1626                        mDirtyUsers.clear();
1627                    }
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1629                } break;
1630                case CHECK_PENDING_VERIFICATION: {
1631                    final int verificationId = msg.arg1;
1632                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1633
1634                    if ((state != null) && !state.timeoutExtended()) {
1635                        final InstallArgs args = state.getInstallArgs();
1636                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1637
1638                        Slog.i(TAG, "Verification timed out for " + originUri);
1639                        mPendingVerification.remove(verificationId);
1640
1641                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1642
1643                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1644                            Slog.i(TAG, "Continuing with installation of " + originUri);
1645                            state.setVerifierResponse(Binder.getCallingUid(),
1646                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1647                            broadcastPackageVerified(verificationId, originUri,
1648                                    PackageManager.VERIFICATION_ALLOW,
1649                                    state.getInstallArgs().getUser());
1650                            try {
1651                                ret = args.copyApk(mContainerService, true);
1652                            } catch (RemoteException e) {
1653                                Slog.e(TAG, "Could not contact the ContainerService");
1654                            }
1655                        } else {
1656                            broadcastPackageVerified(verificationId, originUri,
1657                                    PackageManager.VERIFICATION_REJECT,
1658                                    state.getInstallArgs().getUser());
1659                        }
1660
1661                        Trace.asyncTraceEnd(
1662                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1663
1664                        processPendingInstall(args, ret);
1665                        mHandler.sendEmptyMessage(MCS_UNBIND);
1666                    }
1667                    break;
1668                }
1669                case PACKAGE_VERIFIED: {
1670                    final int verificationId = msg.arg1;
1671
1672                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1673                    if (state == null) {
1674                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1675                        break;
1676                    }
1677
1678                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1679
1680                    state.setVerifierResponse(response.callerUid, response.code);
1681
1682                    if (state.isVerificationComplete()) {
1683                        mPendingVerification.remove(verificationId);
1684
1685                        final InstallArgs args = state.getInstallArgs();
1686                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1687
1688                        int ret;
1689                        if (state.isInstallAllowed()) {
1690                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1691                            broadcastPackageVerified(verificationId, originUri,
1692                                    response.code, state.getInstallArgs().getUser());
1693                            try {
1694                                ret = args.copyApk(mContainerService, true);
1695                            } catch (RemoteException e) {
1696                                Slog.e(TAG, "Could not contact the ContainerService");
1697                            }
1698                        } else {
1699                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1700                        }
1701
1702                        Trace.asyncTraceEnd(
1703                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1704
1705                        processPendingInstall(args, ret);
1706                        mHandler.sendEmptyMessage(MCS_UNBIND);
1707                    }
1708
1709                    break;
1710                }
1711                case START_INTENT_FILTER_VERIFICATIONS: {
1712                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1713                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1714                            params.replacing, params.pkg);
1715                    break;
1716                }
1717                case INTENT_FILTER_VERIFIED: {
1718                    final int verificationId = msg.arg1;
1719
1720                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1721                            verificationId);
1722                    if (state == null) {
1723                        Slog.w(TAG, "Invalid IntentFilter verification token "
1724                                + verificationId + " received");
1725                        break;
1726                    }
1727
1728                    final int userId = state.getUserId();
1729
1730                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1731                            "Processing IntentFilter verification with token:"
1732                            + verificationId + " and userId:" + userId);
1733
1734                    final IntentFilterVerificationResponse response =
1735                            (IntentFilterVerificationResponse) msg.obj;
1736
1737                    state.setVerifierResponse(response.callerUid, response.code);
1738
1739                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1740                            "IntentFilter verification with token:" + verificationId
1741                            + " and userId:" + userId
1742                            + " is settings verifier response with response code:"
1743                            + response.code);
1744
1745                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1746                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1747                                + response.getFailedDomainsString());
1748                    }
1749
1750                    if (state.isVerificationComplete()) {
1751                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1752                    } else {
1753                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1754                                "IntentFilter verification with token:" + verificationId
1755                                + " was not said to be complete");
1756                    }
1757
1758                    break;
1759                }
1760            }
1761        }
1762    }
1763
1764    private StorageEventListener mStorageListener = new StorageEventListener() {
1765        @Override
1766        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1767            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1768                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1769                    final String volumeUuid = vol.getFsUuid();
1770
1771                    // Clean up any users or apps that were removed or recreated
1772                    // while this volume was missing
1773                    reconcileUsers(volumeUuid);
1774                    reconcileApps(volumeUuid);
1775
1776                    // Clean up any install sessions that expired or were
1777                    // cancelled while this volume was missing
1778                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1779
1780                    loadPrivatePackages(vol);
1781
1782                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1783                    unloadPrivatePackages(vol);
1784                }
1785            }
1786
1787            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1788                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1789                    updateExternalMediaStatus(true, false);
1790                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1791                    updateExternalMediaStatus(false, false);
1792                }
1793            }
1794        }
1795
1796        @Override
1797        public void onVolumeForgotten(String fsUuid) {
1798            if (TextUtils.isEmpty(fsUuid)) {
1799                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1800                return;
1801            }
1802
1803            // Remove any apps installed on the forgotten volume
1804            synchronized (mPackages) {
1805                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1806                for (PackageSetting ps : packages) {
1807                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1808                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1809                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1810                }
1811
1812                mSettings.onVolumeForgotten(fsUuid);
1813                mSettings.writeLPr();
1814            }
1815        }
1816    };
1817
1818    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1819            String[] grantedPermissions) {
1820        if (userId >= UserHandle.USER_SYSTEM) {
1821            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1822        } else if (userId == UserHandle.USER_ALL) {
1823            final int[] userIds;
1824            synchronized (mPackages) {
1825                userIds = UserManagerService.getInstance().getUserIds();
1826            }
1827            for (int someUserId : userIds) {
1828                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1829            }
1830        }
1831
1832        // We could have touched GID membership, so flush out packages.list
1833        synchronized (mPackages) {
1834            mSettings.writePackageListLPr();
1835        }
1836    }
1837
1838    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1839            String[] grantedPermissions) {
1840        SettingBase sb = (SettingBase) pkg.mExtras;
1841        if (sb == null) {
1842            return;
1843        }
1844
1845        PermissionsState permissionsState = sb.getPermissionsState();
1846
1847        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1848                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1849
1850        synchronized (mPackages) {
1851            for (String permission : pkg.requestedPermissions) {
1852                BasePermission bp = mSettings.mPermissions.get(permission);
1853                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1854                        && (grantedPermissions == null
1855                               || ArrayUtils.contains(grantedPermissions, permission))) {
1856                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1857                    // Installer cannot change immutable permissions.
1858                    if ((flags & immutableFlags) == 0) {
1859                        grantRuntimePermission(pkg.packageName, permission, userId);
1860                    }
1861                }
1862            }
1863        }
1864    }
1865
1866    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1867        Bundle extras = null;
1868        switch (res.returnCode) {
1869            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1870                extras = new Bundle();
1871                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1872                        res.origPermission);
1873                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1874                        res.origPackage);
1875                break;
1876            }
1877            case PackageManager.INSTALL_SUCCEEDED: {
1878                extras = new Bundle();
1879                extras.putBoolean(Intent.EXTRA_REPLACING,
1880                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1881                break;
1882            }
1883        }
1884        return extras;
1885    }
1886
1887    void scheduleWriteSettingsLocked() {
1888        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1889            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1890        }
1891    }
1892
1893    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1894        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1895        scheduleWritePackageRestrictionsLocked(userId);
1896    }
1897
1898    void scheduleWritePackageRestrictionsLocked(int userId) {
1899        final int[] userIds = (userId == UserHandle.USER_ALL)
1900                ? sUserManager.getUserIds() : new int[]{userId};
1901        for (int nextUserId : userIds) {
1902            if (!sUserManager.exists(nextUserId)) return;
1903            mDirtyUsers.add(nextUserId);
1904            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1905                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1906            }
1907        }
1908    }
1909
1910    public static PackageManagerService main(Context context, Installer installer,
1911            boolean factoryTest, boolean onlyCore) {
1912        PackageManagerService m = new PackageManagerService(context, installer,
1913                factoryTest, onlyCore);
1914        m.enableSystemUserPackages();
1915        ServiceManager.addService("package", m);
1916        return m;
1917    }
1918
1919    private void enableSystemUserPackages() {
1920        if (!UserManager.isSplitSystemUser()) {
1921            return;
1922        }
1923        // For system user, enable apps based on the following conditions:
1924        // - app is whitelisted or belong to one of these groups:
1925        //   -- system app which has no launcher icons
1926        //   -- system app which has INTERACT_ACROSS_USERS permission
1927        //   -- system IME app
1928        // - app is not in the blacklist
1929        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1930        Set<String> enableApps = new ArraySet<>();
1931        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1932                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1933                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1934        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1935        enableApps.addAll(wlApps);
1936        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1937                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1938        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1939        enableApps.removeAll(blApps);
1940        Log.i(TAG, "Applications installed for system user: " + enableApps);
1941        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1942                UserHandle.SYSTEM);
1943        final int allAppsSize = allAps.size();
1944        synchronized (mPackages) {
1945            for (int i = 0; i < allAppsSize; i++) {
1946                String pName = allAps.get(i);
1947                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1948                // Should not happen, but we shouldn't be failing if it does
1949                if (pkgSetting == null) {
1950                    continue;
1951                }
1952                boolean install = enableApps.contains(pName);
1953                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1954                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1955                            + " for system user");
1956                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1957                }
1958            }
1959        }
1960    }
1961
1962    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1963        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1964                Context.DISPLAY_SERVICE);
1965        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1966    }
1967
1968    public PackageManagerService(Context context, Installer installer,
1969            boolean factoryTest, boolean onlyCore) {
1970        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1971                SystemClock.uptimeMillis());
1972
1973        if (mSdkVersion <= 0) {
1974            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1975        }
1976
1977        mContext = context;
1978        mFactoryTest = factoryTest;
1979        mOnlyCore = onlyCore;
1980        mMetrics = new DisplayMetrics();
1981        mSettings = new Settings(mPackages);
1982        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1983                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1984        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1985                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1986        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1987                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1988        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1989                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1990        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1991                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1992        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1993                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1994
1995        String separateProcesses = SystemProperties.get("debug.separate_processes");
1996        if (separateProcesses != null && separateProcesses.length() > 0) {
1997            if ("*".equals(separateProcesses)) {
1998                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1999                mSeparateProcesses = null;
2000                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2001            } else {
2002                mDefParseFlags = 0;
2003                mSeparateProcesses = separateProcesses.split(",");
2004                Slog.w(TAG, "Running with debug.separate_processes: "
2005                        + separateProcesses);
2006            }
2007        } else {
2008            mDefParseFlags = 0;
2009            mSeparateProcesses = null;
2010        }
2011
2012        mInstaller = installer;
2013        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2014                "*dexopt*");
2015        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2016
2017        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2018                FgThread.get().getLooper());
2019
2020        getDefaultDisplayMetrics(context, mMetrics);
2021
2022        SystemConfig systemConfig = SystemConfig.getInstance();
2023        mGlobalGids = systemConfig.getGlobalGids();
2024        mSystemPermissions = systemConfig.getSystemPermissions();
2025        mAvailableFeatures = systemConfig.getAvailableFeatures();
2026
2027        synchronized (mInstallLock) {
2028        // writer
2029        synchronized (mPackages) {
2030            mHandlerThread = new ServiceThread(TAG,
2031                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2032            mHandlerThread.start();
2033            mHandler = new PackageHandler(mHandlerThread.getLooper());
2034            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2035
2036            File dataDir = Environment.getDataDirectory();
2037            mAppInstallDir = new File(dataDir, "app");
2038            mAppLib32InstallDir = new File(dataDir, "app-lib");
2039            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2040            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2041            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2042
2043            sUserManager = new UserManagerService(context, this, mPackages);
2044
2045            // Propagate permission configuration in to package manager.
2046            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2047                    = systemConfig.getPermissions();
2048            for (int i=0; i<permConfig.size(); i++) {
2049                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2050                BasePermission bp = mSettings.mPermissions.get(perm.name);
2051                if (bp == null) {
2052                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2053                    mSettings.mPermissions.put(perm.name, bp);
2054                }
2055                if (perm.gids != null) {
2056                    bp.setGids(perm.gids, perm.perUser);
2057                }
2058            }
2059
2060            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2061            for (int i=0; i<libConfig.size(); i++) {
2062                mSharedLibraries.put(libConfig.keyAt(i),
2063                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2064            }
2065
2066            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2067
2068            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2069
2070            String customResolverActivity = Resources.getSystem().getString(
2071                    R.string.config_customResolverActivity);
2072            if (TextUtils.isEmpty(customResolverActivity)) {
2073                customResolverActivity = null;
2074            } else {
2075                mCustomResolverComponentName = ComponentName.unflattenFromString(
2076                        customResolverActivity);
2077            }
2078
2079            long startTime = SystemClock.uptimeMillis();
2080
2081            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2082                    startTime);
2083
2084            // Set flag to monitor and not change apk file paths when
2085            // scanning install directories.
2086            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2087
2088            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2089            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2090
2091            if (bootClassPath == null) {
2092                Slog.w(TAG, "No BOOTCLASSPATH found!");
2093            }
2094
2095            if (systemServerClassPath == null) {
2096                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2097            }
2098
2099            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2100            final String[] dexCodeInstructionSets =
2101                    getDexCodeInstructionSets(
2102                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2103
2104            /**
2105             * Ensure all external libraries have had dexopt run on them.
2106             */
2107            if (mSharedLibraries.size() > 0) {
2108                // NOTE: For now, we're compiling these system "shared libraries"
2109                // (and framework jars) into all available architectures. It's possible
2110                // to compile them only when we come across an app that uses them (there's
2111                // already logic for that in scanPackageLI) but that adds some complexity.
2112                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2113                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2114                        final String lib = libEntry.path;
2115                        if (lib == null) {
2116                            continue;
2117                        }
2118
2119                        try {
2120                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2121                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2122                                // Shared libraries do not have profiles so we perform a full
2123                                // AOT compilation.
2124                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2125                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2126                                        StorageManager.UUID_PRIVATE_INTERNAL,
2127                                        false /*useProfiles*/);
2128                            }
2129                        } catch (FileNotFoundException e) {
2130                            Slog.w(TAG, "Library not found: " + lib);
2131                        } catch (IOException | InstallerException e) {
2132                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2133                                    + e.getMessage());
2134                        }
2135                    }
2136                }
2137            }
2138
2139            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2140
2141            final VersionInfo ver = mSettings.getInternalVersion();
2142            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2143            // when upgrading from pre-M, promote system app permissions from install to runtime
2144            mPromoteSystemApps =
2145                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2146
2147            // save off the names of pre-existing system packages prior to scanning; we don't
2148            // want to automatically grant runtime permissions for new system apps
2149            if (mPromoteSystemApps) {
2150                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2151                while (pkgSettingIter.hasNext()) {
2152                    PackageSetting ps = pkgSettingIter.next();
2153                    if (isSystemApp(ps)) {
2154                        mExistingSystemPackages.add(ps.name);
2155                    }
2156                }
2157            }
2158
2159            // Collect vendor overlay packages.
2160            // (Do this before scanning any apps.)
2161            // For security and version matching reason, only consider
2162            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2163            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2164            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2165                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2166
2167            // Find base frameworks (resource packages without code).
2168            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2169                    | PackageParser.PARSE_IS_SYSTEM_DIR
2170                    | PackageParser.PARSE_IS_PRIVILEGED,
2171                    scanFlags | SCAN_NO_DEX, 0);
2172
2173            // Collected privileged system packages.
2174            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2175            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2176                    | PackageParser.PARSE_IS_SYSTEM_DIR
2177                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2178
2179            // Collect ordinary system packages.
2180            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2181            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2182                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2183
2184            // Collect all vendor packages.
2185            File vendorAppDir = new File("/vendor/app");
2186            try {
2187                vendorAppDir = vendorAppDir.getCanonicalFile();
2188            } catch (IOException e) {
2189                // failed to look up canonical path, continue with original one
2190            }
2191            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2192                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2193
2194            // Collect all OEM packages.
2195            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2196            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2197                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2198
2199            // Prune any system packages that no longer exist.
2200            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2201            if (!mOnlyCore) {
2202                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2203                while (psit.hasNext()) {
2204                    PackageSetting ps = psit.next();
2205
2206                    /*
2207                     * If this is not a system app, it can't be a
2208                     * disable system app.
2209                     */
2210                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2211                        continue;
2212                    }
2213
2214                    /*
2215                     * If the package is scanned, it's not erased.
2216                     */
2217                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2218                    if (scannedPkg != null) {
2219                        /*
2220                         * If the system app is both scanned and in the
2221                         * disabled packages list, then it must have been
2222                         * added via OTA. Remove it from the currently
2223                         * scanned package so the previously user-installed
2224                         * application can be scanned.
2225                         */
2226                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2227                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2228                                    + ps.name + "; removing system app.  Last known codePath="
2229                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2230                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2231                                    + scannedPkg.mVersionCode);
2232                            removePackageSettingLI(scannedPkg, true);
2233                            mExpectingBetter.put(ps.name, ps.codePath);
2234                        }
2235
2236                        continue;
2237                    }
2238
2239                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2240                        psit.remove();
2241                        logCriticalInfo(Log.WARN, "System package " + ps.name
2242                                + " no longer exists; wiping its data");
2243                        removeDataDirsLI(null, ps.name);
2244                    } else {
2245                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2246                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2247                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2248                        }
2249                    }
2250                }
2251            }
2252
2253            //look for any incomplete package installations
2254            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2255            //clean up list
2256            for(int i = 0; i < deletePkgsList.size(); i++) {
2257                //clean up here
2258                cleanupInstallFailedPackage(deletePkgsList.get(i));
2259            }
2260            //delete tmp files
2261            deleteTempPackageFiles();
2262
2263            // Remove any shared userIDs that have no associated packages
2264            mSettings.pruneSharedUsersLPw();
2265
2266            if (!mOnlyCore) {
2267                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2268                        SystemClock.uptimeMillis());
2269                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2270
2271                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2272                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2273
2274                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2275                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2276
2277                /**
2278                 * Remove disable package settings for any updated system
2279                 * apps that were removed via an OTA. If they're not a
2280                 * previously-updated app, remove them completely.
2281                 * Otherwise, just revoke their system-level permissions.
2282                 */
2283                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2284                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2285                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2286
2287                    String msg;
2288                    if (deletedPkg == null) {
2289                        msg = "Updated system package " + deletedAppName
2290                                + " no longer exists; wiping its data";
2291                        removeDataDirsLI(null, deletedAppName);
2292                    } else {
2293                        msg = "Updated system app + " + deletedAppName
2294                                + " no longer present; removing system privileges for "
2295                                + deletedAppName;
2296
2297                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2298
2299                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2300                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2301                    }
2302                    logCriticalInfo(Log.WARN, msg);
2303                }
2304
2305                /**
2306                 * Make sure all system apps that we expected to appear on
2307                 * the userdata partition actually showed up. If they never
2308                 * appeared, crawl back and revive the system version.
2309                 */
2310                for (int i = 0; i < mExpectingBetter.size(); i++) {
2311                    final String packageName = mExpectingBetter.keyAt(i);
2312                    if (!mPackages.containsKey(packageName)) {
2313                        final File scanFile = mExpectingBetter.valueAt(i);
2314
2315                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2316                                + " but never showed up; reverting to system");
2317
2318                        final int reparseFlags;
2319                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2320                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2321                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2322                                    | PackageParser.PARSE_IS_PRIVILEGED;
2323                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2324                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2325                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2326                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2327                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2328                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2329                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2330                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2331                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2332                        } else {
2333                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2334                            continue;
2335                        }
2336
2337                        mSettings.enableSystemPackageLPw(packageName);
2338
2339                        try {
2340                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2341                        } catch (PackageManagerException e) {
2342                            Slog.e(TAG, "Failed to parse original system package: "
2343                                    + e.getMessage());
2344                        }
2345                    }
2346                }
2347            }
2348            mExpectingBetter.clear();
2349
2350            // Now that we know all of the shared libraries, update all clients to have
2351            // the correct library paths.
2352            updateAllSharedLibrariesLPw();
2353
2354            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2355                // NOTE: We ignore potential failures here during a system scan (like
2356                // the rest of the commands above) because there's precious little we
2357                // can do about it. A settings error is reported, though.
2358                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2359                        false /* boot complete */);
2360            }
2361
2362            // Now that we know all the packages we are keeping,
2363            // read and update their last usage times.
2364            mPackageUsage.readLP();
2365
2366            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2367                    SystemClock.uptimeMillis());
2368            Slog.i(TAG, "Time to scan packages: "
2369                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2370                    + " seconds");
2371
2372            // If the platform SDK has changed since the last time we booted,
2373            // we need to re-grant app permission to catch any new ones that
2374            // appear.  This is really a hack, and means that apps can in some
2375            // cases get permissions that the user didn't initially explicitly
2376            // allow...  it would be nice to have some better way to handle
2377            // this situation.
2378            int updateFlags = UPDATE_PERMISSIONS_ALL;
2379            if (ver.sdkVersion != mSdkVersion) {
2380                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2381                        + mSdkVersion + "; regranting permissions for internal storage");
2382                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2383            }
2384            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2385            ver.sdkVersion = mSdkVersion;
2386
2387            // If this is the first boot or an update from pre-M, and it is a normal
2388            // boot, then we need to initialize the default preferred apps across
2389            // all defined users.
2390            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2391                for (UserInfo user : sUserManager.getUsers(true)) {
2392                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2393                    applyFactoryDefaultBrowserLPw(user.id);
2394                    primeDomainVerificationsLPw(user.id);
2395                }
2396            }
2397
2398            // Prepare storage for system user really early during boot,
2399            // since core system apps like SettingsProvider and SystemUI
2400            // can't wait for user to start
2401            final int storageFlags;
2402            if (StorageManager.isFileBasedEncryptionEnabled()) {
2403                storageFlags = StorageManager.FLAG_STORAGE_DE;
2404            } else {
2405                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2406            }
2407            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2408                    storageFlags);
2409
2410            if (!StorageManager.isFileBasedEncryptionEnabled()
2411                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2412                // When upgrading a non-FBE device, we might need to shuffle
2413                // around the default storage location of system apps
2414                final List<UserInfo> users = sUserManager.getUsers(true);
2415                for (PackageSetting ps : mSettings.mPackages.values()) {
2416                    if (ps.pkg == null || !ps.isSystem()) continue;
2417                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2418                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2419                    for (UserInfo user : users) {
2420                        if (ps.getInstalled(user.id)) {
2421                            try {
2422                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2423                                        ps.name, user.id, storageTarget);
2424                            } catch (InstallerException e) {
2425                                logCriticalInfo(Log.WARN,
2426                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2427                            }
2428                            // We may have just shuffled around app data
2429                            // directories, so prepare it one more time
2430                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2431                                    storageFlags, ps.pkg, false);
2432                        }
2433                    }
2434                }
2435            }
2436
2437            // If this is first boot after an OTA, and a normal boot, then
2438            // we need to clear code cache directories.
2439            if (mIsUpgrade && !onlyCore) {
2440                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2441                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2442                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2443                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2444                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2445                    }
2446                }
2447                ver.fingerprint = Build.FINGERPRINT;
2448            }
2449
2450            checkDefaultBrowser();
2451
2452            // clear only after permissions and other defaults have been updated
2453            mExistingSystemPackages.clear();
2454            mPromoteSystemApps = false;
2455
2456            // All the changes are done during package scanning.
2457            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2458
2459            // can downgrade to reader
2460            mSettings.writeLPr();
2461
2462            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2463                    SystemClock.uptimeMillis());
2464
2465            if (!mOnlyCore) {
2466                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2467                mRequiredInstallerPackage = getRequiredInstallerLPr();
2468                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2469                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2470                        mIntentFilterVerifierComponent);
2471            } else {
2472                mRequiredVerifierPackage = null;
2473                mRequiredInstallerPackage = null;
2474                mIntentFilterVerifierComponent = null;
2475                mIntentFilterVerifier = null;
2476            }
2477
2478            mInstallerService = new PackageInstallerService(context, this);
2479
2480            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2481            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2482            // both the installer and resolver must be present to enable ephemeral
2483            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2484                if (DEBUG_EPHEMERAL) {
2485                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2486                            + " installer:" + ephemeralInstallerComponent);
2487                }
2488                mEphemeralResolverComponent = ephemeralResolverComponent;
2489                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2490                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2491                mEphemeralResolverConnection =
2492                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2493            } else {
2494                if (DEBUG_EPHEMERAL) {
2495                    final String missingComponent =
2496                            (ephemeralResolverComponent == null)
2497                            ? (ephemeralInstallerComponent == null)
2498                                    ? "resolver and installer"
2499                                    : "resolver"
2500                            : "installer";
2501                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2502                }
2503                mEphemeralResolverComponent = null;
2504                mEphemeralInstallerComponent = null;
2505                mEphemeralResolverConnection = null;
2506            }
2507
2508            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2509        } // synchronized (mPackages)
2510        } // synchronized (mInstallLock)
2511
2512        // Now after opening every single application zip, make sure they
2513        // are all flushed.  Not really needed, but keeps things nice and
2514        // tidy.
2515        Runtime.getRuntime().gc();
2516
2517        // The initial scanning above does many calls into installd while
2518        // holding the mPackages lock, but we're mostly interested in yelling
2519        // once we have a booted system.
2520        mInstaller.setWarnIfHeld(mPackages);
2521
2522        // Expose private service for system components to use.
2523        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2524    }
2525
2526    @Override
2527    public boolean isFirstBoot() {
2528        return !mRestoredSettings;
2529    }
2530
2531    @Override
2532    public boolean isOnlyCoreApps() {
2533        return mOnlyCore;
2534    }
2535
2536    @Override
2537    public boolean isUpgrade() {
2538        return mIsUpgrade;
2539    }
2540
2541    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2542        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2543
2544        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2545                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2546        if (matches.size() == 1) {
2547            return matches.get(0).getComponentInfo().packageName;
2548        } else {
2549            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2550            return null;
2551        }
2552    }
2553
2554    private @NonNull String getRequiredInstallerLPr() {
2555        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2556        intent.addCategory(Intent.CATEGORY_DEFAULT);
2557        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2558
2559        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561        if (matches.size() == 1) {
2562            return matches.get(0).getComponentInfo().packageName;
2563        } else {
2564            throw new RuntimeException("There must be exactly one installer; found " + matches);
2565        }
2566    }
2567
2568    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2569        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2570
2571        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2572                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2573        ResolveInfo best = null;
2574        final int N = matches.size();
2575        for (int i = 0; i < N; i++) {
2576            final ResolveInfo cur = matches.get(i);
2577            final String packageName = cur.getComponentInfo().packageName;
2578            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2579                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2580                continue;
2581            }
2582
2583            if (best == null || cur.priority > best.priority) {
2584                best = cur;
2585            }
2586        }
2587
2588        if (best != null) {
2589            return best.getComponentInfo().getComponentName();
2590        } else {
2591            throw new RuntimeException("There must be at least one intent filter verifier");
2592        }
2593    }
2594
2595    private @Nullable ComponentName getEphemeralResolverLPr() {
2596        final String[] packageArray =
2597                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2598        if (packageArray.length == 0) {
2599            if (DEBUG_EPHEMERAL) {
2600                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2601            }
2602            return null;
2603        }
2604
2605        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2606        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2607                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2608
2609        final int N = resolvers.size();
2610        if (N == 0) {
2611            if (DEBUG_EPHEMERAL) {
2612                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2613            }
2614            return null;
2615        }
2616
2617        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2618        for (int i = 0; i < N; i++) {
2619            final ResolveInfo info = resolvers.get(i);
2620
2621            if (info.serviceInfo == null) {
2622                continue;
2623            }
2624
2625            final String packageName = info.serviceInfo.packageName;
2626            if (!possiblePackages.contains(packageName)) {
2627                if (DEBUG_EPHEMERAL) {
2628                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2629                            + " pkg: " + packageName + ", info:" + info);
2630                }
2631                continue;
2632            }
2633
2634            if (DEBUG_EPHEMERAL) {
2635                Slog.v(TAG, "Ephemeral resolver found;"
2636                        + " pkg: " + packageName + ", info:" + info);
2637            }
2638            return new ComponentName(packageName, info.serviceInfo.name);
2639        }
2640        if (DEBUG_EPHEMERAL) {
2641            Slog.v(TAG, "Ephemeral resolver NOT found");
2642        }
2643        return null;
2644    }
2645
2646    private @Nullable ComponentName getEphemeralInstallerLPr() {
2647        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2648        intent.addCategory(Intent.CATEGORY_DEFAULT);
2649        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2650
2651        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2652                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2653        if (matches.size() == 0) {
2654            return null;
2655        } else if (matches.size() == 1) {
2656            return matches.get(0).getComponentInfo().getComponentName();
2657        } else {
2658            throw new RuntimeException(
2659                    "There must be at most one ephemeral installer; found " + matches);
2660        }
2661    }
2662
2663    private void primeDomainVerificationsLPw(int userId) {
2664        if (DEBUG_DOMAIN_VERIFICATION) {
2665            Slog.d(TAG, "Priming domain verifications in user " + userId);
2666        }
2667
2668        SystemConfig systemConfig = SystemConfig.getInstance();
2669        ArraySet<String> packages = systemConfig.getLinkedApps();
2670        ArraySet<String> domains = new ArraySet<String>();
2671
2672        for (String packageName : packages) {
2673            PackageParser.Package pkg = mPackages.get(packageName);
2674            if (pkg != null) {
2675                if (!pkg.isSystemApp()) {
2676                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2677                    continue;
2678                }
2679
2680                domains.clear();
2681                for (PackageParser.Activity a : pkg.activities) {
2682                    for (ActivityIntentInfo filter : a.intents) {
2683                        if (hasValidDomains(filter)) {
2684                            domains.addAll(filter.getHostsList());
2685                        }
2686                    }
2687                }
2688
2689                if (domains.size() > 0) {
2690                    if (DEBUG_DOMAIN_VERIFICATION) {
2691                        Slog.v(TAG, "      + " + packageName);
2692                    }
2693                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2694                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2695                    // and then 'always' in the per-user state actually used for intent resolution.
2696                    final IntentFilterVerificationInfo ivi;
2697                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2698                            new ArrayList<String>(domains));
2699                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2700                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2701                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2702                } else {
2703                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2704                            + "' does not handle web links");
2705                }
2706            } else {
2707                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2708            }
2709        }
2710
2711        scheduleWritePackageRestrictionsLocked(userId);
2712        scheduleWriteSettingsLocked();
2713    }
2714
2715    private void applyFactoryDefaultBrowserLPw(int userId) {
2716        // The default browser app's package name is stored in a string resource,
2717        // with a product-specific overlay used for vendor customization.
2718        String browserPkg = mContext.getResources().getString(
2719                com.android.internal.R.string.default_browser);
2720        if (!TextUtils.isEmpty(browserPkg)) {
2721            // non-empty string => required to be a known package
2722            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2723            if (ps == null) {
2724                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2725                browserPkg = null;
2726            } else {
2727                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2728            }
2729        }
2730
2731        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2732        // default.  If there's more than one, just leave everything alone.
2733        if (browserPkg == null) {
2734            calculateDefaultBrowserLPw(userId);
2735        }
2736    }
2737
2738    private void calculateDefaultBrowserLPw(int userId) {
2739        List<String> allBrowsers = resolveAllBrowserApps(userId);
2740        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2741        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2742    }
2743
2744    private List<String> resolveAllBrowserApps(int userId) {
2745        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2746        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2747                PackageManager.MATCH_ALL, userId);
2748
2749        final int count = list.size();
2750        List<String> result = new ArrayList<String>(count);
2751        for (int i=0; i<count; i++) {
2752            ResolveInfo info = list.get(i);
2753            if (info.activityInfo == null
2754                    || !info.handleAllWebDataURI
2755                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2756                    || result.contains(info.activityInfo.packageName)) {
2757                continue;
2758            }
2759            result.add(info.activityInfo.packageName);
2760        }
2761
2762        return result;
2763    }
2764
2765    private boolean packageIsBrowser(String packageName, int userId) {
2766        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2767                PackageManager.MATCH_ALL, userId);
2768        final int N = list.size();
2769        for (int i = 0; i < N; i++) {
2770            ResolveInfo info = list.get(i);
2771            if (packageName.equals(info.activityInfo.packageName)) {
2772                return true;
2773            }
2774        }
2775        return false;
2776    }
2777
2778    private void checkDefaultBrowser() {
2779        final int myUserId = UserHandle.myUserId();
2780        final String packageName = getDefaultBrowserPackageName(myUserId);
2781        if (packageName != null) {
2782            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2783            if (info == null) {
2784                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2785                synchronized (mPackages) {
2786                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2787                }
2788            }
2789        }
2790    }
2791
2792    @Override
2793    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2794            throws RemoteException {
2795        try {
2796            return super.onTransact(code, data, reply, flags);
2797        } catch (RuntimeException e) {
2798            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2799                Slog.wtf(TAG, "Package Manager Crash", e);
2800            }
2801            throw e;
2802        }
2803    }
2804
2805    void cleanupInstallFailedPackage(PackageSetting ps) {
2806        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2807
2808        removeDataDirsLI(ps.volumeUuid, ps.name);
2809        if (ps.codePath != null) {
2810            removeCodePathLI(ps.codePath);
2811        }
2812        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2813            if (ps.resourcePath.isDirectory()) {
2814                FileUtils.deleteContents(ps.resourcePath);
2815            }
2816            ps.resourcePath.delete();
2817        }
2818        mSettings.removePackageLPw(ps.name);
2819    }
2820
2821    static int[] appendInts(int[] cur, int[] add) {
2822        if (add == null) return cur;
2823        if (cur == null) return add;
2824        final int N = add.length;
2825        for (int i=0; i<N; i++) {
2826            cur = appendInt(cur, add[i]);
2827        }
2828        return cur;
2829    }
2830
2831    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2832        if (!sUserManager.exists(userId)) return null;
2833        final PackageSetting ps = (PackageSetting) p.mExtras;
2834        if (ps == null) {
2835            return null;
2836        }
2837
2838        final PermissionsState permissionsState = ps.getPermissionsState();
2839
2840        final int[] gids = permissionsState.computeGids(userId);
2841        final Set<String> permissions = permissionsState.getPermissions(userId);
2842        final PackageUserState state = ps.readUserState(userId);
2843
2844        return PackageParser.generatePackageInfo(p, gids, flags,
2845                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2846    }
2847
2848    @Override
2849    public void checkPackageStartable(String packageName, int userId) {
2850        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2851
2852        synchronized (mPackages) {
2853            final PackageSetting ps = mSettings.mPackages.get(packageName);
2854            if (ps == null) {
2855                throw new SecurityException("Package " + packageName + " was not found!");
2856            }
2857
2858            if (ps.frozen) {
2859                throw new SecurityException("Package " + packageName + " is currently frozen!");
2860            }
2861
2862            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2863                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2864                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2865            }
2866        }
2867    }
2868
2869    @Override
2870    public boolean isPackageAvailable(String packageName, int userId) {
2871        if (!sUserManager.exists(userId)) return false;
2872        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2873        synchronized (mPackages) {
2874            PackageParser.Package p = mPackages.get(packageName);
2875            if (p != null) {
2876                final PackageSetting ps = (PackageSetting) p.mExtras;
2877                if (ps != null) {
2878                    final PackageUserState state = ps.readUserState(userId);
2879                    if (state != null) {
2880                        return PackageParser.isAvailable(state);
2881                    }
2882                }
2883            }
2884        }
2885        return false;
2886    }
2887
2888    @Override
2889    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        flags = updateFlagsForPackage(flags, userId, packageName);
2892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2893        // reader
2894        synchronized (mPackages) {
2895            PackageParser.Package p = mPackages.get(packageName);
2896            if (DEBUG_PACKAGE_INFO)
2897                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2898            if (p != null) {
2899                return generatePackageInfo(p, flags, userId);
2900            }
2901            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2902                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2903            }
2904        }
2905        return null;
2906    }
2907
2908    @Override
2909    public String[] currentToCanonicalPackageNames(String[] names) {
2910        String[] out = new String[names.length];
2911        // reader
2912        synchronized (mPackages) {
2913            for (int i=names.length-1; i>=0; i--) {
2914                PackageSetting ps = mSettings.mPackages.get(names[i]);
2915                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2916            }
2917        }
2918        return out;
2919    }
2920
2921    @Override
2922    public String[] canonicalToCurrentPackageNames(String[] names) {
2923        String[] out = new String[names.length];
2924        // reader
2925        synchronized (mPackages) {
2926            for (int i=names.length-1; i>=0; i--) {
2927                String cur = mSettings.mRenamedPackages.get(names[i]);
2928                out[i] = cur != null ? cur : names[i];
2929            }
2930        }
2931        return out;
2932    }
2933
2934    @Override
2935    public int getPackageUid(String packageName, int flags, int userId) {
2936        if (!sUserManager.exists(userId)) return -1;
2937        flags = updateFlagsForPackage(flags, userId, packageName);
2938        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2939
2940        // reader
2941        synchronized (mPackages) {
2942            final PackageParser.Package p = mPackages.get(packageName);
2943            if (p != null && p.isMatch(flags)) {
2944                return UserHandle.getUid(userId, p.applicationInfo.uid);
2945            }
2946            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2947                final PackageSetting ps = mSettings.mPackages.get(packageName);
2948                if (ps != null && ps.isMatch(flags)) {
2949                    return UserHandle.getUid(userId, ps.appId);
2950                }
2951            }
2952        }
2953
2954        return -1;
2955    }
2956
2957    @Override
2958    public int[] getPackageGids(String packageName, int flags, int userId) {
2959        if (!sUserManager.exists(userId)) return null;
2960        flags = updateFlagsForPackage(flags, userId, packageName);
2961        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2962                "getPackageGids");
2963
2964        // reader
2965        synchronized (mPackages) {
2966            final PackageParser.Package p = mPackages.get(packageName);
2967            if (p != null && p.isMatch(flags)) {
2968                PackageSetting ps = (PackageSetting) p.mExtras;
2969                return ps.getPermissionsState().computeGids(userId);
2970            }
2971            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2972                final PackageSetting ps = mSettings.mPackages.get(packageName);
2973                if (ps != null && ps.isMatch(flags)) {
2974                    return ps.getPermissionsState().computeGids(userId);
2975                }
2976            }
2977        }
2978
2979        return null;
2980    }
2981
2982    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2983        if (bp.perm != null) {
2984            return PackageParser.generatePermissionInfo(bp.perm, flags);
2985        }
2986        PermissionInfo pi = new PermissionInfo();
2987        pi.name = bp.name;
2988        pi.packageName = bp.sourcePackage;
2989        pi.nonLocalizedLabel = bp.name;
2990        pi.protectionLevel = bp.protectionLevel;
2991        return pi;
2992    }
2993
2994    @Override
2995    public PermissionInfo getPermissionInfo(String name, int flags) {
2996        // reader
2997        synchronized (mPackages) {
2998            final BasePermission p = mSettings.mPermissions.get(name);
2999            if (p != null) {
3000                return generatePermissionInfo(p, flags);
3001            }
3002            return null;
3003        }
3004    }
3005
3006    @Override
3007    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3008        // reader
3009        synchronized (mPackages) {
3010            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3011            for (BasePermission p : mSettings.mPermissions.values()) {
3012                if (group == null) {
3013                    if (p.perm == null || p.perm.info.group == null) {
3014                        out.add(generatePermissionInfo(p, flags));
3015                    }
3016                } else {
3017                    if (p.perm != null && group.equals(p.perm.info.group)) {
3018                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3019                    }
3020                }
3021            }
3022
3023            if (out.size() > 0) {
3024                return out;
3025            }
3026            return mPermissionGroups.containsKey(group) ? out : null;
3027        }
3028    }
3029
3030    @Override
3031    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3032        // reader
3033        synchronized (mPackages) {
3034            return PackageParser.generatePermissionGroupInfo(
3035                    mPermissionGroups.get(name), flags);
3036        }
3037    }
3038
3039    @Override
3040    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3041        // reader
3042        synchronized (mPackages) {
3043            final int N = mPermissionGroups.size();
3044            ArrayList<PermissionGroupInfo> out
3045                    = new ArrayList<PermissionGroupInfo>(N);
3046            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3047                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3048            }
3049            return out;
3050        }
3051    }
3052
3053    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3054            int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        PackageSetting ps = mSettings.mPackages.get(packageName);
3057        if (ps != null) {
3058            if (ps.pkg == null) {
3059                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3060                        flags, userId);
3061                if (pInfo != null) {
3062                    return pInfo.applicationInfo;
3063                }
3064                return null;
3065            }
3066            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3067                    ps.readUserState(userId), userId);
3068        }
3069        return null;
3070    }
3071
3072    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3073            int userId) {
3074        if (!sUserManager.exists(userId)) return null;
3075        PackageSetting ps = mSettings.mPackages.get(packageName);
3076        if (ps != null) {
3077            PackageParser.Package pkg = ps.pkg;
3078            if (pkg == null) {
3079                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3080                    return null;
3081                }
3082                // Only data remains, so we aren't worried about code paths
3083                pkg = new PackageParser.Package(packageName);
3084                pkg.applicationInfo.packageName = packageName;
3085                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3086                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3087                pkg.applicationInfo.uid = ps.appId;
3088                pkg.applicationInfo.initForUser(userId);
3089                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3090                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3091            }
3092            return generatePackageInfo(pkg, flags, userId);
3093        }
3094        return null;
3095    }
3096
3097    @Override
3098    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3099        if (!sUserManager.exists(userId)) return null;
3100        flags = updateFlagsForApplication(flags, userId, packageName);
3101        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3102        // writer
3103        synchronized (mPackages) {
3104            PackageParser.Package p = mPackages.get(packageName);
3105            if (DEBUG_PACKAGE_INFO) Log.v(
3106                    TAG, "getApplicationInfo " + packageName
3107                    + ": " + p);
3108            if (p != null) {
3109                PackageSetting ps = mSettings.mPackages.get(packageName);
3110                if (ps == null) return null;
3111                // Note: isEnabledLP() does not apply here - always return info
3112                return PackageParser.generateApplicationInfo(
3113                        p, flags, ps.readUserState(userId), userId);
3114            }
3115            if ("android".equals(packageName)||"system".equals(packageName)) {
3116                return mAndroidApplication;
3117            }
3118            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3119                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3120            }
3121        }
3122        return null;
3123    }
3124
3125    @Override
3126    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3127            final IPackageDataObserver observer) {
3128        mContext.enforceCallingOrSelfPermission(
3129                android.Manifest.permission.CLEAR_APP_CACHE, null);
3130        // Queue up an async operation since clearing cache may take a little while.
3131        mHandler.post(new Runnable() {
3132            public void run() {
3133                mHandler.removeCallbacks(this);
3134                boolean success = true;
3135                synchronized (mInstallLock) {
3136                    try {
3137                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3138                    } catch (InstallerException e) {
3139                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3140                        success = false;
3141                    }
3142                }
3143                if (observer != null) {
3144                    try {
3145                        observer.onRemoveCompleted(null, success);
3146                    } catch (RemoteException e) {
3147                        Slog.w(TAG, "RemoveException when invoking call back");
3148                    }
3149                }
3150            }
3151        });
3152    }
3153
3154    @Override
3155    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3156            final IntentSender pi) {
3157        mContext.enforceCallingOrSelfPermission(
3158                android.Manifest.permission.CLEAR_APP_CACHE, null);
3159        // Queue up an async operation since clearing cache may take a little while.
3160        mHandler.post(new Runnable() {
3161            public void run() {
3162                mHandler.removeCallbacks(this);
3163                boolean success = true;
3164                synchronized (mInstallLock) {
3165                    try {
3166                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3167                    } catch (InstallerException e) {
3168                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3169                        success = false;
3170                    }
3171                }
3172                if(pi != null) {
3173                    try {
3174                        // Callback via pending intent
3175                        int code = success ? 1 : 0;
3176                        pi.sendIntent(null, code, null,
3177                                null, null);
3178                    } catch (SendIntentException e1) {
3179                        Slog.i(TAG, "Failed to send pending intent");
3180                    }
3181                }
3182            }
3183        });
3184    }
3185
3186    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3187        synchronized (mInstallLock) {
3188            try {
3189                mInstaller.freeCache(volumeUuid, freeStorageSize);
3190            } catch (InstallerException e) {
3191                throw new IOException("Failed to free enough space", e);
3192            }
3193        }
3194    }
3195
3196    /**
3197     * Return if the user key is currently unlocked.
3198     */
3199    private boolean isUserKeyUnlocked(int userId) {
3200        if (StorageManager.isFileBasedEncryptionEnabled()) {
3201            final IMountService mount = IMountService.Stub
3202                    .asInterface(ServiceManager.getService("mount"));
3203            if (mount == null) {
3204                Slog.w(TAG, "Early during boot, assuming locked");
3205                return false;
3206            }
3207            final long token = Binder.clearCallingIdentity();
3208            try {
3209                return mount.isUserKeyUnlocked(userId);
3210            } catch (RemoteException e) {
3211                throw e.rethrowAsRuntimeException();
3212            } finally {
3213                Binder.restoreCallingIdentity(token);
3214            }
3215        } else {
3216            return true;
3217        }
3218    }
3219
3220    /**
3221     * Update given flags based on encryption status of current user.
3222     */
3223    private int updateFlags(int flags, int userId) {
3224        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3225                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3226            // Caller expressed an explicit opinion about what encryption
3227            // aware/unaware components they want to see, so fall through and
3228            // give them what they want
3229        } else {
3230            // Caller expressed no opinion, so match based on user state
3231            if (isUserKeyUnlocked(userId)) {
3232                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3233            } else {
3234                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3235            }
3236        }
3237
3238        // Safe mode means we should ignore any third-party apps
3239        if (mSafeMode) {
3240            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3241        }
3242
3243        return flags;
3244    }
3245
3246    /**
3247     * Update given flags when being used to request {@link PackageInfo}.
3248     */
3249    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3250        boolean triaged = true;
3251        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3252                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3253            // Caller is asking for component details, so they'd better be
3254            // asking for specific encryption matching behavior, or be triaged
3255            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3256                    | PackageManager.MATCH_ENCRYPTION_AWARE
3257                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3258                triaged = false;
3259            }
3260        }
3261        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3262                | PackageManager.MATCH_SYSTEM_ONLY
3263                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3264            triaged = false;
3265        }
3266        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3267            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3268                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3269        }
3270        return updateFlags(flags, userId);
3271    }
3272
3273    /**
3274     * Update given flags when being used to request {@link ApplicationInfo}.
3275     */
3276    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3277        return updateFlagsForPackage(flags, userId, cookie);
3278    }
3279
3280    /**
3281     * Update given flags when being used to request {@link ComponentInfo}.
3282     */
3283    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3284        if (cookie instanceof Intent) {
3285            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3286                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3287            }
3288        }
3289
3290        boolean triaged = true;
3291        // Caller is asking for component details, so they'd better be
3292        // asking for specific encryption matching behavior, or be triaged
3293        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3294                | PackageManager.MATCH_ENCRYPTION_AWARE
3295                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3296            triaged = false;
3297        }
3298        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3299            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3300                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3301        }
3302        return updateFlags(flags, userId);
3303    }
3304
3305    /**
3306     * Update given flags when being used to request {@link ResolveInfo}.
3307     */
3308    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3309        return updateFlagsForComponent(flags, userId, cookie);
3310    }
3311
3312    @Override
3313    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3314        if (!sUserManager.exists(userId)) return null;
3315        flags = updateFlagsForComponent(flags, userId, component);
3316        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3317        synchronized (mPackages) {
3318            PackageParser.Activity a = mActivities.mActivities.get(component);
3319
3320            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3321            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3322                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3323                if (ps == null) return null;
3324                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3325                        userId);
3326            }
3327            if (mResolveComponentName.equals(component)) {
3328                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3329                        new PackageUserState(), userId);
3330            }
3331        }
3332        return null;
3333    }
3334
3335    @Override
3336    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3337            String resolvedType) {
3338        synchronized (mPackages) {
3339            if (component.equals(mResolveComponentName)) {
3340                // The resolver supports EVERYTHING!
3341                return true;
3342            }
3343            PackageParser.Activity a = mActivities.mActivities.get(component);
3344            if (a == null) {
3345                return false;
3346            }
3347            for (int i=0; i<a.intents.size(); i++) {
3348                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3349                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3350                    return true;
3351                }
3352            }
3353            return false;
3354        }
3355    }
3356
3357    @Override
3358    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3359        if (!sUserManager.exists(userId)) return null;
3360        flags = updateFlagsForComponent(flags, userId, component);
3361        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3362        synchronized (mPackages) {
3363            PackageParser.Activity a = mReceivers.mActivities.get(component);
3364            if (DEBUG_PACKAGE_INFO) Log.v(
3365                TAG, "getReceiverInfo " + component + ": " + a);
3366            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3367                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3368                if (ps == null) return null;
3369                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3370                        userId);
3371            }
3372        }
3373        return null;
3374    }
3375
3376    @Override
3377    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return null;
3379        flags = updateFlagsForComponent(flags, userId, component);
3380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3381        synchronized (mPackages) {
3382            PackageParser.Service s = mServices.mServices.get(component);
3383            if (DEBUG_PACKAGE_INFO) Log.v(
3384                TAG, "getServiceInfo " + component + ": " + s);
3385            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3386                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3387                if (ps == null) return null;
3388                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3389                        userId);
3390            }
3391        }
3392        return null;
3393    }
3394
3395    @Override
3396    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3397        if (!sUserManager.exists(userId)) return null;
3398        flags = updateFlagsForComponent(flags, userId, component);
3399        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3400        synchronized (mPackages) {
3401            PackageParser.Provider p = mProviders.mProviders.get(component);
3402            if (DEBUG_PACKAGE_INFO) Log.v(
3403                TAG, "getProviderInfo " + component + ": " + p);
3404            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3405                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3406                if (ps == null) return null;
3407                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3408                        userId);
3409            }
3410        }
3411        return null;
3412    }
3413
3414    @Override
3415    public String[] getSystemSharedLibraryNames() {
3416        Set<String> libSet;
3417        synchronized (mPackages) {
3418            libSet = mSharedLibraries.keySet();
3419            int size = libSet.size();
3420            if (size > 0) {
3421                String[] libs = new String[size];
3422                libSet.toArray(libs);
3423                return libs;
3424            }
3425        }
3426        return null;
3427    }
3428
3429    @Override
3430    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3431        synchronized (mPackages) {
3432            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3433                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3434            if (libraryEntry != null) {
3435                return libraryEntry.apk;
3436            }
3437        }
3438        return null;
3439    }
3440
3441    @Override
3442    public FeatureInfo[] getSystemAvailableFeatures() {
3443        Collection<FeatureInfo> featSet;
3444        synchronized (mPackages) {
3445            featSet = mAvailableFeatures.values();
3446            int size = featSet.size();
3447            if (size > 0) {
3448                FeatureInfo[] features = new FeatureInfo[size+1];
3449                featSet.toArray(features);
3450                FeatureInfo fi = new FeatureInfo();
3451                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3452                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3453                features[size] = fi;
3454                return features;
3455            }
3456        }
3457        return null;
3458    }
3459
3460    @Override
3461    public boolean hasSystemFeature(String name) {
3462        synchronized (mPackages) {
3463            return mAvailableFeatures.containsKey(name);
3464        }
3465    }
3466
3467    @Override
3468    public int checkPermission(String permName, String pkgName, int userId) {
3469        if (!sUserManager.exists(userId)) {
3470            return PackageManager.PERMISSION_DENIED;
3471        }
3472
3473        synchronized (mPackages) {
3474            final PackageParser.Package p = mPackages.get(pkgName);
3475            if (p != null && p.mExtras != null) {
3476                final PackageSetting ps = (PackageSetting) p.mExtras;
3477                final PermissionsState permissionsState = ps.getPermissionsState();
3478                if (permissionsState.hasPermission(permName, userId)) {
3479                    return PackageManager.PERMISSION_GRANTED;
3480                }
3481                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3482                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3483                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3484                    return PackageManager.PERMISSION_GRANTED;
3485                }
3486            }
3487        }
3488
3489        return PackageManager.PERMISSION_DENIED;
3490    }
3491
3492    @Override
3493    public int checkUidPermission(String permName, int uid) {
3494        final int userId = UserHandle.getUserId(uid);
3495
3496        if (!sUserManager.exists(userId)) {
3497            return PackageManager.PERMISSION_DENIED;
3498        }
3499
3500        synchronized (mPackages) {
3501            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3502            if (obj != null) {
3503                final SettingBase ps = (SettingBase) obj;
3504                final PermissionsState permissionsState = ps.getPermissionsState();
3505                if (permissionsState.hasPermission(permName, userId)) {
3506                    return PackageManager.PERMISSION_GRANTED;
3507                }
3508                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3509                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3510                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3511                    return PackageManager.PERMISSION_GRANTED;
3512                }
3513            } else {
3514                ArraySet<String> perms = mSystemPermissions.get(uid);
3515                if (perms != null) {
3516                    if (perms.contains(permName)) {
3517                        return PackageManager.PERMISSION_GRANTED;
3518                    }
3519                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3520                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3521                        return PackageManager.PERMISSION_GRANTED;
3522                    }
3523                }
3524            }
3525        }
3526
3527        return PackageManager.PERMISSION_DENIED;
3528    }
3529
3530    @Override
3531    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3532        if (UserHandle.getCallingUserId() != userId) {
3533            mContext.enforceCallingPermission(
3534                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3535                    "isPermissionRevokedByPolicy for user " + userId);
3536        }
3537
3538        if (checkPermission(permission, packageName, userId)
3539                == PackageManager.PERMISSION_GRANTED) {
3540            return false;
3541        }
3542
3543        final long identity = Binder.clearCallingIdentity();
3544        try {
3545            final int flags = getPermissionFlags(permission, packageName, userId);
3546            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3547        } finally {
3548            Binder.restoreCallingIdentity(identity);
3549        }
3550    }
3551
3552    @Override
3553    public String getPermissionControllerPackageName() {
3554        synchronized (mPackages) {
3555            return mRequiredInstallerPackage;
3556        }
3557    }
3558
3559    /**
3560     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3561     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3562     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3563     * @param message the message to log on security exception
3564     */
3565    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3566            boolean checkShell, String message) {
3567        if (userId < 0) {
3568            throw new IllegalArgumentException("Invalid userId " + userId);
3569        }
3570        if (checkShell) {
3571            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3572        }
3573        if (userId == UserHandle.getUserId(callingUid)) return;
3574        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3575            if (requireFullPermission) {
3576                mContext.enforceCallingOrSelfPermission(
3577                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3578            } else {
3579                try {
3580                    mContext.enforceCallingOrSelfPermission(
3581                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3582                } catch (SecurityException se) {
3583                    mContext.enforceCallingOrSelfPermission(
3584                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3585                }
3586            }
3587        }
3588    }
3589
3590    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3591        if (callingUid == Process.SHELL_UID) {
3592            if (userHandle >= 0
3593                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3594                throw new SecurityException("Shell does not have permission to access user "
3595                        + userHandle);
3596            } else if (userHandle < 0) {
3597                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3598                        + Debug.getCallers(3));
3599            }
3600        }
3601    }
3602
3603    private BasePermission findPermissionTreeLP(String permName) {
3604        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3605            if (permName.startsWith(bp.name) &&
3606                    permName.length() > bp.name.length() &&
3607                    permName.charAt(bp.name.length()) == '.') {
3608                return bp;
3609            }
3610        }
3611        return null;
3612    }
3613
3614    private BasePermission checkPermissionTreeLP(String permName) {
3615        if (permName != null) {
3616            BasePermission bp = findPermissionTreeLP(permName);
3617            if (bp != null) {
3618                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3619                    return bp;
3620                }
3621                throw new SecurityException("Calling uid "
3622                        + Binder.getCallingUid()
3623                        + " is not allowed to add to permission tree "
3624                        + bp.name + " owned by uid " + bp.uid);
3625            }
3626        }
3627        throw new SecurityException("No permission tree found for " + permName);
3628    }
3629
3630    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3631        if (s1 == null) {
3632            return s2 == null;
3633        }
3634        if (s2 == null) {
3635            return false;
3636        }
3637        if (s1.getClass() != s2.getClass()) {
3638            return false;
3639        }
3640        return s1.equals(s2);
3641    }
3642
3643    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3644        if (pi1.icon != pi2.icon) return false;
3645        if (pi1.logo != pi2.logo) return false;
3646        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3647        if (!compareStrings(pi1.name, pi2.name)) return false;
3648        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3649        // We'll take care of setting this one.
3650        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3651        // These are not currently stored in settings.
3652        //if (!compareStrings(pi1.group, pi2.group)) return false;
3653        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3654        //if (pi1.labelRes != pi2.labelRes) return false;
3655        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3656        return true;
3657    }
3658
3659    int permissionInfoFootprint(PermissionInfo info) {
3660        int size = info.name.length();
3661        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3662        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3663        return size;
3664    }
3665
3666    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3667        int size = 0;
3668        for (BasePermission perm : mSettings.mPermissions.values()) {
3669            if (perm.uid == tree.uid) {
3670                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3671            }
3672        }
3673        return size;
3674    }
3675
3676    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3677        // We calculate the max size of permissions defined by this uid and throw
3678        // if that plus the size of 'info' would exceed our stated maximum.
3679        if (tree.uid != Process.SYSTEM_UID) {
3680            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3681            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3682                throw new SecurityException("Permission tree size cap exceeded");
3683            }
3684        }
3685    }
3686
3687    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3688        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3689            throw new SecurityException("Label must be specified in permission");
3690        }
3691        BasePermission tree = checkPermissionTreeLP(info.name);
3692        BasePermission bp = mSettings.mPermissions.get(info.name);
3693        boolean added = bp == null;
3694        boolean changed = true;
3695        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3696        if (added) {
3697            enforcePermissionCapLocked(info, tree);
3698            bp = new BasePermission(info.name, tree.sourcePackage,
3699                    BasePermission.TYPE_DYNAMIC);
3700        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3701            throw new SecurityException(
3702                    "Not allowed to modify non-dynamic permission "
3703                    + info.name);
3704        } else {
3705            if (bp.protectionLevel == fixedLevel
3706                    && bp.perm.owner.equals(tree.perm.owner)
3707                    && bp.uid == tree.uid
3708                    && comparePermissionInfos(bp.perm.info, info)) {
3709                changed = false;
3710            }
3711        }
3712        bp.protectionLevel = fixedLevel;
3713        info = new PermissionInfo(info);
3714        info.protectionLevel = fixedLevel;
3715        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3716        bp.perm.info.packageName = tree.perm.info.packageName;
3717        bp.uid = tree.uid;
3718        if (added) {
3719            mSettings.mPermissions.put(info.name, bp);
3720        }
3721        if (changed) {
3722            if (!async) {
3723                mSettings.writeLPr();
3724            } else {
3725                scheduleWriteSettingsLocked();
3726            }
3727        }
3728        return added;
3729    }
3730
3731    @Override
3732    public boolean addPermission(PermissionInfo info) {
3733        synchronized (mPackages) {
3734            return addPermissionLocked(info, false);
3735        }
3736    }
3737
3738    @Override
3739    public boolean addPermissionAsync(PermissionInfo info) {
3740        synchronized (mPackages) {
3741            return addPermissionLocked(info, true);
3742        }
3743    }
3744
3745    @Override
3746    public void removePermission(String name) {
3747        synchronized (mPackages) {
3748            checkPermissionTreeLP(name);
3749            BasePermission bp = mSettings.mPermissions.get(name);
3750            if (bp != null) {
3751                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3752                    throw new SecurityException(
3753                            "Not allowed to modify non-dynamic permission "
3754                            + name);
3755                }
3756                mSettings.mPermissions.remove(name);
3757                mSettings.writeLPr();
3758            }
3759        }
3760    }
3761
3762    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3763            BasePermission bp) {
3764        int index = pkg.requestedPermissions.indexOf(bp.name);
3765        if (index == -1) {
3766            throw new SecurityException("Package " + pkg.packageName
3767                    + " has not requested permission " + bp.name);
3768        }
3769        if (!bp.isRuntime() && !bp.isDevelopment()) {
3770            throw new SecurityException("Permission " + bp.name
3771                    + " is not a changeable permission type");
3772        }
3773    }
3774
3775    @Override
3776    public void grantRuntimePermission(String packageName, String name, final int userId) {
3777        if (!sUserManager.exists(userId)) {
3778            Log.e(TAG, "No such user:" + userId);
3779            return;
3780        }
3781
3782        mContext.enforceCallingOrSelfPermission(
3783                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3784                "grantRuntimePermission");
3785
3786        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3787                "grantRuntimePermission");
3788
3789        final int uid;
3790        final SettingBase sb;
3791
3792        synchronized (mPackages) {
3793            final PackageParser.Package pkg = mPackages.get(packageName);
3794            if (pkg == null) {
3795                throw new IllegalArgumentException("Unknown package: " + packageName);
3796            }
3797
3798            final BasePermission bp = mSettings.mPermissions.get(name);
3799            if (bp == null) {
3800                throw new IllegalArgumentException("Unknown permission: " + name);
3801            }
3802
3803            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3804
3805            // If a permission review is required for legacy apps we represent
3806            // their permissions as always granted runtime ones since we need
3807            // to keep the review required permission flag per user while an
3808            // install permission's state is shared across all users.
3809            if (Build.PERMISSIONS_REVIEW_REQUIRED
3810                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3811                    && bp.isRuntime()) {
3812                return;
3813            }
3814
3815            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3816            sb = (SettingBase) pkg.mExtras;
3817            if (sb == null) {
3818                throw new IllegalArgumentException("Unknown package: " + packageName);
3819            }
3820
3821            final PermissionsState permissionsState = sb.getPermissionsState();
3822
3823            final int flags = permissionsState.getPermissionFlags(name, userId);
3824            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3825                throw new SecurityException("Cannot grant system fixed permission "
3826                        + name + " for package " + packageName);
3827            }
3828
3829            if (bp.isDevelopment()) {
3830                // Development permissions must be handled specially, since they are not
3831                // normal runtime permissions.  For now they apply to all users.
3832                if (permissionsState.grantInstallPermission(bp) !=
3833                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3834                    scheduleWriteSettingsLocked();
3835                }
3836                return;
3837            }
3838
3839            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3840                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3841                return;
3842            }
3843
3844            final int result = permissionsState.grantRuntimePermission(bp, userId);
3845            switch (result) {
3846                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3847                    return;
3848                }
3849
3850                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3851                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3852                    mHandler.post(new Runnable() {
3853                        @Override
3854                        public void run() {
3855                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3856                        }
3857                    });
3858                }
3859                break;
3860            }
3861
3862            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3863
3864            // Not critical if that is lost - app has to request again.
3865            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3866        }
3867
3868        // Only need to do this if user is initialized. Otherwise it's a new user
3869        // and there are no processes running as the user yet and there's no need
3870        // to make an expensive call to remount processes for the changed permissions.
3871        if (READ_EXTERNAL_STORAGE.equals(name)
3872                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3873            final long token = Binder.clearCallingIdentity();
3874            try {
3875                if (sUserManager.isInitialized(userId)) {
3876                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3877                            MountServiceInternal.class);
3878                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3879                }
3880            } finally {
3881                Binder.restoreCallingIdentity(token);
3882            }
3883        }
3884    }
3885
3886    @Override
3887    public void revokeRuntimePermission(String packageName, String name, int userId) {
3888        if (!sUserManager.exists(userId)) {
3889            Log.e(TAG, "No such user:" + userId);
3890            return;
3891        }
3892
3893        mContext.enforceCallingOrSelfPermission(
3894                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3895                "revokeRuntimePermission");
3896
3897        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3898                "revokeRuntimePermission");
3899
3900        final int appId;
3901
3902        synchronized (mPackages) {
3903            final PackageParser.Package pkg = mPackages.get(packageName);
3904            if (pkg == null) {
3905                throw new IllegalArgumentException("Unknown package: " + packageName);
3906            }
3907
3908            final BasePermission bp = mSettings.mPermissions.get(name);
3909            if (bp == null) {
3910                throw new IllegalArgumentException("Unknown permission: " + name);
3911            }
3912
3913            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3914
3915            // If a permission review is required for legacy apps we represent
3916            // their permissions as always granted runtime ones since we need
3917            // to keep the review required permission flag per user while an
3918            // install permission's state is shared across all users.
3919            if (Build.PERMISSIONS_REVIEW_REQUIRED
3920                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3921                    && bp.isRuntime()) {
3922                return;
3923            }
3924
3925            SettingBase sb = (SettingBase) pkg.mExtras;
3926            if (sb == null) {
3927                throw new IllegalArgumentException("Unknown package: " + packageName);
3928            }
3929
3930            final PermissionsState permissionsState = sb.getPermissionsState();
3931
3932            final int flags = permissionsState.getPermissionFlags(name, userId);
3933            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3934                throw new SecurityException("Cannot revoke system fixed permission "
3935                        + name + " for package " + packageName);
3936            }
3937
3938            if (bp.isDevelopment()) {
3939                // Development permissions must be handled specially, since they are not
3940                // normal runtime permissions.  For now they apply to all users.
3941                if (permissionsState.revokeInstallPermission(bp) !=
3942                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3943                    scheduleWriteSettingsLocked();
3944                }
3945                return;
3946            }
3947
3948            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3949                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3950                return;
3951            }
3952
3953            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3954
3955            // Critical, after this call app should never have the permission.
3956            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3957
3958            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3959        }
3960
3961        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3962    }
3963
3964    @Override
3965    public void resetRuntimePermissions() {
3966        mContext.enforceCallingOrSelfPermission(
3967                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3968                "revokeRuntimePermission");
3969
3970        int callingUid = Binder.getCallingUid();
3971        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3972            mContext.enforceCallingOrSelfPermission(
3973                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3974                    "resetRuntimePermissions");
3975        }
3976
3977        synchronized (mPackages) {
3978            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3979            for (int userId : UserManagerService.getInstance().getUserIds()) {
3980                final int packageCount = mPackages.size();
3981                for (int i = 0; i < packageCount; i++) {
3982                    PackageParser.Package pkg = mPackages.valueAt(i);
3983                    if (!(pkg.mExtras instanceof PackageSetting)) {
3984                        continue;
3985                    }
3986                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3987                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3988                }
3989            }
3990        }
3991    }
3992
3993    @Override
3994    public int getPermissionFlags(String name, String packageName, int userId) {
3995        if (!sUserManager.exists(userId)) {
3996            return 0;
3997        }
3998
3999        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4000
4001        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4002                "getPermissionFlags");
4003
4004        synchronized (mPackages) {
4005            final PackageParser.Package pkg = mPackages.get(packageName);
4006            if (pkg == null) {
4007                throw new IllegalArgumentException("Unknown package: " + packageName);
4008            }
4009
4010            final BasePermission bp = mSettings.mPermissions.get(name);
4011            if (bp == null) {
4012                throw new IllegalArgumentException("Unknown permission: " + name);
4013            }
4014
4015            SettingBase sb = (SettingBase) pkg.mExtras;
4016            if (sb == null) {
4017                throw new IllegalArgumentException("Unknown package: " + packageName);
4018            }
4019
4020            PermissionsState permissionsState = sb.getPermissionsState();
4021            return permissionsState.getPermissionFlags(name, userId);
4022        }
4023    }
4024
4025    @Override
4026    public void updatePermissionFlags(String name, String packageName, int flagMask,
4027            int flagValues, int userId) {
4028        if (!sUserManager.exists(userId)) {
4029            return;
4030        }
4031
4032        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4033
4034        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4035                "updatePermissionFlags");
4036
4037        // Only the system can change these flags and nothing else.
4038        if (getCallingUid() != Process.SYSTEM_UID) {
4039            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4040            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4041            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4042            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4043            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4044        }
4045
4046        synchronized (mPackages) {
4047            final PackageParser.Package pkg = mPackages.get(packageName);
4048            if (pkg == null) {
4049                throw new IllegalArgumentException("Unknown package: " + packageName);
4050            }
4051
4052            final BasePermission bp = mSettings.mPermissions.get(name);
4053            if (bp == null) {
4054                throw new IllegalArgumentException("Unknown permission: " + name);
4055            }
4056
4057            SettingBase sb = (SettingBase) pkg.mExtras;
4058            if (sb == null) {
4059                throw new IllegalArgumentException("Unknown package: " + packageName);
4060            }
4061
4062            PermissionsState permissionsState = sb.getPermissionsState();
4063
4064            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4065
4066            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4067                // Install and runtime permissions are stored in different places,
4068                // so figure out what permission changed and persist the change.
4069                if (permissionsState.getInstallPermissionState(name) != null) {
4070                    scheduleWriteSettingsLocked();
4071                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4072                        || hadState) {
4073                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4074                }
4075            }
4076        }
4077    }
4078
4079    /**
4080     * Update the permission flags for all packages and runtime permissions of a user in order
4081     * to allow device or profile owner to remove POLICY_FIXED.
4082     */
4083    @Override
4084    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4085        if (!sUserManager.exists(userId)) {
4086            return;
4087        }
4088
4089        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4090
4091        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4092                "updatePermissionFlagsForAllApps");
4093
4094        // Only the system can change system fixed flags.
4095        if (getCallingUid() != Process.SYSTEM_UID) {
4096            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4097            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4098        }
4099
4100        synchronized (mPackages) {
4101            boolean changed = false;
4102            final int packageCount = mPackages.size();
4103            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4104                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4105                SettingBase sb = (SettingBase) pkg.mExtras;
4106                if (sb == null) {
4107                    continue;
4108                }
4109                PermissionsState permissionsState = sb.getPermissionsState();
4110                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4111                        userId, flagMask, flagValues);
4112            }
4113            if (changed) {
4114                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4115            }
4116        }
4117    }
4118
4119    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4120        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4121                != PackageManager.PERMISSION_GRANTED
4122            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4123                != PackageManager.PERMISSION_GRANTED) {
4124            throw new SecurityException(message + " requires "
4125                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4126                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4127        }
4128    }
4129
4130    @Override
4131    public boolean shouldShowRequestPermissionRationale(String permissionName,
4132            String packageName, int userId) {
4133        if (UserHandle.getCallingUserId() != userId) {
4134            mContext.enforceCallingPermission(
4135                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4136                    "canShowRequestPermissionRationale for user " + userId);
4137        }
4138
4139        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4140        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4141            return false;
4142        }
4143
4144        if (checkPermission(permissionName, packageName, userId)
4145                == PackageManager.PERMISSION_GRANTED) {
4146            return false;
4147        }
4148
4149        final int flags;
4150
4151        final long identity = Binder.clearCallingIdentity();
4152        try {
4153            flags = getPermissionFlags(permissionName,
4154                    packageName, userId);
4155        } finally {
4156            Binder.restoreCallingIdentity(identity);
4157        }
4158
4159        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4160                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4161                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4162
4163        if ((flags & fixedFlags) != 0) {
4164            return false;
4165        }
4166
4167        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4168    }
4169
4170    @Override
4171    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4172        mContext.enforceCallingOrSelfPermission(
4173                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4174                "addOnPermissionsChangeListener");
4175
4176        synchronized (mPackages) {
4177            mOnPermissionChangeListeners.addListenerLocked(listener);
4178        }
4179    }
4180
4181    @Override
4182    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4183        synchronized (mPackages) {
4184            mOnPermissionChangeListeners.removeListenerLocked(listener);
4185        }
4186    }
4187
4188    @Override
4189    public boolean isProtectedBroadcast(String actionName) {
4190        synchronized (mPackages) {
4191            if (mProtectedBroadcasts.contains(actionName)) {
4192                return true;
4193            } else if (actionName != null) {
4194                // TODO: remove these terrible hacks
4195                if (actionName.startsWith("android.net.netmon.lingerExpired")
4196                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4197                    return true;
4198                }
4199            }
4200        }
4201        return false;
4202    }
4203
4204    @Override
4205    public int checkSignatures(String pkg1, String pkg2) {
4206        synchronized (mPackages) {
4207            final PackageParser.Package p1 = mPackages.get(pkg1);
4208            final PackageParser.Package p2 = mPackages.get(pkg2);
4209            if (p1 == null || p1.mExtras == null
4210                    || p2 == null || p2.mExtras == null) {
4211                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4212            }
4213            return compareSignatures(p1.mSignatures, p2.mSignatures);
4214        }
4215    }
4216
4217    @Override
4218    public int checkUidSignatures(int uid1, int uid2) {
4219        // Map to base uids.
4220        uid1 = UserHandle.getAppId(uid1);
4221        uid2 = UserHandle.getAppId(uid2);
4222        // reader
4223        synchronized (mPackages) {
4224            Signature[] s1;
4225            Signature[] s2;
4226            Object obj = mSettings.getUserIdLPr(uid1);
4227            if (obj != null) {
4228                if (obj instanceof SharedUserSetting) {
4229                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4230                } else if (obj instanceof PackageSetting) {
4231                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4232                } else {
4233                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4234                }
4235            } else {
4236                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4237            }
4238            obj = mSettings.getUserIdLPr(uid2);
4239            if (obj != null) {
4240                if (obj instanceof SharedUserSetting) {
4241                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4242                } else if (obj instanceof PackageSetting) {
4243                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4244                } else {
4245                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4246                }
4247            } else {
4248                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4249            }
4250            return compareSignatures(s1, s2);
4251        }
4252    }
4253
4254    private void killUid(int appId, int userId, String reason) {
4255        final long identity = Binder.clearCallingIdentity();
4256        try {
4257            IActivityManager am = ActivityManagerNative.getDefault();
4258            if (am != null) {
4259                try {
4260                    am.killUid(appId, userId, reason);
4261                } catch (RemoteException e) {
4262                    /* ignore - same process */
4263                }
4264            }
4265        } finally {
4266            Binder.restoreCallingIdentity(identity);
4267        }
4268    }
4269
4270    /**
4271     * Compares two sets of signatures. Returns:
4272     * <br />
4273     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4274     * <br />
4275     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4276     * <br />
4277     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4278     * <br />
4279     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4280     * <br />
4281     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4282     */
4283    static int compareSignatures(Signature[] s1, Signature[] s2) {
4284        if (s1 == null) {
4285            return s2 == null
4286                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4287                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4288        }
4289
4290        if (s2 == null) {
4291            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4292        }
4293
4294        if (s1.length != s2.length) {
4295            return PackageManager.SIGNATURE_NO_MATCH;
4296        }
4297
4298        // Since both signature sets are of size 1, we can compare without HashSets.
4299        if (s1.length == 1) {
4300            return s1[0].equals(s2[0]) ?
4301                    PackageManager.SIGNATURE_MATCH :
4302                    PackageManager.SIGNATURE_NO_MATCH;
4303        }
4304
4305        ArraySet<Signature> set1 = new ArraySet<Signature>();
4306        for (Signature sig : s1) {
4307            set1.add(sig);
4308        }
4309        ArraySet<Signature> set2 = new ArraySet<Signature>();
4310        for (Signature sig : s2) {
4311            set2.add(sig);
4312        }
4313        // Make sure s2 contains all signatures in s1.
4314        if (set1.equals(set2)) {
4315            return PackageManager.SIGNATURE_MATCH;
4316        }
4317        return PackageManager.SIGNATURE_NO_MATCH;
4318    }
4319
4320    /**
4321     * If the database version for this type of package (internal storage or
4322     * external storage) is less than the version where package signatures
4323     * were updated, return true.
4324     */
4325    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4326        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4327        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4328    }
4329
4330    /**
4331     * Used for backward compatibility to make sure any packages with
4332     * certificate chains get upgraded to the new style. {@code existingSigs}
4333     * will be in the old format (since they were stored on disk from before the
4334     * system upgrade) and {@code scannedSigs} will be in the newer format.
4335     */
4336    private int compareSignaturesCompat(PackageSignatures existingSigs,
4337            PackageParser.Package scannedPkg) {
4338        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4339            return PackageManager.SIGNATURE_NO_MATCH;
4340        }
4341
4342        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4343        for (Signature sig : existingSigs.mSignatures) {
4344            existingSet.add(sig);
4345        }
4346        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4347        for (Signature sig : scannedPkg.mSignatures) {
4348            try {
4349                Signature[] chainSignatures = sig.getChainSignatures();
4350                for (Signature chainSig : chainSignatures) {
4351                    scannedCompatSet.add(chainSig);
4352                }
4353            } catch (CertificateEncodingException e) {
4354                scannedCompatSet.add(sig);
4355            }
4356        }
4357        /*
4358         * Make sure the expanded scanned set contains all signatures in the
4359         * existing one.
4360         */
4361        if (scannedCompatSet.equals(existingSet)) {
4362            // Migrate the old signatures to the new scheme.
4363            existingSigs.assignSignatures(scannedPkg.mSignatures);
4364            // The new KeySets will be re-added later in the scanning process.
4365            synchronized (mPackages) {
4366                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4367            }
4368            return PackageManager.SIGNATURE_MATCH;
4369        }
4370        return PackageManager.SIGNATURE_NO_MATCH;
4371    }
4372
4373    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4374        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4375        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4376    }
4377
4378    private int compareSignaturesRecover(PackageSignatures existingSigs,
4379            PackageParser.Package scannedPkg) {
4380        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4381            return PackageManager.SIGNATURE_NO_MATCH;
4382        }
4383
4384        String msg = null;
4385        try {
4386            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4387                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4388                        + scannedPkg.packageName);
4389                return PackageManager.SIGNATURE_MATCH;
4390            }
4391        } catch (CertificateException e) {
4392            msg = e.getMessage();
4393        }
4394
4395        logCriticalInfo(Log.INFO,
4396                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4397        return PackageManager.SIGNATURE_NO_MATCH;
4398    }
4399
4400    @Override
4401    public String[] getPackagesForUid(int uid) {
4402        uid = UserHandle.getAppId(uid);
4403        // reader
4404        synchronized (mPackages) {
4405            Object obj = mSettings.getUserIdLPr(uid);
4406            if (obj instanceof SharedUserSetting) {
4407                final SharedUserSetting sus = (SharedUserSetting) obj;
4408                final int N = sus.packages.size();
4409                final String[] res = new String[N];
4410                final Iterator<PackageSetting> it = sus.packages.iterator();
4411                int i = 0;
4412                while (it.hasNext()) {
4413                    res[i++] = it.next().name;
4414                }
4415                return res;
4416            } else if (obj instanceof PackageSetting) {
4417                final PackageSetting ps = (PackageSetting) obj;
4418                return new String[] { ps.name };
4419            }
4420        }
4421        return null;
4422    }
4423
4424    @Override
4425    public String getNameForUid(int uid) {
4426        // reader
4427        synchronized (mPackages) {
4428            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4429            if (obj instanceof SharedUserSetting) {
4430                final SharedUserSetting sus = (SharedUserSetting) obj;
4431                return sus.name + ":" + sus.userId;
4432            } else if (obj instanceof PackageSetting) {
4433                final PackageSetting ps = (PackageSetting) obj;
4434                return ps.name;
4435            }
4436        }
4437        return null;
4438    }
4439
4440    @Override
4441    public int getUidForSharedUser(String sharedUserName) {
4442        if(sharedUserName == null) {
4443            return -1;
4444        }
4445        // reader
4446        synchronized (mPackages) {
4447            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4448            if (suid == null) {
4449                return -1;
4450            }
4451            return suid.userId;
4452        }
4453    }
4454
4455    @Override
4456    public int getFlagsForUid(int uid) {
4457        synchronized (mPackages) {
4458            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4459            if (obj instanceof SharedUserSetting) {
4460                final SharedUserSetting sus = (SharedUserSetting) obj;
4461                return sus.pkgFlags;
4462            } else if (obj instanceof PackageSetting) {
4463                final PackageSetting ps = (PackageSetting) obj;
4464                return ps.pkgFlags;
4465            }
4466        }
4467        return 0;
4468    }
4469
4470    @Override
4471    public int getPrivateFlagsForUid(int uid) {
4472        synchronized (mPackages) {
4473            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4474            if (obj instanceof SharedUserSetting) {
4475                final SharedUserSetting sus = (SharedUserSetting) obj;
4476                return sus.pkgPrivateFlags;
4477            } else if (obj instanceof PackageSetting) {
4478                final PackageSetting ps = (PackageSetting) obj;
4479                return ps.pkgPrivateFlags;
4480            }
4481        }
4482        return 0;
4483    }
4484
4485    @Override
4486    public boolean isUidPrivileged(int uid) {
4487        uid = UserHandle.getAppId(uid);
4488        // reader
4489        synchronized (mPackages) {
4490            Object obj = mSettings.getUserIdLPr(uid);
4491            if (obj instanceof SharedUserSetting) {
4492                final SharedUserSetting sus = (SharedUserSetting) obj;
4493                final Iterator<PackageSetting> it = sus.packages.iterator();
4494                while (it.hasNext()) {
4495                    if (it.next().isPrivileged()) {
4496                        return true;
4497                    }
4498                }
4499            } else if (obj instanceof PackageSetting) {
4500                final PackageSetting ps = (PackageSetting) obj;
4501                return ps.isPrivileged();
4502            }
4503        }
4504        return false;
4505    }
4506
4507    @Override
4508    public String[] getAppOpPermissionPackages(String permissionName) {
4509        synchronized (mPackages) {
4510            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4511            if (pkgs == null) {
4512                return null;
4513            }
4514            return pkgs.toArray(new String[pkgs.size()]);
4515        }
4516    }
4517
4518    @Override
4519    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4520            int flags, int userId) {
4521        if (!sUserManager.exists(userId)) return null;
4522        flags = updateFlagsForResolve(flags, userId, intent);
4523        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4524        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4525        final ResolveInfo bestChoice =
4526                chooseBestActivity(intent, resolvedType, flags, query, userId);
4527
4528        if (isEphemeralAllowed(intent, query, userId)) {
4529            final EphemeralResolveInfo ai =
4530                    getEphemeralResolveInfo(intent, resolvedType, userId);
4531            if (ai != null) {
4532                if (DEBUG_EPHEMERAL) {
4533                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4534                }
4535                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4536                bestChoice.ephemeralResolveInfo = ai;
4537            }
4538        }
4539        return bestChoice;
4540    }
4541
4542    @Override
4543    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4544            IntentFilter filter, int match, ComponentName activity) {
4545        final int userId = UserHandle.getCallingUserId();
4546        if (DEBUG_PREFERRED) {
4547            Log.v(TAG, "setLastChosenActivity intent=" + intent
4548                + " resolvedType=" + resolvedType
4549                + " flags=" + flags
4550                + " filter=" + filter
4551                + " match=" + match
4552                + " activity=" + activity);
4553            filter.dump(new PrintStreamPrinter(System.out), "    ");
4554        }
4555        intent.setComponent(null);
4556        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4557        // Find any earlier preferred or last chosen entries and nuke them
4558        findPreferredActivity(intent, resolvedType,
4559                flags, query, 0, false, true, false, userId);
4560        // Add the new activity as the last chosen for this filter
4561        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4562                "Setting last chosen");
4563    }
4564
4565    @Override
4566    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4567        final int userId = UserHandle.getCallingUserId();
4568        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4569        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4570        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4571                false, false, false, userId);
4572    }
4573
4574
4575    private boolean isEphemeralAllowed(
4576            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4577        // Short circuit and return early if possible.
4578        if (DISABLE_EPHEMERAL_APPS) {
4579            return false;
4580        }
4581        final int callingUser = UserHandle.getCallingUserId();
4582        if (callingUser != UserHandle.USER_SYSTEM) {
4583            return false;
4584        }
4585        if (mEphemeralResolverConnection == null) {
4586            return false;
4587        }
4588        if (intent.getComponent() != null) {
4589            return false;
4590        }
4591        if (intent.getPackage() != null) {
4592            return false;
4593        }
4594        final boolean isWebUri = hasWebURI(intent);
4595        if (!isWebUri) {
4596            return false;
4597        }
4598        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4599        synchronized (mPackages) {
4600            final int count = resolvedActivites.size();
4601            for (int n = 0; n < count; n++) {
4602                ResolveInfo info = resolvedActivites.get(n);
4603                String packageName = info.activityInfo.packageName;
4604                PackageSetting ps = mSettings.mPackages.get(packageName);
4605                if (ps != null) {
4606                    // Try to get the status from User settings first
4607                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4608                    int status = (int) (packedStatus >> 32);
4609                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4610                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4611                        if (DEBUG_EPHEMERAL) {
4612                            Slog.v(TAG, "DENY ephemeral apps;"
4613                                + " pkg: " + packageName + ", status: " + status);
4614                        }
4615                        return false;
4616                    }
4617                }
4618            }
4619        }
4620        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4621        return true;
4622    }
4623
4624    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4625            int userId) {
4626        MessageDigest digest = null;
4627        try {
4628            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4629        } catch (NoSuchAlgorithmException e) {
4630            // If we can't create a digest, ignore ephemeral apps.
4631            return null;
4632        }
4633
4634        final byte[] hostBytes = intent.getData().getHost().getBytes();
4635        final byte[] digestBytes = digest.digest(hostBytes);
4636        int shaPrefix =
4637                digestBytes[0] << 24
4638                | digestBytes[1] << 16
4639                | digestBytes[2] << 8
4640                | digestBytes[3] << 0;
4641        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4642                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4643        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4644            // No hash prefix match; there are no ephemeral apps for this domain.
4645            return null;
4646        }
4647        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4648            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4649            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4650                continue;
4651            }
4652            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4653            // No filters; this should never happen.
4654            if (filters.isEmpty()) {
4655                continue;
4656            }
4657            // We have a domain match; resolve the filters to see if anything matches.
4658            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4659            for (int j = filters.size() - 1; j >= 0; --j) {
4660                final EphemeralResolveIntentInfo intentInfo =
4661                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4662                ephemeralResolver.addFilter(intentInfo);
4663            }
4664            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4665                    intent, resolvedType, false /*defaultOnly*/, userId);
4666            if (!matchedResolveInfoList.isEmpty()) {
4667                return matchedResolveInfoList.get(0);
4668            }
4669        }
4670        // Hash or filter mis-match; no ephemeral apps for this domain.
4671        return null;
4672    }
4673
4674    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4675            int flags, List<ResolveInfo> query, int userId) {
4676        if (query != null) {
4677            final int N = query.size();
4678            if (N == 1) {
4679                return query.get(0);
4680            } else if (N > 1) {
4681                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4682                // If there is more than one activity with the same priority,
4683                // then let the user decide between them.
4684                ResolveInfo r0 = query.get(0);
4685                ResolveInfo r1 = query.get(1);
4686                if (DEBUG_INTENT_MATCHING || debug) {
4687                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4688                            + r1.activityInfo.name + "=" + r1.priority);
4689                }
4690                // If the first activity has a higher priority, or a different
4691                // default, then it is always desirable to pick it.
4692                if (r0.priority != r1.priority
4693                        || r0.preferredOrder != r1.preferredOrder
4694                        || r0.isDefault != r1.isDefault) {
4695                    return query.get(0);
4696                }
4697                // If we have saved a preference for a preferred activity for
4698                // this Intent, use that.
4699                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4700                        flags, query, r0.priority, true, false, debug, userId);
4701                if (ri != null) {
4702                    return ri;
4703                }
4704                ri = new ResolveInfo(mResolveInfo);
4705                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4706                ri.activityInfo.applicationInfo = new ApplicationInfo(
4707                        ri.activityInfo.applicationInfo);
4708                if (userId != 0) {
4709                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4710                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4711                }
4712                // Make sure that the resolver is displayable in car mode
4713                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4714                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4715                return ri;
4716            }
4717        }
4718        return null;
4719    }
4720
4721    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4722            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4723        final int N = query.size();
4724        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4725                .get(userId);
4726        // Get the list of persistent preferred activities that handle the intent
4727        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4728        List<PersistentPreferredActivity> pprefs = ppir != null
4729                ? ppir.queryIntent(intent, resolvedType,
4730                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4731                : null;
4732        if (pprefs != null && pprefs.size() > 0) {
4733            final int M = pprefs.size();
4734            for (int i=0; i<M; i++) {
4735                final PersistentPreferredActivity ppa = pprefs.get(i);
4736                if (DEBUG_PREFERRED || debug) {
4737                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4738                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4739                            + "\n  component=" + ppa.mComponent);
4740                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4741                }
4742                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4743                        flags | MATCH_DISABLED_COMPONENTS, userId);
4744                if (DEBUG_PREFERRED || debug) {
4745                    Slog.v(TAG, "Found persistent preferred activity:");
4746                    if (ai != null) {
4747                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4748                    } else {
4749                        Slog.v(TAG, "  null");
4750                    }
4751                }
4752                if (ai == null) {
4753                    // This previously registered persistent preferred activity
4754                    // component is no longer known. Ignore it and do NOT remove it.
4755                    continue;
4756                }
4757                for (int j=0; j<N; j++) {
4758                    final ResolveInfo ri = query.get(j);
4759                    if (!ri.activityInfo.applicationInfo.packageName
4760                            .equals(ai.applicationInfo.packageName)) {
4761                        continue;
4762                    }
4763                    if (!ri.activityInfo.name.equals(ai.name)) {
4764                        continue;
4765                    }
4766                    //  Found a persistent preference that can handle the intent.
4767                    if (DEBUG_PREFERRED || debug) {
4768                        Slog.v(TAG, "Returning persistent preferred activity: " +
4769                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4770                    }
4771                    return ri;
4772                }
4773            }
4774        }
4775        return null;
4776    }
4777
4778    // TODO: handle preferred activities missing while user has amnesia
4779    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4780            List<ResolveInfo> query, int priority, boolean always,
4781            boolean removeMatches, boolean debug, int userId) {
4782        if (!sUserManager.exists(userId)) return null;
4783        flags = updateFlagsForResolve(flags, userId, intent);
4784        // writer
4785        synchronized (mPackages) {
4786            if (intent.getSelector() != null) {
4787                intent = intent.getSelector();
4788            }
4789            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4790
4791            // Try to find a matching persistent preferred activity.
4792            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4793                    debug, userId);
4794
4795            // If a persistent preferred activity matched, use it.
4796            if (pri != null) {
4797                return pri;
4798            }
4799
4800            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4801            // Get the list of preferred activities that handle the intent
4802            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4803            List<PreferredActivity> prefs = pir != null
4804                    ? pir.queryIntent(intent, resolvedType,
4805                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4806                    : null;
4807            if (prefs != null && prefs.size() > 0) {
4808                boolean changed = false;
4809                try {
4810                    // First figure out how good the original match set is.
4811                    // We will only allow preferred activities that came
4812                    // from the same match quality.
4813                    int match = 0;
4814
4815                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4816
4817                    final int N = query.size();
4818                    for (int j=0; j<N; j++) {
4819                        final ResolveInfo ri = query.get(j);
4820                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4821                                + ": 0x" + Integer.toHexString(match));
4822                        if (ri.match > match) {
4823                            match = ri.match;
4824                        }
4825                    }
4826
4827                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4828                            + Integer.toHexString(match));
4829
4830                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4831                    final int M = prefs.size();
4832                    for (int i=0; i<M; i++) {
4833                        final PreferredActivity pa = prefs.get(i);
4834                        if (DEBUG_PREFERRED || debug) {
4835                            Slog.v(TAG, "Checking PreferredActivity ds="
4836                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4837                                    + "\n  component=" + pa.mPref.mComponent);
4838                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4839                        }
4840                        if (pa.mPref.mMatch != match) {
4841                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4842                                    + Integer.toHexString(pa.mPref.mMatch));
4843                            continue;
4844                        }
4845                        // If it's not an "always" type preferred activity and that's what we're
4846                        // looking for, skip it.
4847                        if (always && !pa.mPref.mAlways) {
4848                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4849                            continue;
4850                        }
4851                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4852                                flags | MATCH_DISABLED_COMPONENTS, userId);
4853                        if (DEBUG_PREFERRED || debug) {
4854                            Slog.v(TAG, "Found preferred activity:");
4855                            if (ai != null) {
4856                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4857                            } else {
4858                                Slog.v(TAG, "  null");
4859                            }
4860                        }
4861                        if (ai == null) {
4862                            // This previously registered preferred activity
4863                            // component is no longer known.  Most likely an update
4864                            // to the app was installed and in the new version this
4865                            // component no longer exists.  Clean it up by removing
4866                            // it from the preferred activities list, and skip it.
4867                            Slog.w(TAG, "Removing dangling preferred activity: "
4868                                    + pa.mPref.mComponent);
4869                            pir.removeFilter(pa);
4870                            changed = true;
4871                            continue;
4872                        }
4873                        for (int j=0; j<N; j++) {
4874                            final ResolveInfo ri = query.get(j);
4875                            if (!ri.activityInfo.applicationInfo.packageName
4876                                    .equals(ai.applicationInfo.packageName)) {
4877                                continue;
4878                            }
4879                            if (!ri.activityInfo.name.equals(ai.name)) {
4880                                continue;
4881                            }
4882
4883                            if (removeMatches) {
4884                                pir.removeFilter(pa);
4885                                changed = true;
4886                                if (DEBUG_PREFERRED) {
4887                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4888                                }
4889                                break;
4890                            }
4891
4892                            // Okay we found a previously set preferred or last chosen app.
4893                            // If the result set is different from when this
4894                            // was created, we need to clear it and re-ask the
4895                            // user their preference, if we're looking for an "always" type entry.
4896                            if (always && !pa.mPref.sameSet(query)) {
4897                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4898                                        + intent + " type " + resolvedType);
4899                                if (DEBUG_PREFERRED) {
4900                                    Slog.v(TAG, "Removing preferred activity since set changed "
4901                                            + pa.mPref.mComponent);
4902                                }
4903                                pir.removeFilter(pa);
4904                                // Re-add the filter as a "last chosen" entry (!always)
4905                                PreferredActivity lastChosen = new PreferredActivity(
4906                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4907                                pir.addFilter(lastChosen);
4908                                changed = true;
4909                                return null;
4910                            }
4911
4912                            // Yay! Either the set matched or we're looking for the last chosen
4913                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4914                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4915                            return ri;
4916                        }
4917                    }
4918                } finally {
4919                    if (changed) {
4920                        if (DEBUG_PREFERRED) {
4921                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4922                        }
4923                        scheduleWritePackageRestrictionsLocked(userId);
4924                    }
4925                }
4926            }
4927        }
4928        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4929        return null;
4930    }
4931
4932    /*
4933     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4934     */
4935    @Override
4936    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4937            int targetUserId) {
4938        mContext.enforceCallingOrSelfPermission(
4939                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4940        List<CrossProfileIntentFilter> matches =
4941                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4942        if (matches != null) {
4943            int size = matches.size();
4944            for (int i = 0; i < size; i++) {
4945                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4946            }
4947        }
4948        if (hasWebURI(intent)) {
4949            // cross-profile app linking works only towards the parent.
4950            final UserInfo parent = getProfileParent(sourceUserId);
4951            synchronized(mPackages) {
4952                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4953                        intent, resolvedType, 0, sourceUserId, parent.id);
4954                return xpDomainInfo != null;
4955            }
4956        }
4957        return false;
4958    }
4959
4960    private UserInfo getProfileParent(int userId) {
4961        final long identity = Binder.clearCallingIdentity();
4962        try {
4963            return sUserManager.getProfileParent(userId);
4964        } finally {
4965            Binder.restoreCallingIdentity(identity);
4966        }
4967    }
4968
4969    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4970            String resolvedType, int userId) {
4971        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4972        if (resolver != null) {
4973            return resolver.queryIntent(intent, resolvedType, false, userId);
4974        }
4975        return null;
4976    }
4977
4978    @Override
4979    public List<ResolveInfo> queryIntentActivities(Intent intent,
4980            String resolvedType, int flags, int userId) {
4981        if (!sUserManager.exists(userId)) return Collections.emptyList();
4982        flags = updateFlagsForResolve(flags, userId, intent);
4983        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4984        ComponentName comp = intent.getComponent();
4985        if (comp == null) {
4986            if (intent.getSelector() != null) {
4987                intent = intent.getSelector();
4988                comp = intent.getComponent();
4989            }
4990        }
4991
4992        if (comp != null) {
4993            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4994            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4995            if (ai != null) {
4996                final ResolveInfo ri = new ResolveInfo();
4997                ri.activityInfo = ai;
4998                list.add(ri);
4999            }
5000            return list;
5001        }
5002
5003        // reader
5004        synchronized (mPackages) {
5005            final String pkgName = intent.getPackage();
5006            if (pkgName == null) {
5007                List<CrossProfileIntentFilter> matchingFilters =
5008                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5009                // Check for results that need to skip the current profile.
5010                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5011                        resolvedType, flags, userId);
5012                if (xpResolveInfo != null) {
5013                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5014                    result.add(xpResolveInfo);
5015                    return filterIfNotSystemUser(result, userId);
5016                }
5017
5018                // Check for results in the current profile.
5019                List<ResolveInfo> result = mActivities.queryIntent(
5020                        intent, resolvedType, flags, userId);
5021                result = filterIfNotSystemUser(result, userId);
5022
5023                // Check for cross profile results.
5024                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5025                xpResolveInfo = queryCrossProfileIntents(
5026                        matchingFilters, intent, resolvedType, flags, userId,
5027                        hasNonNegativePriorityResult);
5028                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5029                    boolean isVisibleToUser = filterIfNotSystemUser(
5030                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5031                    if (isVisibleToUser) {
5032                        result.add(xpResolveInfo);
5033                        Collections.sort(result, mResolvePrioritySorter);
5034                    }
5035                }
5036                if (hasWebURI(intent)) {
5037                    CrossProfileDomainInfo xpDomainInfo = null;
5038                    final UserInfo parent = getProfileParent(userId);
5039                    if (parent != null) {
5040                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5041                                flags, userId, parent.id);
5042                    }
5043                    if (xpDomainInfo != null) {
5044                        if (xpResolveInfo != null) {
5045                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5046                            // in the result.
5047                            result.remove(xpResolveInfo);
5048                        }
5049                        if (result.size() == 0) {
5050                            result.add(xpDomainInfo.resolveInfo);
5051                            return result;
5052                        }
5053                    } else if (result.size() <= 1) {
5054                        return result;
5055                    }
5056                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5057                            xpDomainInfo, userId);
5058                    Collections.sort(result, mResolvePrioritySorter);
5059                }
5060                return result;
5061            }
5062            final PackageParser.Package pkg = mPackages.get(pkgName);
5063            if (pkg != null) {
5064                return filterIfNotSystemUser(
5065                        mActivities.queryIntentForPackage(
5066                                intent, resolvedType, flags, pkg.activities, userId),
5067                        userId);
5068            }
5069            return new ArrayList<ResolveInfo>();
5070        }
5071    }
5072
5073    private static class CrossProfileDomainInfo {
5074        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5075        ResolveInfo resolveInfo;
5076        /* Best domain verification status of the activities found in the other profile */
5077        int bestDomainVerificationStatus;
5078    }
5079
5080    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5081            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5082        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5083                sourceUserId)) {
5084            return null;
5085        }
5086        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5087                resolvedType, flags, parentUserId);
5088
5089        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5090            return null;
5091        }
5092        CrossProfileDomainInfo result = null;
5093        int size = resultTargetUser.size();
5094        for (int i = 0; i < size; i++) {
5095            ResolveInfo riTargetUser = resultTargetUser.get(i);
5096            // Intent filter verification is only for filters that specify a host. So don't return
5097            // those that handle all web uris.
5098            if (riTargetUser.handleAllWebDataURI) {
5099                continue;
5100            }
5101            String packageName = riTargetUser.activityInfo.packageName;
5102            PackageSetting ps = mSettings.mPackages.get(packageName);
5103            if (ps == null) {
5104                continue;
5105            }
5106            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5107            int status = (int)(verificationState >> 32);
5108            if (result == null) {
5109                result = new CrossProfileDomainInfo();
5110                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5111                        sourceUserId, parentUserId);
5112                result.bestDomainVerificationStatus = status;
5113            } else {
5114                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5115                        result.bestDomainVerificationStatus);
5116            }
5117        }
5118        // Don't consider matches with status NEVER across profiles.
5119        if (result != null && result.bestDomainVerificationStatus
5120                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5121            return null;
5122        }
5123        return result;
5124    }
5125
5126    /**
5127     * Verification statuses are ordered from the worse to the best, except for
5128     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5129     */
5130    private int bestDomainVerificationStatus(int status1, int status2) {
5131        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5132            return status2;
5133        }
5134        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5135            return status1;
5136        }
5137        return (int) MathUtils.max(status1, status2);
5138    }
5139
5140    private boolean isUserEnabled(int userId) {
5141        long callingId = Binder.clearCallingIdentity();
5142        try {
5143            UserInfo userInfo = sUserManager.getUserInfo(userId);
5144            return userInfo != null && userInfo.isEnabled();
5145        } finally {
5146            Binder.restoreCallingIdentity(callingId);
5147        }
5148    }
5149
5150    /**
5151     * Filter out activities with systemUserOnly flag set, when current user is not System.
5152     *
5153     * @return filtered list
5154     */
5155    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5156        if (userId == UserHandle.USER_SYSTEM) {
5157            return resolveInfos;
5158        }
5159        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5160            ResolveInfo info = resolveInfos.get(i);
5161            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5162                resolveInfos.remove(i);
5163            }
5164        }
5165        return resolveInfos;
5166    }
5167
5168    /**
5169     * @param resolveInfos list of resolve infos in descending priority order
5170     * @return if the list contains a resolve info with non-negative priority
5171     */
5172    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5173        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5174    }
5175
5176    private static boolean hasWebURI(Intent intent) {
5177        if (intent.getData() == null) {
5178            return false;
5179        }
5180        final String scheme = intent.getScheme();
5181        if (TextUtils.isEmpty(scheme)) {
5182            return false;
5183        }
5184        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5185    }
5186
5187    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5188            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5189            int userId) {
5190        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5191
5192        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5193            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5194                    candidates.size());
5195        }
5196
5197        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5198        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5199        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5200        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5201        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5202        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5203
5204        synchronized (mPackages) {
5205            final int count = candidates.size();
5206            // First, try to use linked apps. Partition the candidates into four lists:
5207            // one for the final results, one for the "do not use ever", one for "undefined status"
5208            // and finally one for "browser app type".
5209            for (int n=0; n<count; n++) {
5210                ResolveInfo info = candidates.get(n);
5211                String packageName = info.activityInfo.packageName;
5212                PackageSetting ps = mSettings.mPackages.get(packageName);
5213                if (ps != null) {
5214                    // Add to the special match all list (Browser use case)
5215                    if (info.handleAllWebDataURI) {
5216                        matchAllList.add(info);
5217                        continue;
5218                    }
5219                    // Try to get the status from User settings first
5220                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5221                    int status = (int)(packedStatus >> 32);
5222                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5223                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5224                        if (DEBUG_DOMAIN_VERIFICATION) {
5225                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5226                                    + " : linkgen=" + linkGeneration);
5227                        }
5228                        // Use link-enabled generation as preferredOrder, i.e.
5229                        // prefer newly-enabled over earlier-enabled.
5230                        info.preferredOrder = linkGeneration;
5231                        alwaysList.add(info);
5232                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5233                        if (DEBUG_DOMAIN_VERIFICATION) {
5234                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5235                        }
5236                        neverList.add(info);
5237                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5238                        if (DEBUG_DOMAIN_VERIFICATION) {
5239                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5240                        }
5241                        alwaysAskList.add(info);
5242                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5243                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5244                        if (DEBUG_DOMAIN_VERIFICATION) {
5245                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5246                        }
5247                        undefinedList.add(info);
5248                    }
5249                }
5250            }
5251
5252            // We'll want to include browser possibilities in a few cases
5253            boolean includeBrowser = false;
5254
5255            // First try to add the "always" resolution(s) for the current user, if any
5256            if (alwaysList.size() > 0) {
5257                result.addAll(alwaysList);
5258            } else {
5259                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5260                result.addAll(undefinedList);
5261                // Maybe add one for the other profile.
5262                if (xpDomainInfo != null && (
5263                        xpDomainInfo.bestDomainVerificationStatus
5264                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5265                    result.add(xpDomainInfo.resolveInfo);
5266                }
5267                includeBrowser = true;
5268            }
5269
5270            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5271            // If there were 'always' entries their preferred order has been set, so we also
5272            // back that off to make the alternatives equivalent
5273            if (alwaysAskList.size() > 0) {
5274                for (ResolveInfo i : result) {
5275                    i.preferredOrder = 0;
5276                }
5277                result.addAll(alwaysAskList);
5278                includeBrowser = true;
5279            }
5280
5281            if (includeBrowser) {
5282                // Also add browsers (all of them or only the default one)
5283                if (DEBUG_DOMAIN_VERIFICATION) {
5284                    Slog.v(TAG, "   ...including browsers in candidate set");
5285                }
5286                if ((matchFlags & MATCH_ALL) != 0) {
5287                    result.addAll(matchAllList);
5288                } else {
5289                    // Browser/generic handling case.  If there's a default browser, go straight
5290                    // to that (but only if there is no other higher-priority match).
5291                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5292                    int maxMatchPrio = 0;
5293                    ResolveInfo defaultBrowserMatch = null;
5294                    final int numCandidates = matchAllList.size();
5295                    for (int n = 0; n < numCandidates; n++) {
5296                        ResolveInfo info = matchAllList.get(n);
5297                        // track the highest overall match priority...
5298                        if (info.priority > maxMatchPrio) {
5299                            maxMatchPrio = info.priority;
5300                        }
5301                        // ...and the highest-priority default browser match
5302                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5303                            if (defaultBrowserMatch == null
5304                                    || (defaultBrowserMatch.priority < info.priority)) {
5305                                if (debug) {
5306                                    Slog.v(TAG, "Considering default browser match " + info);
5307                                }
5308                                defaultBrowserMatch = info;
5309                            }
5310                        }
5311                    }
5312                    if (defaultBrowserMatch != null
5313                            && defaultBrowserMatch.priority >= maxMatchPrio
5314                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5315                    {
5316                        if (debug) {
5317                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5318                        }
5319                        result.add(defaultBrowserMatch);
5320                    } else {
5321                        result.addAll(matchAllList);
5322                    }
5323                }
5324
5325                // If there is nothing selected, add all candidates and remove the ones that the user
5326                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5327                if (result.size() == 0) {
5328                    result.addAll(candidates);
5329                    result.removeAll(neverList);
5330                }
5331            }
5332        }
5333        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5334            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5335                    result.size());
5336            for (ResolveInfo info : result) {
5337                Slog.v(TAG, "  + " + info.activityInfo);
5338            }
5339        }
5340        return result;
5341    }
5342
5343    // Returns a packed value as a long:
5344    //
5345    // high 'int'-sized word: link status: undefined/ask/never/always.
5346    // low 'int'-sized word: relative priority among 'always' results.
5347    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5348        long result = ps.getDomainVerificationStatusForUser(userId);
5349        // if none available, get the master status
5350        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5351            if (ps.getIntentFilterVerificationInfo() != null) {
5352                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5353            }
5354        }
5355        return result;
5356    }
5357
5358    private ResolveInfo querySkipCurrentProfileIntents(
5359            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5360            int flags, int sourceUserId) {
5361        if (matchingFilters != null) {
5362            int size = matchingFilters.size();
5363            for (int i = 0; i < size; i ++) {
5364                CrossProfileIntentFilter filter = matchingFilters.get(i);
5365                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5366                    // Checking if there are activities in the target user that can handle the
5367                    // intent.
5368                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5369                            resolvedType, flags, sourceUserId);
5370                    if (resolveInfo != null) {
5371                        return resolveInfo;
5372                    }
5373                }
5374            }
5375        }
5376        return null;
5377    }
5378
5379    // Return matching ResolveInfo in target user if any.
5380    private ResolveInfo queryCrossProfileIntents(
5381            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5382            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5383        if (matchingFilters != null) {
5384            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5385            // match the same intent. For performance reasons, it is better not to
5386            // run queryIntent twice for the same userId
5387            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5388            int size = matchingFilters.size();
5389            for (int i = 0; i < size; i++) {
5390                CrossProfileIntentFilter filter = matchingFilters.get(i);
5391                int targetUserId = filter.getTargetUserId();
5392                boolean skipCurrentProfile =
5393                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5394                boolean skipCurrentProfileIfNoMatchFound =
5395                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5396                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5397                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5398                    // Checking if there are activities in the target user that can handle the
5399                    // intent.
5400                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5401                            resolvedType, flags, sourceUserId);
5402                    if (resolveInfo != null) return resolveInfo;
5403                    alreadyTriedUserIds.put(targetUserId, true);
5404                }
5405            }
5406        }
5407        return null;
5408    }
5409
5410    /**
5411     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5412     * will forward the intent to the filter's target user.
5413     * Otherwise, returns null.
5414     */
5415    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5416            String resolvedType, int flags, int sourceUserId) {
5417        int targetUserId = filter.getTargetUserId();
5418        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5419                resolvedType, flags, targetUserId);
5420        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5421            // If all the matches in the target profile are suspended, return null.
5422            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5423                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5424                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5425                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5426                            targetUserId);
5427                }
5428            }
5429        }
5430        return null;
5431    }
5432
5433    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5434            int sourceUserId, int targetUserId) {
5435        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5436        long ident = Binder.clearCallingIdentity();
5437        boolean targetIsProfile;
5438        try {
5439            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5440        } finally {
5441            Binder.restoreCallingIdentity(ident);
5442        }
5443        String className;
5444        if (targetIsProfile) {
5445            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5446        } else {
5447            className = FORWARD_INTENT_TO_PARENT;
5448        }
5449        ComponentName forwardingActivityComponentName = new ComponentName(
5450                mAndroidApplication.packageName, className);
5451        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5452                sourceUserId);
5453        if (!targetIsProfile) {
5454            forwardingActivityInfo.showUserIcon = targetUserId;
5455            forwardingResolveInfo.noResourceId = true;
5456        }
5457        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5458        forwardingResolveInfo.priority = 0;
5459        forwardingResolveInfo.preferredOrder = 0;
5460        forwardingResolveInfo.match = 0;
5461        forwardingResolveInfo.isDefault = true;
5462        forwardingResolveInfo.filter = filter;
5463        forwardingResolveInfo.targetUserId = targetUserId;
5464        return forwardingResolveInfo;
5465    }
5466
5467    @Override
5468    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5469            Intent[] specifics, String[] specificTypes, Intent intent,
5470            String resolvedType, int flags, int userId) {
5471        if (!sUserManager.exists(userId)) return Collections.emptyList();
5472        flags = updateFlagsForResolve(flags, userId, intent);
5473        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5474                false, "query intent activity options");
5475        final String resultsAction = intent.getAction();
5476
5477        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5478                | PackageManager.GET_RESOLVED_FILTER, userId);
5479
5480        if (DEBUG_INTENT_MATCHING) {
5481            Log.v(TAG, "Query " + intent + ": " + results);
5482        }
5483
5484        int specificsPos = 0;
5485        int N;
5486
5487        // todo: note that the algorithm used here is O(N^2).  This
5488        // isn't a problem in our current environment, but if we start running
5489        // into situations where we have more than 5 or 10 matches then this
5490        // should probably be changed to something smarter...
5491
5492        // First we go through and resolve each of the specific items
5493        // that were supplied, taking care of removing any corresponding
5494        // duplicate items in the generic resolve list.
5495        if (specifics != null) {
5496            for (int i=0; i<specifics.length; i++) {
5497                final Intent sintent = specifics[i];
5498                if (sintent == null) {
5499                    continue;
5500                }
5501
5502                if (DEBUG_INTENT_MATCHING) {
5503                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5504                }
5505
5506                String action = sintent.getAction();
5507                if (resultsAction != null && resultsAction.equals(action)) {
5508                    // If this action was explicitly requested, then don't
5509                    // remove things that have it.
5510                    action = null;
5511                }
5512
5513                ResolveInfo ri = null;
5514                ActivityInfo ai = null;
5515
5516                ComponentName comp = sintent.getComponent();
5517                if (comp == null) {
5518                    ri = resolveIntent(
5519                        sintent,
5520                        specificTypes != null ? specificTypes[i] : null,
5521                            flags, userId);
5522                    if (ri == null) {
5523                        continue;
5524                    }
5525                    if (ri == mResolveInfo) {
5526                        // ACK!  Must do something better with this.
5527                    }
5528                    ai = ri.activityInfo;
5529                    comp = new ComponentName(ai.applicationInfo.packageName,
5530                            ai.name);
5531                } else {
5532                    ai = getActivityInfo(comp, flags, userId);
5533                    if (ai == null) {
5534                        continue;
5535                    }
5536                }
5537
5538                // Look for any generic query activities that are duplicates
5539                // of this specific one, and remove them from the results.
5540                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5541                N = results.size();
5542                int j;
5543                for (j=specificsPos; j<N; j++) {
5544                    ResolveInfo sri = results.get(j);
5545                    if ((sri.activityInfo.name.equals(comp.getClassName())
5546                            && sri.activityInfo.applicationInfo.packageName.equals(
5547                                    comp.getPackageName()))
5548                        || (action != null && sri.filter.matchAction(action))) {
5549                        results.remove(j);
5550                        if (DEBUG_INTENT_MATCHING) Log.v(
5551                            TAG, "Removing duplicate item from " + j
5552                            + " due to specific " + specificsPos);
5553                        if (ri == null) {
5554                            ri = sri;
5555                        }
5556                        j--;
5557                        N--;
5558                    }
5559                }
5560
5561                // Add this specific item to its proper place.
5562                if (ri == null) {
5563                    ri = new ResolveInfo();
5564                    ri.activityInfo = ai;
5565                }
5566                results.add(specificsPos, ri);
5567                ri.specificIndex = i;
5568                specificsPos++;
5569            }
5570        }
5571
5572        // Now we go through the remaining generic results and remove any
5573        // duplicate actions that are found here.
5574        N = results.size();
5575        for (int i=specificsPos; i<N-1; i++) {
5576            final ResolveInfo rii = results.get(i);
5577            if (rii.filter == null) {
5578                continue;
5579            }
5580
5581            // Iterate over all of the actions of this result's intent
5582            // filter...  typically this should be just one.
5583            final Iterator<String> it = rii.filter.actionsIterator();
5584            if (it == null) {
5585                continue;
5586            }
5587            while (it.hasNext()) {
5588                final String action = it.next();
5589                if (resultsAction != null && resultsAction.equals(action)) {
5590                    // If this action was explicitly requested, then don't
5591                    // remove things that have it.
5592                    continue;
5593                }
5594                for (int j=i+1; j<N; j++) {
5595                    final ResolveInfo rij = results.get(j);
5596                    if (rij.filter != null && rij.filter.hasAction(action)) {
5597                        results.remove(j);
5598                        if (DEBUG_INTENT_MATCHING) Log.v(
5599                            TAG, "Removing duplicate item from " + j
5600                            + " due to action " + action + " at " + i);
5601                        j--;
5602                        N--;
5603                    }
5604                }
5605            }
5606
5607            // If the caller didn't request filter information, drop it now
5608            // so we don't have to marshall/unmarshall it.
5609            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5610                rii.filter = null;
5611            }
5612        }
5613
5614        // Filter out the caller activity if so requested.
5615        if (caller != null) {
5616            N = results.size();
5617            for (int i=0; i<N; i++) {
5618                ActivityInfo ainfo = results.get(i).activityInfo;
5619                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5620                        && caller.getClassName().equals(ainfo.name)) {
5621                    results.remove(i);
5622                    break;
5623                }
5624            }
5625        }
5626
5627        // If the caller didn't request filter information,
5628        // drop them now so we don't have to
5629        // marshall/unmarshall it.
5630        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5631            N = results.size();
5632            for (int i=0; i<N; i++) {
5633                results.get(i).filter = null;
5634            }
5635        }
5636
5637        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5638        return results;
5639    }
5640
5641    @Override
5642    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5643            int userId) {
5644        if (!sUserManager.exists(userId)) return Collections.emptyList();
5645        flags = updateFlagsForResolve(flags, userId, intent);
5646        ComponentName comp = intent.getComponent();
5647        if (comp == null) {
5648            if (intent.getSelector() != null) {
5649                intent = intent.getSelector();
5650                comp = intent.getComponent();
5651            }
5652        }
5653        if (comp != null) {
5654            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5655            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5656            if (ai != null) {
5657                ResolveInfo ri = new ResolveInfo();
5658                ri.activityInfo = ai;
5659                list.add(ri);
5660            }
5661            return list;
5662        }
5663
5664        // reader
5665        synchronized (mPackages) {
5666            String pkgName = intent.getPackage();
5667            if (pkgName == null) {
5668                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5669            }
5670            final PackageParser.Package pkg = mPackages.get(pkgName);
5671            if (pkg != null) {
5672                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5673                        userId);
5674            }
5675            return null;
5676        }
5677    }
5678
5679    @Override
5680    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5681        if (!sUserManager.exists(userId)) return null;
5682        flags = updateFlagsForResolve(flags, userId, intent);
5683        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5684        if (query != null) {
5685            if (query.size() >= 1) {
5686                // If there is more than one service with the same priority,
5687                // just arbitrarily pick the first one.
5688                return query.get(0);
5689            }
5690        }
5691        return null;
5692    }
5693
5694    @Override
5695    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5696            int userId) {
5697        if (!sUserManager.exists(userId)) return Collections.emptyList();
5698        flags = updateFlagsForResolve(flags, userId, intent);
5699        ComponentName comp = intent.getComponent();
5700        if (comp == null) {
5701            if (intent.getSelector() != null) {
5702                intent = intent.getSelector();
5703                comp = intent.getComponent();
5704            }
5705        }
5706        if (comp != null) {
5707            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5708            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5709            if (si != null) {
5710                final ResolveInfo ri = new ResolveInfo();
5711                ri.serviceInfo = si;
5712                list.add(ri);
5713            }
5714            return list;
5715        }
5716
5717        // reader
5718        synchronized (mPackages) {
5719            String pkgName = intent.getPackage();
5720            if (pkgName == null) {
5721                return mServices.queryIntent(intent, resolvedType, flags, userId);
5722            }
5723            final PackageParser.Package pkg = mPackages.get(pkgName);
5724            if (pkg != null) {
5725                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5726                        userId);
5727            }
5728            return null;
5729        }
5730    }
5731
5732    @Override
5733    public List<ResolveInfo> queryIntentContentProviders(
5734            Intent intent, String resolvedType, int flags, int userId) {
5735        if (!sUserManager.exists(userId)) return Collections.emptyList();
5736        flags = updateFlagsForResolve(flags, userId, intent);
5737        ComponentName comp = intent.getComponent();
5738        if (comp == null) {
5739            if (intent.getSelector() != null) {
5740                intent = intent.getSelector();
5741                comp = intent.getComponent();
5742            }
5743        }
5744        if (comp != null) {
5745            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5746            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5747            if (pi != null) {
5748                final ResolveInfo ri = new ResolveInfo();
5749                ri.providerInfo = pi;
5750                list.add(ri);
5751            }
5752            return list;
5753        }
5754
5755        // reader
5756        synchronized (mPackages) {
5757            String pkgName = intent.getPackage();
5758            if (pkgName == null) {
5759                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5760            }
5761            final PackageParser.Package pkg = mPackages.get(pkgName);
5762            if (pkg != null) {
5763                return mProviders.queryIntentForPackage(
5764                        intent, resolvedType, flags, pkg.providers, userId);
5765            }
5766            return null;
5767        }
5768    }
5769
5770    @Override
5771    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5772        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5773        flags = updateFlagsForPackage(flags, userId, null);
5774        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5775        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5776
5777        // writer
5778        synchronized (mPackages) {
5779            ArrayList<PackageInfo> list;
5780            if (listUninstalled) {
5781                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5782                for (PackageSetting ps : mSettings.mPackages.values()) {
5783                    PackageInfo pi;
5784                    if (ps.pkg != null) {
5785                        pi = generatePackageInfo(ps.pkg, flags, userId);
5786                    } else {
5787                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5788                    }
5789                    if (pi != null) {
5790                        list.add(pi);
5791                    }
5792                }
5793            } else {
5794                list = new ArrayList<PackageInfo>(mPackages.size());
5795                for (PackageParser.Package p : mPackages.values()) {
5796                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5797                    if (pi != null) {
5798                        list.add(pi);
5799                    }
5800                }
5801            }
5802
5803            return new ParceledListSlice<PackageInfo>(list);
5804        }
5805    }
5806
5807    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5808            String[] permissions, boolean[] tmp, int flags, int userId) {
5809        int numMatch = 0;
5810        final PermissionsState permissionsState = ps.getPermissionsState();
5811        for (int i=0; i<permissions.length; i++) {
5812            final String permission = permissions[i];
5813            if (permissionsState.hasPermission(permission, userId)) {
5814                tmp[i] = true;
5815                numMatch++;
5816            } else {
5817                tmp[i] = false;
5818            }
5819        }
5820        if (numMatch == 0) {
5821            return;
5822        }
5823        PackageInfo pi;
5824        if (ps.pkg != null) {
5825            pi = generatePackageInfo(ps.pkg, flags, userId);
5826        } else {
5827            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5828        }
5829        // The above might return null in cases of uninstalled apps or install-state
5830        // skew across users/profiles.
5831        if (pi != null) {
5832            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5833                if (numMatch == permissions.length) {
5834                    pi.requestedPermissions = permissions;
5835                } else {
5836                    pi.requestedPermissions = new String[numMatch];
5837                    numMatch = 0;
5838                    for (int i=0; i<permissions.length; i++) {
5839                        if (tmp[i]) {
5840                            pi.requestedPermissions[numMatch] = permissions[i];
5841                            numMatch++;
5842                        }
5843                    }
5844                }
5845            }
5846            list.add(pi);
5847        }
5848    }
5849
5850    @Override
5851    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5852            String[] permissions, int flags, int userId) {
5853        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5854        flags = updateFlagsForPackage(flags, userId, permissions);
5855        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5856
5857        // writer
5858        synchronized (mPackages) {
5859            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5860            boolean[] tmpBools = new boolean[permissions.length];
5861            if (listUninstalled) {
5862                for (PackageSetting ps : mSettings.mPackages.values()) {
5863                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5864                }
5865            } else {
5866                for (PackageParser.Package pkg : mPackages.values()) {
5867                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5868                    if (ps != null) {
5869                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5870                                userId);
5871                    }
5872                }
5873            }
5874
5875            return new ParceledListSlice<PackageInfo>(list);
5876        }
5877    }
5878
5879    @Override
5880    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5881        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5882        flags = updateFlagsForApplication(flags, userId, null);
5883        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5884
5885        // writer
5886        synchronized (mPackages) {
5887            ArrayList<ApplicationInfo> list;
5888            if (listUninstalled) {
5889                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5890                for (PackageSetting ps : mSettings.mPackages.values()) {
5891                    ApplicationInfo ai;
5892                    if (ps.pkg != null) {
5893                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5894                                ps.readUserState(userId), userId);
5895                    } else {
5896                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5897                    }
5898                    if (ai != null) {
5899                        list.add(ai);
5900                    }
5901                }
5902            } else {
5903                list = new ArrayList<ApplicationInfo>(mPackages.size());
5904                for (PackageParser.Package p : mPackages.values()) {
5905                    if (p.mExtras != null) {
5906                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5907                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5908                        if (ai != null) {
5909                            list.add(ai);
5910                        }
5911                    }
5912                }
5913            }
5914
5915            return new ParceledListSlice<ApplicationInfo>(list);
5916        }
5917    }
5918
5919    @Override
5920    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5921        if (DISABLE_EPHEMERAL_APPS) {
5922            return null;
5923        }
5924
5925        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5926                "getEphemeralApplications");
5927        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5928                "getEphemeralApplications");
5929        synchronized (mPackages) {
5930            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5931                    .getEphemeralApplicationsLPw(userId);
5932            if (ephemeralApps != null) {
5933                return new ParceledListSlice<>(ephemeralApps);
5934            }
5935        }
5936        return null;
5937    }
5938
5939    @Override
5940    public boolean isEphemeralApplication(String packageName, int userId) {
5941        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5942                "isEphemeral");
5943        if (DISABLE_EPHEMERAL_APPS) {
5944            return false;
5945        }
5946
5947        if (!isCallerSameApp(packageName)) {
5948            return false;
5949        }
5950        synchronized (mPackages) {
5951            PackageParser.Package pkg = mPackages.get(packageName);
5952            if (pkg != null) {
5953                return pkg.applicationInfo.isEphemeralApp();
5954            }
5955        }
5956        return false;
5957    }
5958
5959    @Override
5960    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5961        if (DISABLE_EPHEMERAL_APPS) {
5962            return null;
5963        }
5964
5965        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5966                "getCookie");
5967        if (!isCallerSameApp(packageName)) {
5968            return null;
5969        }
5970        synchronized (mPackages) {
5971            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5972                    packageName, userId);
5973        }
5974    }
5975
5976    @Override
5977    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5978        if (DISABLE_EPHEMERAL_APPS) {
5979            return true;
5980        }
5981
5982        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5983                "setCookie");
5984        if (!isCallerSameApp(packageName)) {
5985            return false;
5986        }
5987        synchronized (mPackages) {
5988            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5989                    packageName, cookie, userId);
5990        }
5991    }
5992
5993    @Override
5994    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5995        if (DISABLE_EPHEMERAL_APPS) {
5996            return null;
5997        }
5998
5999        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6000                "getEphemeralApplicationIcon");
6001        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6002                "getEphemeralApplicationIcon");
6003        synchronized (mPackages) {
6004            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6005                    packageName, userId);
6006        }
6007    }
6008
6009    private boolean isCallerSameApp(String packageName) {
6010        PackageParser.Package pkg = mPackages.get(packageName);
6011        return pkg != null
6012                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6013    }
6014
6015    public List<ApplicationInfo> getPersistentApplications(int flags) {
6016        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6017
6018        // reader
6019        synchronized (mPackages) {
6020            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6021            final int userId = UserHandle.getCallingUserId();
6022            while (i.hasNext()) {
6023                final PackageParser.Package p = i.next();
6024                if (p.applicationInfo != null
6025                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6026                        && (!mSafeMode || isSystemApp(p))) {
6027                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6028                    if (ps != null) {
6029                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6030                                ps.readUserState(userId), userId);
6031                        if (ai != null) {
6032                            finalList.add(ai);
6033                        }
6034                    }
6035                }
6036            }
6037        }
6038
6039        return finalList;
6040    }
6041
6042    @Override
6043    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6044        if (!sUserManager.exists(userId)) return null;
6045        flags = updateFlagsForComponent(flags, userId, name);
6046        // reader
6047        synchronized (mPackages) {
6048            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6049            PackageSetting ps = provider != null
6050                    ? mSettings.mPackages.get(provider.owner.packageName)
6051                    : null;
6052            return ps != null
6053                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6054                    ? PackageParser.generateProviderInfo(provider, flags,
6055                            ps.readUserState(userId), userId)
6056                    : null;
6057        }
6058    }
6059
6060    /**
6061     * @deprecated
6062     */
6063    @Deprecated
6064    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6065        // reader
6066        synchronized (mPackages) {
6067            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6068                    .entrySet().iterator();
6069            final int userId = UserHandle.getCallingUserId();
6070            while (i.hasNext()) {
6071                Map.Entry<String, PackageParser.Provider> entry = i.next();
6072                PackageParser.Provider p = entry.getValue();
6073                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6074
6075                if (ps != null && p.syncable
6076                        && (!mSafeMode || (p.info.applicationInfo.flags
6077                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6078                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6079                            ps.readUserState(userId), userId);
6080                    if (info != null) {
6081                        outNames.add(entry.getKey());
6082                        outInfo.add(info);
6083                    }
6084                }
6085            }
6086        }
6087    }
6088
6089    @Override
6090    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6091            int uid, int flags) {
6092        final int userId = processName != null ? UserHandle.getUserId(uid)
6093                : UserHandle.getCallingUserId();
6094        if (!sUserManager.exists(userId)) return null;
6095        flags = updateFlagsForComponent(flags, userId, processName);
6096
6097        ArrayList<ProviderInfo> finalList = null;
6098        // reader
6099        synchronized (mPackages) {
6100            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6101            while (i.hasNext()) {
6102                final PackageParser.Provider p = i.next();
6103                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6104                if (ps != null && p.info.authority != null
6105                        && (processName == null
6106                                || (p.info.processName.equals(processName)
6107                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6108                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6109                    if (finalList == null) {
6110                        finalList = new ArrayList<ProviderInfo>(3);
6111                    }
6112                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6113                            ps.readUserState(userId), userId);
6114                    if (info != null) {
6115                        finalList.add(info);
6116                    }
6117                }
6118            }
6119        }
6120
6121        if (finalList != null) {
6122            Collections.sort(finalList, mProviderInitOrderSorter);
6123            return new ParceledListSlice<ProviderInfo>(finalList);
6124        }
6125
6126        return null;
6127    }
6128
6129    @Override
6130    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6131        // reader
6132        synchronized (mPackages) {
6133            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6134            return PackageParser.generateInstrumentationInfo(i, flags);
6135        }
6136    }
6137
6138    @Override
6139    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6140            int flags) {
6141        ArrayList<InstrumentationInfo> finalList =
6142            new ArrayList<InstrumentationInfo>();
6143
6144        // reader
6145        synchronized (mPackages) {
6146            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6147            while (i.hasNext()) {
6148                final PackageParser.Instrumentation p = i.next();
6149                if (targetPackage == null
6150                        || targetPackage.equals(p.info.targetPackage)) {
6151                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6152                            flags);
6153                    if (ii != null) {
6154                        finalList.add(ii);
6155                    }
6156                }
6157            }
6158        }
6159
6160        return finalList;
6161    }
6162
6163    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6164        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6165        if (overlays == null) {
6166            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6167            return;
6168        }
6169        for (PackageParser.Package opkg : overlays.values()) {
6170            // Not much to do if idmap fails: we already logged the error
6171            // and we certainly don't want to abort installation of pkg simply
6172            // because an overlay didn't fit properly. For these reasons,
6173            // ignore the return value of createIdmapForPackagePairLI.
6174            createIdmapForPackagePairLI(pkg, opkg);
6175        }
6176    }
6177
6178    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6179            PackageParser.Package opkg) {
6180        if (!opkg.mTrustedOverlay) {
6181            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6182                    opkg.baseCodePath + ": overlay not trusted");
6183            return false;
6184        }
6185        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6186        if (overlaySet == null) {
6187            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6188                    opkg.baseCodePath + " but target package has no known overlays");
6189            return false;
6190        }
6191        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6192        // TODO: generate idmap for split APKs
6193        try {
6194            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6195        } catch (InstallerException e) {
6196            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6197                    + opkg.baseCodePath);
6198            return false;
6199        }
6200        PackageParser.Package[] overlayArray =
6201            overlaySet.values().toArray(new PackageParser.Package[0]);
6202        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6203            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6204                return p1.mOverlayPriority - p2.mOverlayPriority;
6205            }
6206        };
6207        Arrays.sort(overlayArray, cmp);
6208
6209        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6210        int i = 0;
6211        for (PackageParser.Package p : overlayArray) {
6212            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6213        }
6214        return true;
6215    }
6216
6217    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6219        try {
6220            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6221        } finally {
6222            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6223        }
6224    }
6225
6226    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6227        final File[] files = dir.listFiles();
6228        if (ArrayUtils.isEmpty(files)) {
6229            Log.d(TAG, "No files in app dir " + dir);
6230            return;
6231        }
6232
6233        if (DEBUG_PACKAGE_SCANNING) {
6234            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6235                    + " flags=0x" + Integer.toHexString(parseFlags));
6236        }
6237
6238        for (File file : files) {
6239            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6240                    && !PackageInstallerService.isStageName(file.getName());
6241            if (!isPackage) {
6242                // Ignore entries which are not packages
6243                continue;
6244            }
6245            try {
6246                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6247                        scanFlags, currentTime, null);
6248            } catch (PackageManagerException e) {
6249                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6250
6251                // Delete invalid userdata apps
6252                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6253                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6254                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6255                    removeCodePathLI(file);
6256                }
6257            }
6258        }
6259    }
6260
6261    private static File getSettingsProblemFile() {
6262        File dataDir = Environment.getDataDirectory();
6263        File systemDir = new File(dataDir, "system");
6264        File fname = new File(systemDir, "uiderrors.txt");
6265        return fname;
6266    }
6267
6268    static void reportSettingsProblem(int priority, String msg) {
6269        logCriticalInfo(priority, msg);
6270    }
6271
6272    static void logCriticalInfo(int priority, String msg) {
6273        Slog.println(priority, TAG, msg);
6274        EventLogTags.writePmCriticalInfo(msg);
6275        try {
6276            File fname = getSettingsProblemFile();
6277            FileOutputStream out = new FileOutputStream(fname, true);
6278            PrintWriter pw = new FastPrintWriter(out);
6279            SimpleDateFormat formatter = new SimpleDateFormat();
6280            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6281            pw.println(dateString + ": " + msg);
6282            pw.close();
6283            FileUtils.setPermissions(
6284                    fname.toString(),
6285                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6286                    -1, -1);
6287        } catch (java.io.IOException e) {
6288        }
6289    }
6290
6291    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6292            int parseFlags) throws PackageManagerException {
6293        if (ps != null
6294                && ps.codePath.equals(srcFile)
6295                && ps.timeStamp == srcFile.lastModified()
6296                && !isCompatSignatureUpdateNeeded(pkg)
6297                && !isRecoverSignatureUpdateNeeded(pkg)) {
6298            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6299            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6300            ArraySet<PublicKey> signingKs;
6301            synchronized (mPackages) {
6302                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6303            }
6304            if (ps.signatures.mSignatures != null
6305                    && ps.signatures.mSignatures.length != 0
6306                    && signingKs != null) {
6307                // Optimization: reuse the existing cached certificates
6308                // if the package appears to be unchanged.
6309                pkg.mSignatures = ps.signatures.mSignatures;
6310                pkg.mSigningKeys = signingKs;
6311                return;
6312            }
6313
6314            Slog.w(TAG, "PackageSetting for " + ps.name
6315                    + " is missing signatures.  Collecting certs again to recover them.");
6316        } else {
6317            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6318        }
6319
6320        try {
6321            PackageParser.collectCertificates(pkg, parseFlags);
6322        } catch (PackageParserException e) {
6323            throw PackageManagerException.from(e);
6324        }
6325    }
6326
6327    /**
6328     *  Traces a package scan.
6329     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6330     */
6331    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6332            long currentTime, UserHandle user) throws PackageManagerException {
6333        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6334        try {
6335            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6336        } finally {
6337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6338        }
6339    }
6340
6341    /**
6342     *  Scans a package and returns the newly parsed package.
6343     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6344     */
6345    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6346            long currentTime, UserHandle user) throws PackageManagerException {
6347        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6348        parseFlags |= mDefParseFlags;
6349        PackageParser pp = new PackageParser();
6350        pp.setSeparateProcesses(mSeparateProcesses);
6351        pp.setOnlyCoreApps(mOnlyCore);
6352        pp.setDisplayMetrics(mMetrics);
6353
6354        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6355            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6356        }
6357
6358        final PackageParser.Package pkg;
6359        try {
6360            pkg = pp.parsePackage(scanFile, parseFlags);
6361        } catch (PackageParserException e) {
6362            throw PackageManagerException.from(e);
6363        }
6364
6365        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6366    }
6367
6368    /**
6369     *  Scans a package and returns the newly parsed package.
6370     *  @throws PackageManagerException on a parse error.
6371     */
6372    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6373            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6374            throws PackageManagerException {
6375        // If the package has children and this is the first dive in the function
6376        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6377        // packages (parent and children) would be successfully scanned before the
6378        // actual scan since scanning mutates internal state and we want to atomically
6379        // install the package and its children.
6380        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6381            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6382                scanFlags |= SCAN_CHECK_ONLY;
6383            }
6384        } else {
6385            scanFlags &= ~SCAN_CHECK_ONLY;
6386        }
6387
6388        // Scan the parent
6389        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6390                scanFlags, currentTime, user);
6391
6392        // Scan the children
6393        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6394        for (int i = 0; i < childCount; i++) {
6395            PackageParser.Package childPackage = pkg.childPackages.get(i);
6396            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6397                    currentTime, user);
6398        }
6399
6400
6401        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6402            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6403        }
6404
6405        return scannedPkg;
6406    }
6407
6408    /**
6409     *  Scans a package and returns the newly parsed package.
6410     *  @throws PackageManagerException on a parse error.
6411     */
6412    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6413            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6414            throws PackageManagerException {
6415        PackageSetting ps = null;
6416        PackageSetting updatedPkg;
6417        // reader
6418        synchronized (mPackages) {
6419            // Look to see if we already know about this package.
6420            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6421            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6422                // This package has been renamed to its original name.  Let's
6423                // use that.
6424                ps = mSettings.peekPackageLPr(oldName);
6425            }
6426            // If there was no original package, see one for the real package name.
6427            if (ps == null) {
6428                ps = mSettings.peekPackageLPr(pkg.packageName);
6429            }
6430            // Check to see if this package could be hiding/updating a system
6431            // package.  Must look for it either under the original or real
6432            // package name depending on our state.
6433            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6434            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6435
6436            // If this is a package we don't know about on the system partition, we
6437            // may need to remove disabled child packages on the system partition
6438            // or may need to not add child packages if the parent apk is updated
6439            // on the data partition and no longer defines this child package.
6440            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6441                // If this is a parent package for an updated system app and this system
6442                // app got an OTA update which no longer defines some of the child packages
6443                // we have to prune them from the disabled system packages.
6444                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6445                if (disabledPs != null) {
6446                    final int scannedChildCount = (pkg.childPackages != null)
6447                            ? pkg.childPackages.size() : 0;
6448                    final int disabledChildCount = disabledPs.childPackageNames != null
6449                            ? disabledPs.childPackageNames.size() : 0;
6450                    for (int i = 0; i < disabledChildCount; i++) {
6451                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6452                        boolean disabledPackageAvailable = false;
6453                        for (int j = 0; j < scannedChildCount; j++) {
6454                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6455                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6456                                disabledPackageAvailable = true;
6457                                break;
6458                            }
6459                         }
6460                         if (!disabledPackageAvailable) {
6461                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6462                         }
6463                    }
6464                }
6465            }
6466        }
6467
6468        boolean updatedPkgBetter = false;
6469        // First check if this is a system package that may involve an update
6470        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6471            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6472            // it needs to drop FLAG_PRIVILEGED.
6473            if (locationIsPrivileged(scanFile)) {
6474                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6475            } else {
6476                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6477            }
6478
6479            if (ps != null && !ps.codePath.equals(scanFile)) {
6480                // The path has changed from what was last scanned...  check the
6481                // version of the new path against what we have stored to determine
6482                // what to do.
6483                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6484                if (pkg.mVersionCode <= ps.versionCode) {
6485                    // The system package has been updated and the code path does not match
6486                    // Ignore entry. Skip it.
6487                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6488                            + " ignored: updated version " + ps.versionCode
6489                            + " better than this " + pkg.mVersionCode);
6490                    if (!updatedPkg.codePath.equals(scanFile)) {
6491                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6492                                + ps.name + " changing from " + updatedPkg.codePathString
6493                                + " to " + scanFile);
6494                        updatedPkg.codePath = scanFile;
6495                        updatedPkg.codePathString = scanFile.toString();
6496                        updatedPkg.resourcePath = scanFile;
6497                        updatedPkg.resourcePathString = scanFile.toString();
6498                    }
6499                    updatedPkg.pkg = pkg;
6500                    updatedPkg.versionCode = pkg.mVersionCode;
6501
6502                    // Update the disabled system child packages to point to the package too.
6503                    final int childCount = updatedPkg.childPackageNames != null
6504                            ? updatedPkg.childPackageNames.size() : 0;
6505                    for (int i = 0; i < childCount; i++) {
6506                        String childPackageName = updatedPkg.childPackageNames.get(i);
6507                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6508                                childPackageName);
6509                        if (updatedChildPkg != null) {
6510                            updatedChildPkg.pkg = pkg;
6511                            updatedChildPkg.versionCode = pkg.mVersionCode;
6512                        }
6513                    }
6514
6515                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6516                            + scanFile + " ignored: updated version " + ps.versionCode
6517                            + " better than this " + pkg.mVersionCode);
6518                } else {
6519                    // The current app on the system partition is better than
6520                    // what we have updated to on the data partition; switch
6521                    // back to the system partition version.
6522                    // At this point, its safely assumed that package installation for
6523                    // apps in system partition will go through. If not there won't be a working
6524                    // version of the app
6525                    // writer
6526                    synchronized (mPackages) {
6527                        // Just remove the loaded entries from package lists.
6528                        mPackages.remove(ps.name);
6529                    }
6530
6531                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6532                            + " reverting from " + ps.codePathString
6533                            + ": new version " + pkg.mVersionCode
6534                            + " better than installed " + ps.versionCode);
6535
6536                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6537                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6538                    synchronized (mInstallLock) {
6539                        args.cleanUpResourcesLI();
6540                    }
6541                    synchronized (mPackages) {
6542                        mSettings.enableSystemPackageLPw(ps.name);
6543                    }
6544                    updatedPkgBetter = true;
6545                }
6546            }
6547        }
6548
6549        if (updatedPkg != null) {
6550            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6551            // initially
6552            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6553
6554            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6555            // flag set initially
6556            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6557                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6558            }
6559        }
6560
6561        // Verify certificates against what was last scanned
6562        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6563
6564        /*
6565         * A new system app appeared, but we already had a non-system one of the
6566         * same name installed earlier.
6567         */
6568        boolean shouldHideSystemApp = false;
6569        if (updatedPkg == null && ps != null
6570                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6571            /*
6572             * Check to make sure the signatures match first. If they don't,
6573             * wipe the installed application and its data.
6574             */
6575            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6576                    != PackageManager.SIGNATURE_MATCH) {
6577                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6578                        + " signatures don't match existing userdata copy; removing");
6579                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null);
6580                ps = null;
6581            } else {
6582                /*
6583                 * If the newly-added system app is an older version than the
6584                 * already installed version, hide it. It will be scanned later
6585                 * and re-added like an update.
6586                 */
6587                if (pkg.mVersionCode <= ps.versionCode) {
6588                    shouldHideSystemApp = true;
6589                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6590                            + " but new version " + pkg.mVersionCode + " better than installed "
6591                            + ps.versionCode + "; hiding system");
6592                } else {
6593                    /*
6594                     * The newly found system app is a newer version that the
6595                     * one previously installed. Simply remove the
6596                     * already-installed application and replace it with our own
6597                     * while keeping the application data.
6598                     */
6599                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6600                            + " reverting from " + ps.codePathString + ": new version "
6601                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6602                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6603                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6604                    synchronized (mInstallLock) {
6605                        args.cleanUpResourcesLI();
6606                    }
6607                }
6608            }
6609        }
6610
6611        // The apk is forward locked (not public) if its code and resources
6612        // are kept in different files. (except for app in either system or
6613        // vendor path).
6614        // TODO grab this value from PackageSettings
6615        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6616            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6617                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6618            }
6619        }
6620
6621        // TODO: extend to support forward-locked splits
6622        String resourcePath = null;
6623        String baseResourcePath = null;
6624        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6625            if (ps != null && ps.resourcePathString != null) {
6626                resourcePath = ps.resourcePathString;
6627                baseResourcePath = ps.resourcePathString;
6628            } else {
6629                // Should not happen at all. Just log an error.
6630                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6631            }
6632        } else {
6633            resourcePath = pkg.codePath;
6634            baseResourcePath = pkg.baseCodePath;
6635        }
6636
6637        // Set application objects path explicitly.
6638        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6639        pkg.setApplicationInfoCodePath(pkg.codePath);
6640        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6641        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6642        pkg.setApplicationInfoResourcePath(resourcePath);
6643        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6644        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6645
6646        // Note that we invoke the following method only if we are about to unpack an application
6647        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6648                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6649
6650        /*
6651         * If the system app should be overridden by a previously installed
6652         * data, hide the system app now and let the /data/app scan pick it up
6653         * again.
6654         */
6655        if (shouldHideSystemApp) {
6656            synchronized (mPackages) {
6657                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6658            }
6659        }
6660
6661        return scannedPkg;
6662    }
6663
6664    private static String fixProcessName(String defProcessName,
6665            String processName, int uid) {
6666        if (processName == null) {
6667            return defProcessName;
6668        }
6669        return processName;
6670    }
6671
6672    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6673            throws PackageManagerException {
6674        if (pkgSetting.signatures.mSignatures != null) {
6675            // Already existing package. Make sure signatures match
6676            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6677                    == PackageManager.SIGNATURE_MATCH;
6678            if (!match) {
6679                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6680                        == PackageManager.SIGNATURE_MATCH;
6681            }
6682            if (!match) {
6683                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6684                        == PackageManager.SIGNATURE_MATCH;
6685            }
6686            if (!match) {
6687                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6688                        + pkg.packageName + " signatures do not match the "
6689                        + "previously installed version; ignoring!");
6690            }
6691        }
6692
6693        // Check for shared user signatures
6694        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6695            // Already existing package. Make sure signatures match
6696            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6697                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6698            if (!match) {
6699                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6700                        == PackageManager.SIGNATURE_MATCH;
6701            }
6702            if (!match) {
6703                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6704                        == PackageManager.SIGNATURE_MATCH;
6705            }
6706            if (!match) {
6707                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6708                        "Package " + pkg.packageName
6709                        + " has no signatures that match those in shared user "
6710                        + pkgSetting.sharedUser.name + "; ignoring!");
6711            }
6712        }
6713    }
6714
6715    /**
6716     * Enforces that only the system UID or root's UID can call a method exposed
6717     * via Binder.
6718     *
6719     * @param message used as message if SecurityException is thrown
6720     * @throws SecurityException if the caller is not system or root
6721     */
6722    private static final void enforceSystemOrRoot(String message) {
6723        final int uid = Binder.getCallingUid();
6724        if (uid != Process.SYSTEM_UID && uid != 0) {
6725            throw new SecurityException(message);
6726        }
6727    }
6728
6729    @Override
6730    public void performFstrimIfNeeded() {
6731        enforceSystemOrRoot("Only the system can request fstrim");
6732
6733        // Before everything else, see whether we need to fstrim.
6734        try {
6735            IMountService ms = PackageHelper.getMountService();
6736            if (ms != null) {
6737                final boolean isUpgrade = isUpgrade();
6738                boolean doTrim = isUpgrade;
6739                if (doTrim) {
6740                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6741                } else {
6742                    final long interval = android.provider.Settings.Global.getLong(
6743                            mContext.getContentResolver(),
6744                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6745                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6746                    if (interval > 0) {
6747                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6748                        if (timeSinceLast > interval) {
6749                            doTrim = true;
6750                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6751                                    + "; running immediately");
6752                        }
6753                    }
6754                }
6755                if (doTrim) {
6756                    if (!isFirstBoot()) {
6757                        try {
6758                            ActivityManagerNative.getDefault().showBootMessage(
6759                                    mContext.getResources().getString(
6760                                            R.string.android_upgrading_fstrim), true);
6761                        } catch (RemoteException e) {
6762                        }
6763                    }
6764                    ms.runMaintenance();
6765                }
6766            } else {
6767                Slog.e(TAG, "Mount service unavailable!");
6768            }
6769        } catch (RemoteException e) {
6770            // Can't happen; MountService is local
6771        }
6772    }
6773
6774    @Override
6775    public void extractPackagesIfNeeded() {
6776        enforceSystemOrRoot("Only the system can request package extraction");
6777
6778        // Extract pacakges only if profile-guided compilation is enabled because
6779        // otherwise BackgroundDexOptService will not dexopt them later.
6780        if (mUseJitProfiles) {
6781            ArraySet<String> pkgs = getOptimizablePackages();
6782            if (pkgs != null) {
6783                for (String pkg : pkgs) {
6784                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6785                            true /* extractOnly */, false /* force */);
6786                }
6787            }
6788        }
6789    }
6790
6791    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6792        List<ResolveInfo> ris = null;
6793        try {
6794            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6795                    intent, null, 0, userId);
6796        } catch (RemoteException e) {
6797        }
6798        ArraySet<String> pkgNames = new ArraySet<String>();
6799        if (ris != null) {
6800            for (ResolveInfo ri : ris) {
6801                pkgNames.add(ri.activityInfo.packageName);
6802            }
6803        }
6804        return pkgNames;
6805    }
6806
6807    @Override
6808    public void notifyPackageUse(String packageName) {
6809        synchronized (mPackages) {
6810            PackageParser.Package p = mPackages.get(packageName);
6811            if (p == null) {
6812                return;
6813            }
6814            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6815        }
6816    }
6817
6818    // TODO: this is not used nor needed. Delete it.
6819    @Override
6820    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6821        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6822                false /* extractOnly */, false /* force */);
6823    }
6824
6825    @Override
6826    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6827            boolean extractOnly, boolean force) {
6828        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6829    }
6830
6831    private boolean performDexOptTraced(String packageName, String instructionSet,
6832                boolean useProfiles, boolean extractOnly, boolean force) {
6833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6834        try {
6835            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6836                    force);
6837        } finally {
6838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6839        }
6840    }
6841
6842    private boolean performDexOptInternal(String packageName, String instructionSet,
6843                boolean useProfiles, boolean extractOnly, boolean force) {
6844        PackageParser.Package p;
6845        final String targetInstructionSet;
6846        synchronized (mPackages) {
6847            p = mPackages.get(packageName);
6848            if (p == null) {
6849                return false;
6850            }
6851            mPackageUsage.write(false);
6852
6853            targetInstructionSet = instructionSet != null ? instructionSet :
6854                    getPrimaryInstructionSet(p.applicationInfo);
6855            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6856                // Skip only if we do not use profiles since they might trigger a recompilation.
6857                return false;
6858            }
6859        }
6860        long callingId = Binder.clearCallingIdentity();
6861        try {
6862            synchronized (mInstallLock) {
6863                final String[] instructionSets = new String[] { targetInstructionSet };
6864                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6865                        useProfiles, extractOnly, force);
6866                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6867            }
6868        } finally {
6869            Binder.restoreCallingIdentity(callingId);
6870        }
6871    }
6872
6873    public ArraySet<String> getOptimizablePackages() {
6874        ArraySet<String> pkgs = new ArraySet<String>();
6875        synchronized (mPackages) {
6876            for (PackageParser.Package p : mPackages.values()) {
6877                if (PackageDexOptimizer.canOptimizePackage(p)) {
6878                    pkgs.add(p.packageName);
6879                }
6880            }
6881        }
6882        return pkgs;
6883    }
6884
6885    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6886            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6887        // Select the dex optimizer based on the force parameter.
6888        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6889        //       allocate an object here.
6890        PackageDexOptimizer pdo = force
6891                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6892                : mPackageDexOptimizer;
6893
6894        // Optimize all dependencies first. Note: we ignore the return value and march on
6895        // on errors.
6896        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6897        if (!deps.isEmpty()) {
6898            for (PackageParser.Package depPackage : deps) {
6899                // TODO: Analyze and investigate if we (should) profile libraries.
6900                // Currently this will do a full compilation of the library.
6901                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6902                        false /* extractOnly */);
6903            }
6904        }
6905
6906        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6907    }
6908
6909    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6910        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6911            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6912            Set<String> collectedNames = new HashSet<>();
6913            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6914
6915            retValue.remove(p);
6916
6917            return retValue;
6918        } else {
6919            return Collections.emptyList();
6920        }
6921    }
6922
6923    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6924            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6925        if (!collectedNames.contains(p.packageName)) {
6926            collectedNames.add(p.packageName);
6927            collected.add(p);
6928
6929            if (p.usesLibraries != null) {
6930                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6931            }
6932            if (p.usesOptionalLibraries != null) {
6933                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6934                        collectedNames);
6935            }
6936        }
6937    }
6938
6939    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6940            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6941        for (String libName : libs) {
6942            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6943            if (libPkg != null) {
6944                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6945            }
6946        }
6947    }
6948
6949    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6950        synchronized (mPackages) {
6951            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6952            if (lib != null && lib.apk != null) {
6953                return mPackages.get(lib.apk);
6954            }
6955        }
6956        return null;
6957    }
6958
6959    public void shutdown() {
6960        mPackageUsage.write(true);
6961    }
6962
6963    @Override
6964    public void forceDexOpt(String packageName) {
6965        enforceSystemOrRoot("forceDexOpt");
6966
6967        PackageParser.Package pkg;
6968        synchronized (mPackages) {
6969            pkg = mPackages.get(packageName);
6970            if (pkg == null) {
6971                throw new IllegalArgumentException("Unknown package: " + packageName);
6972            }
6973        }
6974
6975        synchronized (mInstallLock) {
6976            final String[] instructionSets = new String[] {
6977                    getPrimaryInstructionSet(pkg.applicationInfo) };
6978
6979            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6980
6981            // Whoever is calling forceDexOpt wants a fully compiled package.
6982            // Don't use profiles since that may cause compilation to be skipped.
6983            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6984                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6985
6986            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6987            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6988                throw new IllegalStateException("Failed to dexopt: " + res);
6989            }
6990        }
6991    }
6992
6993    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6994        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6995            Slog.w(TAG, "Unable to update from " + oldPkg.name
6996                    + " to " + newPkg.packageName
6997                    + ": old package not in system partition");
6998            return false;
6999        } else if (mPackages.get(oldPkg.name) != null) {
7000            Slog.w(TAG, "Unable to update from " + oldPkg.name
7001                    + " to " + newPkg.packageName
7002                    + ": old package still exists");
7003            return false;
7004        }
7005        return true;
7006    }
7007
7008    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7009        // TODO: triage flags as part of 26466827
7010        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7011
7012        boolean res = true;
7013        final int[] users = sUserManager.getUserIds();
7014        for (int user : users) {
7015            try {
7016                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7017            } catch (InstallerException e) {
7018                Slog.w(TAG, "Failed to delete data directory", e);
7019                res = false;
7020            }
7021        }
7022        return res;
7023    }
7024
7025    void removeCodePathLI(File codePath) {
7026        if (codePath.isDirectory()) {
7027            try {
7028                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7029            } catch (InstallerException e) {
7030                Slog.w(TAG, "Failed to remove code path", e);
7031            }
7032        } else {
7033            codePath.delete();
7034        }
7035    }
7036
7037    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7038        try {
7039            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7040        } catch (InstallerException e) {
7041            Slog.w(TAG, "Failed to destroy app data", e);
7042        }
7043    }
7044
7045    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7046            int appId, String seinfo) {
7047        try {
7048            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7049        } catch (InstallerException e) {
7050            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7051        }
7052    }
7053
7054    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7055        final PackageParser.Package pkg;
7056        synchronized (mPackages) {
7057            pkg = mPackages.get(packageName);
7058        }
7059        if (pkg == null) {
7060            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7061            return;
7062        }
7063        deleteCodeCacheDirsLI(pkg);
7064    }
7065
7066    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7067        // TODO: triage flags as part of 26466827
7068        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7069
7070        int[] users = sUserManager.getUserIds();
7071        int res = 0;
7072        for (int user : users) {
7073            // Remove the parent code cache
7074            try {
7075                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7076                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7077            } catch (InstallerException e) {
7078                Slog.w(TAG, "Failed to delete code cache directory", e);
7079            }
7080            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7081            for (int i = 0; i < childCount; i++) {
7082                PackageParser.Package childPkg = pkg.childPackages.get(i);
7083                // Remove the child code cache
7084                try {
7085                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7086                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7087                } catch (InstallerException e) {
7088                    Slog.w(TAG, "Failed to delete code cache directory", e);
7089                }
7090            }
7091        }
7092    }
7093
7094    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7095            long lastUpdateTime) {
7096        // Set parent install/update time
7097        PackageSetting ps = (PackageSetting) pkg.mExtras;
7098        if (ps != null) {
7099            ps.firstInstallTime = firstInstallTime;
7100            ps.lastUpdateTime = lastUpdateTime;
7101        }
7102        // Set children install/update time
7103        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7104        for (int i = 0; i < childCount; i++) {
7105            PackageParser.Package childPkg = pkg.childPackages.get(i);
7106            ps = (PackageSetting) childPkg.mExtras;
7107            if (ps != null) {
7108                ps.firstInstallTime = firstInstallTime;
7109                ps.lastUpdateTime = lastUpdateTime;
7110            }
7111        }
7112    }
7113
7114    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7115            PackageParser.Package changingLib) {
7116        if (file.path != null) {
7117            usesLibraryFiles.add(file.path);
7118            return;
7119        }
7120        PackageParser.Package p = mPackages.get(file.apk);
7121        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7122            // If we are doing this while in the middle of updating a library apk,
7123            // then we need to make sure to use that new apk for determining the
7124            // dependencies here.  (We haven't yet finished committing the new apk
7125            // to the package manager state.)
7126            if (p == null || p.packageName.equals(changingLib.packageName)) {
7127                p = changingLib;
7128            }
7129        }
7130        if (p != null) {
7131            usesLibraryFiles.addAll(p.getAllCodePaths());
7132        }
7133    }
7134
7135    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7136            PackageParser.Package changingLib) throws PackageManagerException {
7137        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7138            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7139            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7140            for (int i=0; i<N; i++) {
7141                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7142                if (file == null) {
7143                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7144                            "Package " + pkg.packageName + " requires unavailable shared library "
7145                            + pkg.usesLibraries.get(i) + "; failing!");
7146                }
7147                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7148            }
7149            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7150            for (int i=0; i<N; i++) {
7151                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7152                if (file == null) {
7153                    Slog.w(TAG, "Package " + pkg.packageName
7154                            + " desires unavailable shared library "
7155                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7156                } else {
7157                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7158                }
7159            }
7160            N = usesLibraryFiles.size();
7161            if (N > 0) {
7162                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7163            } else {
7164                pkg.usesLibraryFiles = null;
7165            }
7166        }
7167    }
7168
7169    private static boolean hasString(List<String> list, List<String> which) {
7170        if (list == null) {
7171            return false;
7172        }
7173        for (int i=list.size()-1; i>=0; i--) {
7174            for (int j=which.size()-1; j>=0; j--) {
7175                if (which.get(j).equals(list.get(i))) {
7176                    return true;
7177                }
7178            }
7179        }
7180        return false;
7181    }
7182
7183    private void updateAllSharedLibrariesLPw() {
7184        for (PackageParser.Package pkg : mPackages.values()) {
7185            try {
7186                updateSharedLibrariesLPw(pkg, null);
7187            } catch (PackageManagerException e) {
7188                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7189            }
7190        }
7191    }
7192
7193    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7194            PackageParser.Package changingPkg) {
7195        ArrayList<PackageParser.Package> res = null;
7196        for (PackageParser.Package pkg : mPackages.values()) {
7197            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7198                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7199                if (res == null) {
7200                    res = new ArrayList<PackageParser.Package>();
7201                }
7202                res.add(pkg);
7203                try {
7204                    updateSharedLibrariesLPw(pkg, changingPkg);
7205                } catch (PackageManagerException e) {
7206                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7207                }
7208            }
7209        }
7210        return res;
7211    }
7212
7213    /**
7214     * Derive the value of the {@code cpuAbiOverride} based on the provided
7215     * value and an optional stored value from the package settings.
7216     */
7217    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7218        String cpuAbiOverride = null;
7219
7220        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7221            cpuAbiOverride = null;
7222        } else if (abiOverride != null) {
7223            cpuAbiOverride = abiOverride;
7224        } else if (settings != null) {
7225            cpuAbiOverride = settings.cpuAbiOverrideString;
7226        }
7227
7228        return cpuAbiOverride;
7229    }
7230
7231    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7232            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7233        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7234        // If the package has children and this is the first dive in the function
7235        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7236        // whether all packages (parent and children) would be successfully scanned
7237        // before the actual scan since scanning mutates internal state and we want
7238        // to atomically install the package and its children.
7239        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7240            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7241                scanFlags |= SCAN_CHECK_ONLY;
7242            }
7243        } else {
7244            scanFlags &= ~SCAN_CHECK_ONLY;
7245        }
7246
7247        final PackageParser.Package scannedPkg;
7248        try {
7249            // Scan the parent
7250            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7251            // Scan the children
7252            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7253            for (int i = 0; i < childCount; i++) {
7254                PackageParser.Package childPkg = pkg.childPackages.get(i);
7255                scanPackageLI(childPkg, parseFlags,
7256                        scanFlags, currentTime, user);
7257            }
7258        } finally {
7259            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7260        }
7261
7262        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7263            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7264        }
7265
7266        return scannedPkg;
7267    }
7268
7269    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7270            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7271        boolean success = false;
7272        try {
7273            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7274                    currentTime, user);
7275            success = true;
7276            return res;
7277        } finally {
7278            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7279                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7280            }
7281        }
7282    }
7283
7284    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7285            int scanFlags, long currentTime, UserHandle user)
7286            throws PackageManagerException {
7287        final File scanFile = new File(pkg.codePath);
7288        if (pkg.applicationInfo.getCodePath() == null ||
7289                pkg.applicationInfo.getResourcePath() == null) {
7290            // Bail out. The resource and code paths haven't been set.
7291            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7292                    "Code and resource paths haven't been set correctly");
7293        }
7294
7295        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7296            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7297        } else {
7298            // Only allow system apps to be flagged as core apps.
7299            pkg.coreApp = false;
7300        }
7301
7302        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7303            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7304        }
7305
7306        if (mCustomResolverComponentName != null &&
7307                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7308            setUpCustomResolverActivity(pkg);
7309        }
7310
7311        if (pkg.packageName.equals("android")) {
7312            synchronized (mPackages) {
7313                if (mAndroidApplication != null) {
7314                    Slog.w(TAG, "*************************************************");
7315                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7316                    Slog.w(TAG, " file=" + scanFile);
7317                    Slog.w(TAG, "*************************************************");
7318                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7319                            "Core android package being redefined.  Skipping.");
7320                }
7321
7322                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7323                    // Set up information for our fall-back user intent resolution activity.
7324                    mPlatformPackage = pkg;
7325                    pkg.mVersionCode = mSdkVersion;
7326                    mAndroidApplication = pkg.applicationInfo;
7327
7328                    if (!mResolverReplaced) {
7329                        mResolveActivity.applicationInfo = mAndroidApplication;
7330                        mResolveActivity.name = ResolverActivity.class.getName();
7331                        mResolveActivity.packageName = mAndroidApplication.packageName;
7332                        mResolveActivity.processName = "system:ui";
7333                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7334                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7335                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7336                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7337                        mResolveActivity.exported = true;
7338                        mResolveActivity.enabled = true;
7339                        mResolveInfo.activityInfo = mResolveActivity;
7340                        mResolveInfo.priority = 0;
7341                        mResolveInfo.preferredOrder = 0;
7342                        mResolveInfo.match = 0;
7343                        mResolveComponentName = new ComponentName(
7344                                mAndroidApplication.packageName, mResolveActivity.name);
7345                    }
7346                }
7347            }
7348        }
7349
7350        if (DEBUG_PACKAGE_SCANNING) {
7351            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7352                Log.d(TAG, "Scanning package " + pkg.packageName);
7353        }
7354
7355        synchronized (mPackages) {
7356            if (mPackages.containsKey(pkg.packageName)
7357                    || mSharedLibraries.containsKey(pkg.packageName)) {
7358                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7359                        "Application package " + pkg.packageName
7360                                + " already installed.  Skipping duplicate.");
7361            }
7362
7363            // If we're only installing presumed-existing packages, require that the
7364            // scanned APK is both already known and at the path previously established
7365            // for it.  Previously unknown packages we pick up normally, but if we have an
7366            // a priori expectation about this package's install presence, enforce it.
7367            // With a singular exception for new system packages. When an OTA contains
7368            // a new system package, we allow the codepath to change from a system location
7369            // to the user-installed location. If we don't allow this change, any newer,
7370            // user-installed version of the application will be ignored.
7371            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7372                if (mExpectingBetter.containsKey(pkg.packageName)) {
7373                    logCriticalInfo(Log.WARN,
7374                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7375                } else {
7376                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7377                    if (known != null) {
7378                        if (DEBUG_PACKAGE_SCANNING) {
7379                            Log.d(TAG, "Examining " + pkg.codePath
7380                                    + " and requiring known paths " + known.codePathString
7381                                    + " & " + known.resourcePathString);
7382                        }
7383                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7384                                || !pkg.applicationInfo.getResourcePath().equals(
7385                                known.resourcePathString)) {
7386                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7387                                    "Application package " + pkg.packageName
7388                                            + " found at " + pkg.applicationInfo.getCodePath()
7389                                            + " but expected at " + known.codePathString
7390                                            + "; ignoring.");
7391                        }
7392                    }
7393                }
7394            }
7395        }
7396
7397        // Initialize package source and resource directories
7398        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7399        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7400
7401        SharedUserSetting suid = null;
7402        PackageSetting pkgSetting = null;
7403
7404        if (!isSystemApp(pkg)) {
7405            // Only system apps can use these features.
7406            pkg.mOriginalPackages = null;
7407            pkg.mRealPackage = null;
7408            pkg.mAdoptPermissions = null;
7409        }
7410
7411        // Getting the package setting may have a side-effect, so if we
7412        // are only checking if scan would succeed, stash a copy of the
7413        // old setting to restore at the end.
7414        PackageSetting nonMutatedPs = null;
7415
7416        // writer
7417        synchronized (mPackages) {
7418            if (pkg.mSharedUserId != null) {
7419                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7420                if (suid == null) {
7421                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7422                            "Creating application package " + pkg.packageName
7423                            + " for shared user failed");
7424                }
7425                if (DEBUG_PACKAGE_SCANNING) {
7426                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7427                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7428                                + "): packages=" + suid.packages);
7429                }
7430            }
7431
7432            // Check if we are renaming from an original package name.
7433            PackageSetting origPackage = null;
7434            String realName = null;
7435            if (pkg.mOriginalPackages != null) {
7436                // This package may need to be renamed to a previously
7437                // installed name.  Let's check on that...
7438                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7439                if (pkg.mOriginalPackages.contains(renamed)) {
7440                    // This package had originally been installed as the
7441                    // original name, and we have already taken care of
7442                    // transitioning to the new one.  Just update the new
7443                    // one to continue using the old name.
7444                    realName = pkg.mRealPackage;
7445                    if (!pkg.packageName.equals(renamed)) {
7446                        // Callers into this function may have already taken
7447                        // care of renaming the package; only do it here if
7448                        // it is not already done.
7449                        pkg.setPackageName(renamed);
7450                    }
7451
7452                } else {
7453                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7454                        if ((origPackage = mSettings.peekPackageLPr(
7455                                pkg.mOriginalPackages.get(i))) != null) {
7456                            // We do have the package already installed under its
7457                            // original name...  should we use it?
7458                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7459                                // New package is not compatible with original.
7460                                origPackage = null;
7461                                continue;
7462                            } else if (origPackage.sharedUser != null) {
7463                                // Make sure uid is compatible between packages.
7464                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7465                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7466                                            + " to " + pkg.packageName + ": old uid "
7467                                            + origPackage.sharedUser.name
7468                                            + " differs from " + pkg.mSharedUserId);
7469                                    origPackage = null;
7470                                    continue;
7471                                }
7472                            } else {
7473                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7474                                        + pkg.packageName + " to old name " + origPackage.name);
7475                            }
7476                            break;
7477                        }
7478                    }
7479                }
7480            }
7481
7482            if (mTransferedPackages.contains(pkg.packageName)) {
7483                Slog.w(TAG, "Package " + pkg.packageName
7484                        + " was transferred to another, but its .apk remains");
7485            }
7486
7487            // See comments in nonMutatedPs declaration
7488            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7489                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7490                if (foundPs != null) {
7491                    nonMutatedPs = new PackageSetting(foundPs);
7492                }
7493            }
7494
7495            // Just create the setting, don't add it yet. For already existing packages
7496            // the PkgSetting exists already and doesn't have to be created.
7497            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7498                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7499                    pkg.applicationInfo.primaryCpuAbi,
7500                    pkg.applicationInfo.secondaryCpuAbi,
7501                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7502                    user, false);
7503            if (pkgSetting == null) {
7504                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7505                        "Creating application package " + pkg.packageName + " failed");
7506            }
7507
7508            if (pkgSetting.origPackage != null) {
7509                // If we are first transitioning from an original package,
7510                // fix up the new package's name now.  We need to do this after
7511                // looking up the package under its new name, so getPackageLP
7512                // can take care of fiddling things correctly.
7513                pkg.setPackageName(origPackage.name);
7514
7515                // File a report about this.
7516                String msg = "New package " + pkgSetting.realName
7517                        + " renamed to replace old package " + pkgSetting.name;
7518                reportSettingsProblem(Log.WARN, msg);
7519
7520                // Make a note of it.
7521                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7522                    mTransferedPackages.add(origPackage.name);
7523                }
7524
7525                // No longer need to retain this.
7526                pkgSetting.origPackage = null;
7527            }
7528
7529            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7530                // Make a note of it.
7531                mTransferedPackages.add(pkg.packageName);
7532            }
7533
7534            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7535                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7536            }
7537
7538            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7539                // Check all shared libraries and map to their actual file path.
7540                // We only do this here for apps not on a system dir, because those
7541                // are the only ones that can fail an install due to this.  We
7542                // will take care of the system apps by updating all of their
7543                // library paths after the scan is done.
7544                updateSharedLibrariesLPw(pkg, null);
7545            }
7546
7547            if (mFoundPolicyFile) {
7548                SELinuxMMAC.assignSeinfoValue(pkg);
7549            }
7550
7551            pkg.applicationInfo.uid = pkgSetting.appId;
7552            pkg.mExtras = pkgSetting;
7553            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7554                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7555                    // We just determined the app is signed correctly, so bring
7556                    // over the latest parsed certs.
7557                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7558                } else {
7559                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7560                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7561                                "Package " + pkg.packageName + " upgrade keys do not match the "
7562                                + "previously installed version");
7563                    } else {
7564                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7565                        String msg = "System package " + pkg.packageName
7566                            + " signature changed; retaining data.";
7567                        reportSettingsProblem(Log.WARN, msg);
7568                    }
7569                }
7570            } else {
7571                try {
7572                    verifySignaturesLP(pkgSetting, pkg);
7573                    // We just determined the app is signed correctly, so bring
7574                    // over the latest parsed certs.
7575                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7576                } catch (PackageManagerException e) {
7577                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7578                        throw e;
7579                    }
7580                    // The signature has changed, but this package is in the system
7581                    // image...  let's recover!
7582                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7583                    // However...  if this package is part of a shared user, but it
7584                    // doesn't match the signature of the shared user, let's fail.
7585                    // What this means is that you can't change the signatures
7586                    // associated with an overall shared user, which doesn't seem all
7587                    // that unreasonable.
7588                    if (pkgSetting.sharedUser != null) {
7589                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7590                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7591                            throw new PackageManagerException(
7592                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7593                                            "Signature mismatch for shared user: "
7594                                            + pkgSetting.sharedUser);
7595                        }
7596                    }
7597                    // File a report about this.
7598                    String msg = "System package " + pkg.packageName
7599                        + " signature changed; retaining data.";
7600                    reportSettingsProblem(Log.WARN, msg);
7601                }
7602            }
7603            // Verify that this new package doesn't have any content providers
7604            // that conflict with existing packages.  Only do this if the
7605            // package isn't already installed, since we don't want to break
7606            // things that are installed.
7607            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7608                final int N = pkg.providers.size();
7609                int i;
7610                for (i=0; i<N; i++) {
7611                    PackageParser.Provider p = pkg.providers.get(i);
7612                    if (p.info.authority != null) {
7613                        String names[] = p.info.authority.split(";");
7614                        for (int j = 0; j < names.length; j++) {
7615                            if (mProvidersByAuthority.containsKey(names[j])) {
7616                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7617                                final String otherPackageName =
7618                                        ((other != null && other.getComponentName() != null) ?
7619                                                other.getComponentName().getPackageName() : "?");
7620                                throw new PackageManagerException(
7621                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7622                                                "Can't install because provider name " + names[j]
7623                                                + " (in package " + pkg.applicationInfo.packageName
7624                                                + ") is already used by " + otherPackageName);
7625                            }
7626                        }
7627                    }
7628                }
7629            }
7630
7631            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7632                // This package wants to adopt ownership of permissions from
7633                // another package.
7634                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7635                    final String origName = pkg.mAdoptPermissions.get(i);
7636                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7637                    if (orig != null) {
7638                        if (verifyPackageUpdateLPr(orig, pkg)) {
7639                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7640                                    + pkg.packageName);
7641                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7642                        }
7643                    }
7644                }
7645            }
7646        }
7647
7648        final String pkgName = pkg.packageName;
7649
7650        final long scanFileTime = scanFile.lastModified();
7651        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7652        pkg.applicationInfo.processName = fixProcessName(
7653                pkg.applicationInfo.packageName,
7654                pkg.applicationInfo.processName,
7655                pkg.applicationInfo.uid);
7656
7657        if (pkg != mPlatformPackage) {
7658            // Get all of our default paths setup
7659            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7660        }
7661
7662        final String path = scanFile.getPath();
7663        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7664
7665        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7666            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7667
7668            // Some system apps still use directory structure for native libraries
7669            // in which case we might end up not detecting abi solely based on apk
7670            // structure. Try to detect abi based on directory structure.
7671            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7672                    pkg.applicationInfo.primaryCpuAbi == null) {
7673                setBundledAppAbisAndRoots(pkg, pkgSetting);
7674                setNativeLibraryPaths(pkg);
7675            }
7676
7677        } else {
7678            if ((scanFlags & SCAN_MOVE) != 0) {
7679                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7680                // but we already have this packages package info in the PackageSetting. We just
7681                // use that and derive the native library path based on the new codepath.
7682                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7683                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7684            }
7685
7686            // Set native library paths again. For moves, the path will be updated based on the
7687            // ABIs we've determined above. For non-moves, the path will be updated based on the
7688            // ABIs we determined during compilation, but the path will depend on the final
7689            // package path (after the rename away from the stage path).
7690            setNativeLibraryPaths(pkg);
7691        }
7692
7693        // This is a special case for the "system" package, where the ABI is
7694        // dictated by the zygote configuration (and init.rc). We should keep track
7695        // of this ABI so that we can deal with "normal" applications that run under
7696        // the same UID correctly.
7697        if (mPlatformPackage == pkg) {
7698            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7699                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7700        }
7701
7702        // If there's a mismatch between the abi-override in the package setting
7703        // and the abiOverride specified for the install. Warn about this because we
7704        // would've already compiled the app without taking the package setting into
7705        // account.
7706        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7707            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7708                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7709                        " for package " + pkg.packageName);
7710            }
7711        }
7712
7713        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7714        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7715        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7716
7717        // Copy the derived override back to the parsed package, so that we can
7718        // update the package settings accordingly.
7719        pkg.cpuAbiOverride = cpuAbiOverride;
7720
7721        if (DEBUG_ABI_SELECTION) {
7722            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7723                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7724                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7725        }
7726
7727        // Push the derived path down into PackageSettings so we know what to
7728        // clean up at uninstall time.
7729        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7730
7731        if (DEBUG_ABI_SELECTION) {
7732            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7733                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7734                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7735        }
7736
7737        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7738            // We don't do this here during boot because we can do it all
7739            // at once after scanning all existing packages.
7740            //
7741            // We also do this *before* we perform dexopt on this package, so that
7742            // we can avoid redundant dexopts, and also to make sure we've got the
7743            // code and package path correct.
7744            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7745                    pkg, true /* boot complete */);
7746        }
7747
7748        if (mFactoryTest && pkg.requestedPermissions.contains(
7749                android.Manifest.permission.FACTORY_TEST)) {
7750            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7751        }
7752
7753        ArrayList<PackageParser.Package> clientLibPkgs = null;
7754
7755        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7756            if (nonMutatedPs != null) {
7757                synchronized (mPackages) {
7758                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7759                }
7760            }
7761            return pkg;
7762        }
7763
7764        // Only privileged apps and updated privileged apps can add child packages.
7765        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7766            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7767                throw new PackageManagerException("Only privileged apps and updated "
7768                        + "privileged apps can add child packages. Ignoring package "
7769                        + pkg.packageName);
7770            }
7771            final int childCount = pkg.childPackages.size();
7772            for (int i = 0; i < childCount; i++) {
7773                PackageParser.Package childPkg = pkg.childPackages.get(i);
7774                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7775                        childPkg.packageName)) {
7776                    throw new PackageManagerException("Cannot override a child package of "
7777                            + "another disabled system app. Ignoring package " + pkg.packageName);
7778                }
7779            }
7780        }
7781
7782        // writer
7783        synchronized (mPackages) {
7784            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7785                // Only system apps can add new shared libraries.
7786                if (pkg.libraryNames != null) {
7787                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7788                        String name = pkg.libraryNames.get(i);
7789                        boolean allowed = false;
7790                        if (pkg.isUpdatedSystemApp()) {
7791                            // New library entries can only be added through the
7792                            // system image.  This is important to get rid of a lot
7793                            // of nasty edge cases: for example if we allowed a non-
7794                            // system update of the app to add a library, then uninstalling
7795                            // the update would make the library go away, and assumptions
7796                            // we made such as through app install filtering would now
7797                            // have allowed apps on the device which aren't compatible
7798                            // with it.  Better to just have the restriction here, be
7799                            // conservative, and create many fewer cases that can negatively
7800                            // impact the user experience.
7801                            final PackageSetting sysPs = mSettings
7802                                    .getDisabledSystemPkgLPr(pkg.packageName);
7803                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7804                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7805                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7806                                        allowed = true;
7807                                        break;
7808                                    }
7809                                }
7810                            }
7811                        } else {
7812                            allowed = true;
7813                        }
7814                        if (allowed) {
7815                            if (!mSharedLibraries.containsKey(name)) {
7816                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7817                            } else if (!name.equals(pkg.packageName)) {
7818                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7819                                        + name + " already exists; skipping");
7820                            }
7821                        } else {
7822                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7823                                    + name + " that is not declared on system image; skipping");
7824                        }
7825                    }
7826                    if ((scanFlags & SCAN_BOOTING) == 0) {
7827                        // If we are not booting, we need to update any applications
7828                        // that are clients of our shared library.  If we are booting,
7829                        // this will all be done once the scan is complete.
7830                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7831                    }
7832                }
7833            }
7834        }
7835
7836        // Request the ActivityManager to kill the process(only for existing packages)
7837        // so that we do not end up in a confused state while the user is still using the older
7838        // version of the application while the new one gets installed.
7839        if ((scanFlags & SCAN_REPLACING) != 0) {
7840            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7841
7842            killApplication(pkg.applicationInfo.packageName,
7843                        pkg.applicationInfo.uid, "replace pkg");
7844
7845            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7846        }
7847
7848        // Also need to kill any apps that are dependent on the library.
7849        if (clientLibPkgs != null) {
7850            for (int i=0; i<clientLibPkgs.size(); i++) {
7851                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7852                killApplication(clientPkg.applicationInfo.packageName,
7853                        clientPkg.applicationInfo.uid, "update lib");
7854            }
7855        }
7856
7857        // Make sure we're not adding any bogus keyset info
7858        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7859        ksms.assertScannedPackageValid(pkg);
7860
7861        // writer
7862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7863
7864        boolean createIdmapFailed = false;
7865        synchronized (mPackages) {
7866            // We don't expect installation to fail beyond this point
7867
7868            // Add the new setting to mSettings
7869            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7870            // Add the new setting to mPackages
7871            mPackages.put(pkg.applicationInfo.packageName, pkg);
7872            // Make sure we don't accidentally delete its data.
7873            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7874            while (iter.hasNext()) {
7875                PackageCleanItem item = iter.next();
7876                if (pkgName.equals(item.packageName)) {
7877                    iter.remove();
7878                }
7879            }
7880
7881            // Take care of first install / last update times.
7882            if (currentTime != 0) {
7883                if (pkgSetting.firstInstallTime == 0) {
7884                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7885                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7886                    pkgSetting.lastUpdateTime = currentTime;
7887                }
7888            } else if (pkgSetting.firstInstallTime == 0) {
7889                // We need *something*.  Take time time stamp of the file.
7890                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7891            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7892                if (scanFileTime != pkgSetting.timeStamp) {
7893                    // A package on the system image has changed; consider this
7894                    // to be an update.
7895                    pkgSetting.lastUpdateTime = scanFileTime;
7896                }
7897            }
7898
7899            // Add the package's KeySets to the global KeySetManagerService
7900            ksms.addScannedPackageLPw(pkg);
7901
7902            int N = pkg.providers.size();
7903            StringBuilder r = null;
7904            int i;
7905            for (i=0; i<N; i++) {
7906                PackageParser.Provider p = pkg.providers.get(i);
7907                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7908                        p.info.processName, pkg.applicationInfo.uid);
7909                mProviders.addProvider(p);
7910                p.syncable = p.info.isSyncable;
7911                if (p.info.authority != null) {
7912                    String names[] = p.info.authority.split(";");
7913                    p.info.authority = null;
7914                    for (int j = 0; j < names.length; j++) {
7915                        if (j == 1 && p.syncable) {
7916                            // We only want the first authority for a provider to possibly be
7917                            // syncable, so if we already added this provider using a different
7918                            // authority clear the syncable flag. We copy the provider before
7919                            // changing it because the mProviders object contains a reference
7920                            // to a provider that we don't want to change.
7921                            // Only do this for the second authority since the resulting provider
7922                            // object can be the same for all future authorities for this provider.
7923                            p = new PackageParser.Provider(p);
7924                            p.syncable = false;
7925                        }
7926                        if (!mProvidersByAuthority.containsKey(names[j])) {
7927                            mProvidersByAuthority.put(names[j], p);
7928                            if (p.info.authority == null) {
7929                                p.info.authority = names[j];
7930                            } else {
7931                                p.info.authority = p.info.authority + ";" + names[j];
7932                            }
7933                            if (DEBUG_PACKAGE_SCANNING) {
7934                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7935                                    Log.d(TAG, "Registered content provider: " + names[j]
7936                                            + ", className = " + p.info.name + ", isSyncable = "
7937                                            + p.info.isSyncable);
7938                            }
7939                        } else {
7940                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7941                            Slog.w(TAG, "Skipping provider name " + names[j] +
7942                                    " (in package " + pkg.applicationInfo.packageName +
7943                                    "): name already used by "
7944                                    + ((other != null && other.getComponentName() != null)
7945                                            ? other.getComponentName().getPackageName() : "?"));
7946                        }
7947                    }
7948                }
7949                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7950                    if (r == null) {
7951                        r = new StringBuilder(256);
7952                    } else {
7953                        r.append(' ');
7954                    }
7955                    r.append(p.info.name);
7956                }
7957            }
7958            if (r != null) {
7959                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7960            }
7961
7962            N = pkg.services.size();
7963            r = null;
7964            for (i=0; i<N; i++) {
7965                PackageParser.Service s = pkg.services.get(i);
7966                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7967                        s.info.processName, pkg.applicationInfo.uid);
7968                mServices.addService(s);
7969                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7970                    if (r == null) {
7971                        r = new StringBuilder(256);
7972                    } else {
7973                        r.append(' ');
7974                    }
7975                    r.append(s.info.name);
7976                }
7977            }
7978            if (r != null) {
7979                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7980            }
7981
7982            N = pkg.receivers.size();
7983            r = null;
7984            for (i=0; i<N; i++) {
7985                PackageParser.Activity a = pkg.receivers.get(i);
7986                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7987                        a.info.processName, pkg.applicationInfo.uid);
7988                mReceivers.addActivity(a, "receiver");
7989                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7990                    if (r == null) {
7991                        r = new StringBuilder(256);
7992                    } else {
7993                        r.append(' ');
7994                    }
7995                    r.append(a.info.name);
7996                }
7997            }
7998            if (r != null) {
7999                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8000            }
8001
8002            N = pkg.activities.size();
8003            r = null;
8004            for (i=0; i<N; i++) {
8005                PackageParser.Activity a = pkg.activities.get(i);
8006                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8007                        a.info.processName, pkg.applicationInfo.uid);
8008                mActivities.addActivity(a, "activity");
8009                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8010                    if (r == null) {
8011                        r = new StringBuilder(256);
8012                    } else {
8013                        r.append(' ');
8014                    }
8015                    r.append(a.info.name);
8016                }
8017            }
8018            if (r != null) {
8019                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8020            }
8021
8022            N = pkg.permissionGroups.size();
8023            r = null;
8024            for (i=0; i<N; i++) {
8025                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8026                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8027                if (cur == null) {
8028                    mPermissionGroups.put(pg.info.name, pg);
8029                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8030                        if (r == null) {
8031                            r = new StringBuilder(256);
8032                        } else {
8033                            r.append(' ');
8034                        }
8035                        r.append(pg.info.name);
8036                    }
8037                } else {
8038                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8039                            + pg.info.packageName + " ignored: original from "
8040                            + cur.info.packageName);
8041                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8042                        if (r == null) {
8043                            r = new StringBuilder(256);
8044                        } else {
8045                            r.append(' ');
8046                        }
8047                        r.append("DUP:");
8048                        r.append(pg.info.name);
8049                    }
8050                }
8051            }
8052            if (r != null) {
8053                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8054            }
8055
8056            N = pkg.permissions.size();
8057            r = null;
8058            for (i=0; i<N; i++) {
8059                PackageParser.Permission p = pkg.permissions.get(i);
8060
8061                // Assume by default that we did not install this permission into the system.
8062                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8063
8064                // Now that permission groups have a special meaning, we ignore permission
8065                // groups for legacy apps to prevent unexpected behavior. In particular,
8066                // permissions for one app being granted to someone just becase they happen
8067                // to be in a group defined by another app (before this had no implications).
8068                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8069                    p.group = mPermissionGroups.get(p.info.group);
8070                    // Warn for a permission in an unknown group.
8071                    if (p.info.group != null && p.group == null) {
8072                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8073                                + p.info.packageName + " in an unknown group " + p.info.group);
8074                    }
8075                }
8076
8077                ArrayMap<String, BasePermission> permissionMap =
8078                        p.tree ? mSettings.mPermissionTrees
8079                                : mSettings.mPermissions;
8080                BasePermission bp = permissionMap.get(p.info.name);
8081
8082                // Allow system apps to redefine non-system permissions
8083                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8084                    final boolean currentOwnerIsSystem = (bp.perm != null
8085                            && isSystemApp(bp.perm.owner));
8086                    if (isSystemApp(p.owner)) {
8087                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8088                            // It's a built-in permission and no owner, take ownership now
8089                            bp.packageSetting = pkgSetting;
8090                            bp.perm = p;
8091                            bp.uid = pkg.applicationInfo.uid;
8092                            bp.sourcePackage = p.info.packageName;
8093                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8094                        } else if (!currentOwnerIsSystem) {
8095                            String msg = "New decl " + p.owner + " of permission  "
8096                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8097                            reportSettingsProblem(Log.WARN, msg);
8098                            bp = null;
8099                        }
8100                    }
8101                }
8102
8103                if (bp == null) {
8104                    bp = new BasePermission(p.info.name, p.info.packageName,
8105                            BasePermission.TYPE_NORMAL);
8106                    permissionMap.put(p.info.name, bp);
8107                }
8108
8109                if (bp.perm == null) {
8110                    if (bp.sourcePackage == null
8111                            || bp.sourcePackage.equals(p.info.packageName)) {
8112                        BasePermission tree = findPermissionTreeLP(p.info.name);
8113                        if (tree == null
8114                                || tree.sourcePackage.equals(p.info.packageName)) {
8115                            bp.packageSetting = pkgSetting;
8116                            bp.perm = p;
8117                            bp.uid = pkg.applicationInfo.uid;
8118                            bp.sourcePackage = p.info.packageName;
8119                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8120                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8121                                if (r == null) {
8122                                    r = new StringBuilder(256);
8123                                } else {
8124                                    r.append(' ');
8125                                }
8126                                r.append(p.info.name);
8127                            }
8128                        } else {
8129                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8130                                    + p.info.packageName + " ignored: base tree "
8131                                    + tree.name + " is from package "
8132                                    + tree.sourcePackage);
8133                        }
8134                    } else {
8135                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8136                                + p.info.packageName + " ignored: original from "
8137                                + bp.sourcePackage);
8138                    }
8139                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8140                    if (r == null) {
8141                        r = new StringBuilder(256);
8142                    } else {
8143                        r.append(' ');
8144                    }
8145                    r.append("DUP:");
8146                    r.append(p.info.name);
8147                }
8148                if (bp.perm == p) {
8149                    bp.protectionLevel = p.info.protectionLevel;
8150                }
8151            }
8152
8153            if (r != null) {
8154                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8155            }
8156
8157            N = pkg.instrumentation.size();
8158            r = null;
8159            for (i=0; i<N; i++) {
8160                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8161                a.info.packageName = pkg.applicationInfo.packageName;
8162                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8163                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8164                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8165                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8166                a.info.dataDir = pkg.applicationInfo.dataDir;
8167                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8168                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8169
8170                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8171                // need other information about the application, like the ABI and what not ?
8172                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8173                mInstrumentation.put(a.getComponentName(), a);
8174                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8175                    if (r == null) {
8176                        r = new StringBuilder(256);
8177                    } else {
8178                        r.append(' ');
8179                    }
8180                    r.append(a.info.name);
8181                }
8182            }
8183            if (r != null) {
8184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8185            }
8186
8187            if (pkg.protectedBroadcasts != null) {
8188                N = pkg.protectedBroadcasts.size();
8189                for (i=0; i<N; i++) {
8190                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8191                }
8192            }
8193
8194            pkgSetting.setTimeStamp(scanFileTime);
8195
8196            // Create idmap files for pairs of (packages, overlay packages).
8197            // Note: "android", ie framework-res.apk, is handled by native layers.
8198            if (pkg.mOverlayTarget != null) {
8199                // This is an overlay package.
8200                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8201                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8202                        mOverlays.put(pkg.mOverlayTarget,
8203                                new ArrayMap<String, PackageParser.Package>());
8204                    }
8205                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8206                    map.put(pkg.packageName, pkg);
8207                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8208                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8209                        createIdmapFailed = true;
8210                    }
8211                }
8212            } else if (mOverlays.containsKey(pkg.packageName) &&
8213                    !pkg.packageName.equals("android")) {
8214                // This is a regular package, with one or more known overlay packages.
8215                createIdmapsForPackageLI(pkg);
8216            }
8217        }
8218
8219        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8220
8221        if (createIdmapFailed) {
8222            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8223                    "scanPackageLI failed to createIdmap");
8224        }
8225        return pkg;
8226    }
8227
8228    /**
8229     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8230     * is derived purely on the basis of the contents of {@code scanFile} and
8231     * {@code cpuAbiOverride}.
8232     *
8233     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8234     */
8235    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8236                                 String cpuAbiOverride, boolean extractLibs)
8237            throws PackageManagerException {
8238        // TODO: We can probably be smarter about this stuff. For installed apps,
8239        // we can calculate this information at install time once and for all. For
8240        // system apps, we can probably assume that this information doesn't change
8241        // after the first boot scan. As things stand, we do lots of unnecessary work.
8242
8243        // Give ourselves some initial paths; we'll come back for another
8244        // pass once we've determined ABI below.
8245        setNativeLibraryPaths(pkg);
8246
8247        // We would never need to extract libs for forward-locked and external packages,
8248        // since the container service will do it for us. We shouldn't attempt to
8249        // extract libs from system app when it was not updated.
8250        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8251                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8252            extractLibs = false;
8253        }
8254
8255        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8256        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8257
8258        NativeLibraryHelper.Handle handle = null;
8259        try {
8260            handle = NativeLibraryHelper.Handle.create(pkg);
8261            // TODO(multiArch): This can be null for apps that didn't go through the
8262            // usual installation process. We can calculate it again, like we
8263            // do during install time.
8264            //
8265            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8266            // unnecessary.
8267            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8268
8269            // Null out the abis so that they can be recalculated.
8270            pkg.applicationInfo.primaryCpuAbi = null;
8271            pkg.applicationInfo.secondaryCpuAbi = null;
8272            if (isMultiArch(pkg.applicationInfo)) {
8273                // Warn if we've set an abiOverride for multi-lib packages..
8274                // By definition, we need to copy both 32 and 64 bit libraries for
8275                // such packages.
8276                if (pkg.cpuAbiOverride != null
8277                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8278                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8279                }
8280
8281                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8282                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8283                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8284                    if (extractLibs) {
8285                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8286                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8287                                useIsaSpecificSubdirs);
8288                    } else {
8289                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8290                    }
8291                }
8292
8293                maybeThrowExceptionForMultiArchCopy(
8294                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8295
8296                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8297                    if (extractLibs) {
8298                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8299                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8300                                useIsaSpecificSubdirs);
8301                    } else {
8302                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8303                    }
8304                }
8305
8306                maybeThrowExceptionForMultiArchCopy(
8307                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8308
8309                if (abi64 >= 0) {
8310                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8311                }
8312
8313                if (abi32 >= 0) {
8314                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8315                    if (abi64 >= 0) {
8316                        pkg.applicationInfo.secondaryCpuAbi = abi;
8317                    } else {
8318                        pkg.applicationInfo.primaryCpuAbi = abi;
8319                    }
8320                }
8321                if (cpuAbiOverride != null &&
8322                        cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) {
8323                    pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8324                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8325                }
8326            } else {
8327                String[] abiList = (cpuAbiOverride != null) ?
8328                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8329
8330                // Enable gross and lame hacks for apps that are built with old
8331                // SDK tools. We must scan their APKs for renderscript bitcode and
8332                // not launch them if it's present. Don't bother checking on devices
8333                // that don't have 64 bit support.
8334                boolean needsRenderScriptOverride = false;
8335                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8336                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8337                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8338                    needsRenderScriptOverride = true;
8339                }
8340
8341                final int copyRet;
8342                if (extractLibs) {
8343                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8344                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8345                } else {
8346                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8347                }
8348
8349                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8350                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8351                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8352                }
8353
8354                if (copyRet >= 0) {
8355                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8356                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8357                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8358                } else if (needsRenderScriptOverride) {
8359                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8360                }
8361            }
8362        } catch (IOException ioe) {
8363            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8364        } finally {
8365            IoUtils.closeQuietly(handle);
8366        }
8367
8368        // Now that we've calculated the ABIs and determined if it's an internal app,
8369        // we will go ahead and populate the nativeLibraryPath.
8370        setNativeLibraryPaths(pkg);
8371    }
8372
8373    /**
8374     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8375     * i.e, so that all packages can be run inside a single process if required.
8376     *
8377     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8378     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8379     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8380     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8381     * updating a package that belongs to a shared user.
8382     *
8383     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8384     * adds unnecessary complexity.
8385     */
8386    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8387            PackageParser.Package scannedPackage, boolean bootComplete) {
8388        String requiredInstructionSet = null;
8389        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8390            requiredInstructionSet = VMRuntime.getInstructionSet(
8391                     scannedPackage.applicationInfo.primaryCpuAbi);
8392        }
8393
8394        PackageSetting requirer = null;
8395        for (PackageSetting ps : packagesForUser) {
8396            // If packagesForUser contains scannedPackage, we skip it. This will happen
8397            // when scannedPackage is an update of an existing package. Without this check,
8398            // we will never be able to change the ABI of any package belonging to a shared
8399            // user, even if it's compatible with other packages.
8400            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8401                if (ps.primaryCpuAbiString == null) {
8402                    continue;
8403                }
8404
8405                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8406                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8407                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8408                    // this but there's not much we can do.
8409                    String errorMessage = "Instruction set mismatch, "
8410                            + ((requirer == null) ? "[caller]" : requirer)
8411                            + " requires " + requiredInstructionSet + " whereas " + ps
8412                            + " requires " + instructionSet;
8413                    Slog.w(TAG, errorMessage);
8414                }
8415
8416                if (requiredInstructionSet == null) {
8417                    requiredInstructionSet = instructionSet;
8418                    requirer = ps;
8419                }
8420            }
8421        }
8422
8423        if (requiredInstructionSet != null) {
8424            String adjustedAbi;
8425            if (requirer != null) {
8426                // requirer != null implies that either scannedPackage was null or that scannedPackage
8427                // did not require an ABI, in which case we have to adjust scannedPackage to match
8428                // the ABI of the set (which is the same as requirer's ABI)
8429                adjustedAbi = requirer.primaryCpuAbiString;
8430                if (scannedPackage != null) {
8431                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8432                }
8433            } else {
8434                // requirer == null implies that we're updating all ABIs in the set to
8435                // match scannedPackage.
8436                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8437            }
8438
8439            for (PackageSetting ps : packagesForUser) {
8440                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8441                    if (ps.primaryCpuAbiString != null) {
8442                        continue;
8443                    }
8444
8445                    ps.primaryCpuAbiString = adjustedAbi;
8446                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8447                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8448                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8449                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8450                                + " (requirer="
8451                                + (requirer == null ? "null" : requirer.pkg.packageName)
8452                                + ", scannedPackage="
8453                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8454                                + ")");
8455                        try {
8456                            mInstaller.rmdex(ps.codePathString,
8457                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8458                        } catch (InstallerException ignored) {
8459                        }
8460                    }
8461                }
8462            }
8463        }
8464    }
8465
8466    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8467        synchronized (mPackages) {
8468            mResolverReplaced = true;
8469            // Set up information for custom user intent resolution activity.
8470            mResolveActivity.applicationInfo = pkg.applicationInfo;
8471            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8472            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8473            mResolveActivity.processName = pkg.applicationInfo.packageName;
8474            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8475            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8476                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8477            mResolveActivity.theme = 0;
8478            mResolveActivity.exported = true;
8479            mResolveActivity.enabled = true;
8480            mResolveInfo.activityInfo = mResolveActivity;
8481            mResolveInfo.priority = 0;
8482            mResolveInfo.preferredOrder = 0;
8483            mResolveInfo.match = 0;
8484            mResolveComponentName = mCustomResolverComponentName;
8485            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8486                    mResolveComponentName);
8487        }
8488    }
8489
8490    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8491        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8492
8493        // Set up information for ephemeral installer activity
8494        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8495        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8496        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8497        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8498        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8499        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8500                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8501        mEphemeralInstallerActivity.theme = 0;
8502        mEphemeralInstallerActivity.exported = true;
8503        mEphemeralInstallerActivity.enabled = true;
8504        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8505        mEphemeralInstallerInfo.priority = 0;
8506        mEphemeralInstallerInfo.preferredOrder = 0;
8507        mEphemeralInstallerInfo.match = 0;
8508
8509        if (DEBUG_EPHEMERAL) {
8510            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8511        }
8512    }
8513
8514    private static String calculateBundledApkRoot(final String codePathString) {
8515        final File codePath = new File(codePathString);
8516        final File codeRoot;
8517        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8518            codeRoot = Environment.getRootDirectory();
8519        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8520            codeRoot = Environment.getOemDirectory();
8521        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8522            codeRoot = Environment.getVendorDirectory();
8523        } else {
8524            // Unrecognized code path; take its top real segment as the apk root:
8525            // e.g. /something/app/blah.apk => /something
8526            try {
8527                File f = codePath.getCanonicalFile();
8528                File parent = f.getParentFile();    // non-null because codePath is a file
8529                File tmp;
8530                while ((tmp = parent.getParentFile()) != null) {
8531                    f = parent;
8532                    parent = tmp;
8533                }
8534                codeRoot = f;
8535                Slog.w(TAG, "Unrecognized code path "
8536                        + codePath + " - using " + codeRoot);
8537            } catch (IOException e) {
8538                // Can't canonicalize the code path -- shenanigans?
8539                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8540                return Environment.getRootDirectory().getPath();
8541            }
8542        }
8543        return codeRoot.getPath();
8544    }
8545
8546    /**
8547     * Derive and set the location of native libraries for the given package,
8548     * which varies depending on where and how the package was installed.
8549     */
8550    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8551        final ApplicationInfo info = pkg.applicationInfo;
8552        final String codePath = pkg.codePath;
8553        final File codeFile = new File(codePath);
8554        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8555        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8556
8557        info.nativeLibraryRootDir = null;
8558        info.nativeLibraryRootRequiresIsa = false;
8559        info.nativeLibraryDir = null;
8560        info.secondaryNativeLibraryDir = null;
8561
8562        if (isApkFile(codeFile)) {
8563            // Monolithic install
8564            if (bundledApp) {
8565                // If "/system/lib64/apkname" exists, assume that is the per-package
8566                // native library directory to use; otherwise use "/system/lib/apkname".
8567                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8568                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8569                        getPrimaryInstructionSet(info));
8570
8571                // This is a bundled system app so choose the path based on the ABI.
8572                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8573                // is just the default path.
8574                final String apkName = deriveCodePathName(codePath);
8575                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8576                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8577                        apkName).getAbsolutePath();
8578
8579                if (info.secondaryCpuAbi != null) {
8580                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8581                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8582                            secondaryLibDir, apkName).getAbsolutePath();
8583                }
8584            } else if (asecApp) {
8585                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8586                        .getAbsolutePath();
8587            } else {
8588                final String apkName = deriveCodePathName(codePath);
8589                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8590                        .getAbsolutePath();
8591            }
8592
8593            info.nativeLibraryRootRequiresIsa = false;
8594            info.nativeLibraryDir = info.nativeLibraryRootDir;
8595        } else {
8596            // Cluster install
8597            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8598            info.nativeLibraryRootRequiresIsa = true;
8599
8600            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8601                    getPrimaryInstructionSet(info)).getAbsolutePath();
8602
8603            if (info.secondaryCpuAbi != null) {
8604                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8605                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8606            }
8607        }
8608    }
8609
8610    /**
8611     * Calculate the abis and roots for a bundled app. These can uniquely
8612     * be determined from the contents of the system partition, i.e whether
8613     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8614     * of this information, and instead assume that the system was built
8615     * sensibly.
8616     */
8617    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8618                                           PackageSetting pkgSetting) {
8619        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8620
8621        // If "/system/lib64/apkname" exists, assume that is the per-package
8622        // native library directory to use; otherwise use "/system/lib/apkname".
8623        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8624        setBundledAppAbi(pkg, apkRoot, apkName);
8625        // pkgSetting might be null during rescan following uninstall of updates
8626        // to a bundled app, so accommodate that possibility.  The settings in
8627        // that case will be established later from the parsed package.
8628        //
8629        // If the settings aren't null, sync them up with what we've just derived.
8630        // note that apkRoot isn't stored in the package settings.
8631        if (pkgSetting != null) {
8632            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8633            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8634        }
8635    }
8636
8637    /**
8638     * Deduces the ABI of a bundled app and sets the relevant fields on the
8639     * parsed pkg object.
8640     *
8641     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8642     *        under which system libraries are installed.
8643     * @param apkName the name of the installed package.
8644     */
8645    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8646        final File codeFile = new File(pkg.codePath);
8647
8648        final boolean has64BitLibs;
8649        final boolean has32BitLibs;
8650        if (isApkFile(codeFile)) {
8651            // Monolithic install
8652            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8653            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8654        } else {
8655            // Cluster install
8656            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8657            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8658                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8659                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8660                has64BitLibs = (new File(rootDir, isa)).exists();
8661            } else {
8662                has64BitLibs = false;
8663            }
8664            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8665                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8666                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8667                has32BitLibs = (new File(rootDir, isa)).exists();
8668            } else {
8669                has32BitLibs = false;
8670            }
8671        }
8672
8673        if (has64BitLibs && !has32BitLibs) {
8674            // The package has 64 bit libs, but not 32 bit libs. Its primary
8675            // ABI should be 64 bit. We can safely assume here that the bundled
8676            // native libraries correspond to the most preferred ABI in the list.
8677
8678            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8679            pkg.applicationInfo.secondaryCpuAbi = null;
8680        } else if (has32BitLibs && !has64BitLibs) {
8681            // The package has 32 bit libs but not 64 bit libs. Its primary
8682            // ABI should be 32 bit.
8683
8684            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8685            pkg.applicationInfo.secondaryCpuAbi = null;
8686        } else if (has32BitLibs && has64BitLibs) {
8687            // The application has both 64 and 32 bit bundled libraries. We check
8688            // here that the app declares multiArch support, and warn if it doesn't.
8689            //
8690            // We will be lenient here and record both ABIs. The primary will be the
8691            // ABI that's higher on the list, i.e, a device that's configured to prefer
8692            // 64 bit apps will see a 64 bit primary ABI,
8693
8694            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8695                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8696            }
8697
8698            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8699                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8700                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8701            } else {
8702                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8703                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8704            }
8705        } else {
8706            pkg.applicationInfo.primaryCpuAbi = null;
8707            pkg.applicationInfo.secondaryCpuAbi = null;
8708        }
8709    }
8710
8711    private void killPackage(PackageParser.Package pkg, String reason) {
8712        // Kill the parent package
8713        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8714        // Kill the child packages
8715        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8716        for (int i = 0; i < childCount; i++) {
8717            PackageParser.Package childPkg = pkg.childPackages.get(i);
8718            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8719        }
8720    }
8721
8722    private void killApplication(String pkgName, int appId, String reason) {
8723        // Request the ActivityManager to kill the process(only for existing packages)
8724        // so that we do not end up in a confused state while the user is still using the older
8725        // version of the application while the new one gets installed.
8726        IActivityManager am = ActivityManagerNative.getDefault();
8727        if (am != null) {
8728            try {
8729                am.killApplicationWithAppId(pkgName, appId, reason);
8730            } catch (RemoteException e) {
8731            }
8732        }
8733    }
8734
8735    private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) {
8736        // Remove the parent package setting
8737        PackageSetting ps = (PackageSetting) pkg.mExtras;
8738        if (ps != null) {
8739            removePackageSettingLI(ps, chatty);
8740        }
8741        // Remove the child package setting
8742        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8743        for (int i = 0; i < childCount; i++) {
8744            PackageParser.Package childPkg = pkg.childPackages.get(i);
8745            ps = (PackageSetting) childPkg.mExtras;
8746            if (ps != null) {
8747                removePackageSettingLI(ps, chatty);
8748            }
8749        }
8750    }
8751
8752    void removePackageSettingLI(PackageSetting ps, boolean chatty) {
8753        if (DEBUG_INSTALL) {
8754            if (chatty)
8755                Log.d(TAG, "Removing package " + ps.name);
8756        }
8757
8758        // writer
8759        synchronized (mPackages) {
8760            mPackages.remove(ps.name);
8761            final PackageParser.Package pkg = ps.pkg;
8762            if (pkg != null) {
8763                cleanPackageDataStructuresLILPw(pkg, chatty);
8764            }
8765        }
8766    }
8767
8768    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8769        if (DEBUG_INSTALL) {
8770            if (chatty)
8771                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8772        }
8773
8774        // writer
8775        synchronized (mPackages) {
8776            // Remove the parent package
8777            mPackages.remove(pkg.applicationInfo.packageName);
8778            cleanPackageDataStructuresLILPw(pkg, chatty);
8779
8780            // Remove the child packages
8781            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8782            for (int i = 0; i < childCount; i++) {
8783                PackageParser.Package childPkg = pkg.childPackages.get(i);
8784                mPackages.remove(childPkg.applicationInfo.packageName);
8785                cleanPackageDataStructuresLILPw(childPkg, chatty);
8786            }
8787        }
8788    }
8789
8790    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8791        int N = pkg.providers.size();
8792        StringBuilder r = null;
8793        int i;
8794        for (i=0; i<N; i++) {
8795            PackageParser.Provider p = pkg.providers.get(i);
8796            mProviders.removeProvider(p);
8797            if (p.info.authority == null) {
8798
8799                /* There was another ContentProvider with this authority when
8800                 * this app was installed so this authority is null,
8801                 * Ignore it as we don't have to unregister the provider.
8802                 */
8803                continue;
8804            }
8805            String names[] = p.info.authority.split(";");
8806            for (int j = 0; j < names.length; j++) {
8807                if (mProvidersByAuthority.get(names[j]) == p) {
8808                    mProvidersByAuthority.remove(names[j]);
8809                    if (DEBUG_REMOVE) {
8810                        if (chatty)
8811                            Log.d(TAG, "Unregistered content provider: " + names[j]
8812                                    + ", className = " + p.info.name + ", isSyncable = "
8813                                    + p.info.isSyncable);
8814                    }
8815                }
8816            }
8817            if (DEBUG_REMOVE && chatty) {
8818                if (r == null) {
8819                    r = new StringBuilder(256);
8820                } else {
8821                    r.append(' ');
8822                }
8823                r.append(p.info.name);
8824            }
8825        }
8826        if (r != null) {
8827            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8828        }
8829
8830        N = pkg.services.size();
8831        r = null;
8832        for (i=0; i<N; i++) {
8833            PackageParser.Service s = pkg.services.get(i);
8834            mServices.removeService(s);
8835            if (chatty) {
8836                if (r == null) {
8837                    r = new StringBuilder(256);
8838                } else {
8839                    r.append(' ');
8840                }
8841                r.append(s.info.name);
8842            }
8843        }
8844        if (r != null) {
8845            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8846        }
8847
8848        N = pkg.receivers.size();
8849        r = null;
8850        for (i=0; i<N; i++) {
8851            PackageParser.Activity a = pkg.receivers.get(i);
8852            mReceivers.removeActivity(a, "receiver");
8853            if (DEBUG_REMOVE && chatty) {
8854                if (r == null) {
8855                    r = new StringBuilder(256);
8856                } else {
8857                    r.append(' ');
8858                }
8859                r.append(a.info.name);
8860            }
8861        }
8862        if (r != null) {
8863            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8864        }
8865
8866        N = pkg.activities.size();
8867        r = null;
8868        for (i=0; i<N; i++) {
8869            PackageParser.Activity a = pkg.activities.get(i);
8870            mActivities.removeActivity(a, "activity");
8871            if (DEBUG_REMOVE && chatty) {
8872                if (r == null) {
8873                    r = new StringBuilder(256);
8874                } else {
8875                    r.append(' ');
8876                }
8877                r.append(a.info.name);
8878            }
8879        }
8880        if (r != null) {
8881            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8882        }
8883
8884        N = pkg.permissions.size();
8885        r = null;
8886        for (i=0; i<N; i++) {
8887            PackageParser.Permission p = pkg.permissions.get(i);
8888            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8889            if (bp == null) {
8890                bp = mSettings.mPermissionTrees.get(p.info.name);
8891            }
8892            if (bp != null && bp.perm == p) {
8893                bp.perm = null;
8894                if (DEBUG_REMOVE && chatty) {
8895                    if (r == null) {
8896                        r = new StringBuilder(256);
8897                    } else {
8898                        r.append(' ');
8899                    }
8900                    r.append(p.info.name);
8901                }
8902            }
8903            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8904                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8905                if (appOpPkgs != null) {
8906                    appOpPkgs.remove(pkg.packageName);
8907                }
8908            }
8909        }
8910        if (r != null) {
8911            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8912        }
8913
8914        N = pkg.requestedPermissions.size();
8915        r = null;
8916        for (i=0; i<N; i++) {
8917            String perm = pkg.requestedPermissions.get(i);
8918            BasePermission bp = mSettings.mPermissions.get(perm);
8919            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8920                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8921                if (appOpPkgs != null) {
8922                    appOpPkgs.remove(pkg.packageName);
8923                    if (appOpPkgs.isEmpty()) {
8924                        mAppOpPermissionPackages.remove(perm);
8925                    }
8926                }
8927            }
8928        }
8929        if (r != null) {
8930            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8931        }
8932
8933        N = pkg.instrumentation.size();
8934        r = null;
8935        for (i=0; i<N; i++) {
8936            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8937            mInstrumentation.remove(a.getComponentName());
8938            if (DEBUG_REMOVE && chatty) {
8939                if (r == null) {
8940                    r = new StringBuilder(256);
8941                } else {
8942                    r.append(' ');
8943                }
8944                r.append(a.info.name);
8945            }
8946        }
8947        if (r != null) {
8948            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8949        }
8950
8951        r = null;
8952        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8953            // Only system apps can hold shared libraries.
8954            if (pkg.libraryNames != null) {
8955                for (i=0; i<pkg.libraryNames.size(); i++) {
8956                    String name = pkg.libraryNames.get(i);
8957                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8958                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8959                        mSharedLibraries.remove(name);
8960                        if (DEBUG_REMOVE && chatty) {
8961                            if (r == null) {
8962                                r = new StringBuilder(256);
8963                            } else {
8964                                r.append(' ');
8965                            }
8966                            r.append(name);
8967                        }
8968                    }
8969                }
8970            }
8971        }
8972        if (r != null) {
8973            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8974        }
8975    }
8976
8977    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8978        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8979            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8980                return true;
8981            }
8982        }
8983        return false;
8984    }
8985
8986    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8987    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8988    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8989
8990    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
8991        // Update the parent permissions
8992        updatePermissionsLPw(pkg.packageName, pkg, flags);
8993        // Update the child permissions
8994        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8995        for (int i = 0; i < childCount; i++) {
8996            PackageParser.Package childPkg = pkg.childPackages.get(i);
8997            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
8998        }
8999    }
9000
9001    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9002            int flags) {
9003        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9004        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9005    }
9006
9007    private void updatePermissionsLPw(String changingPkg,
9008            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9009        // Make sure there are no dangling permission trees.
9010        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9011        while (it.hasNext()) {
9012            final BasePermission bp = it.next();
9013            if (bp.packageSetting == null) {
9014                // We may not yet have parsed the package, so just see if
9015                // we still know about its settings.
9016                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9017            }
9018            if (bp.packageSetting == null) {
9019                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9020                        + " from package " + bp.sourcePackage);
9021                it.remove();
9022            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9023                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9024                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9025                            + " from package " + bp.sourcePackage);
9026                    flags |= UPDATE_PERMISSIONS_ALL;
9027                    it.remove();
9028                }
9029            }
9030        }
9031
9032        // Make sure all dynamic permissions have been assigned to a package,
9033        // and make sure there are no dangling permissions.
9034        it = mSettings.mPermissions.values().iterator();
9035        while (it.hasNext()) {
9036            final BasePermission bp = it.next();
9037            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9038                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9039                        + bp.name + " pkg=" + bp.sourcePackage
9040                        + " info=" + bp.pendingInfo);
9041                if (bp.packageSetting == null && bp.pendingInfo != null) {
9042                    final BasePermission tree = findPermissionTreeLP(bp.name);
9043                    if (tree != null && tree.perm != null) {
9044                        bp.packageSetting = tree.packageSetting;
9045                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9046                                new PermissionInfo(bp.pendingInfo));
9047                        bp.perm.info.packageName = tree.perm.info.packageName;
9048                        bp.perm.info.name = bp.name;
9049                        bp.uid = tree.uid;
9050                    }
9051                }
9052            }
9053            if (bp.packageSetting == null) {
9054                // We may not yet have parsed the package, so just see if
9055                // we still know about its settings.
9056                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9057            }
9058            if (bp.packageSetting == null) {
9059                Slog.w(TAG, "Removing dangling permission: " + bp.name
9060                        + " from package " + bp.sourcePackage);
9061                it.remove();
9062            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9063                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9064                    Slog.i(TAG, "Removing old permission: " + bp.name
9065                            + " from package " + bp.sourcePackage);
9066                    flags |= UPDATE_PERMISSIONS_ALL;
9067                    it.remove();
9068                }
9069            }
9070        }
9071
9072        // Now update the permissions for all packages, in particular
9073        // replace the granted permissions of the system packages.
9074        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9075            for (PackageParser.Package pkg : mPackages.values()) {
9076                if (pkg != pkgInfo) {
9077                    // Only replace for packages on requested volume
9078                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9079                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9080                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9081                    grantPermissionsLPw(pkg, replace, changingPkg);
9082                }
9083            }
9084        }
9085
9086        if (pkgInfo != null) {
9087            // Only replace for packages on requested volume
9088            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9089            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9090                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9091            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9092        }
9093    }
9094
9095    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9096            String packageOfInterest) {
9097        // IMPORTANT: There are two types of permissions: install and runtime.
9098        // Install time permissions are granted when the app is installed to
9099        // all device users and users added in the future. Runtime permissions
9100        // are granted at runtime explicitly to specific users. Normal and signature
9101        // protected permissions are install time permissions. Dangerous permissions
9102        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9103        // otherwise they are runtime permissions. This function does not manage
9104        // runtime permissions except for the case an app targeting Lollipop MR1
9105        // being upgraded to target a newer SDK, in which case dangerous permissions
9106        // are transformed from install time to runtime ones.
9107
9108        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9109        if (ps == null) {
9110            return;
9111        }
9112
9113        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9114
9115        PermissionsState permissionsState = ps.getPermissionsState();
9116        PermissionsState origPermissions = permissionsState;
9117
9118        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9119
9120        boolean runtimePermissionsRevoked = false;
9121        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9122
9123        boolean changedInstallPermission = false;
9124
9125        if (replace) {
9126            ps.installPermissionsFixed = false;
9127            if (!ps.isSharedUser()) {
9128                origPermissions = new PermissionsState(permissionsState);
9129                permissionsState.reset();
9130            } else {
9131                // We need to know only about runtime permission changes since the
9132                // calling code always writes the install permissions state but
9133                // the runtime ones are written only if changed. The only cases of
9134                // changed runtime permissions here are promotion of an install to
9135                // runtime and revocation of a runtime from a shared user.
9136                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9137                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9138                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9139                    runtimePermissionsRevoked = true;
9140                }
9141            }
9142        }
9143
9144        permissionsState.setGlobalGids(mGlobalGids);
9145
9146        final int N = pkg.requestedPermissions.size();
9147        for (int i=0; i<N; i++) {
9148            final String name = pkg.requestedPermissions.get(i);
9149            final BasePermission bp = mSettings.mPermissions.get(name);
9150
9151            if (DEBUG_INSTALL) {
9152                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9153            }
9154
9155            if (bp == null || bp.packageSetting == null) {
9156                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9157                    Slog.w(TAG, "Unknown permission " + name
9158                            + " in package " + pkg.packageName);
9159                }
9160                continue;
9161            }
9162
9163            final String perm = bp.name;
9164            boolean allowedSig = false;
9165            int grant = GRANT_DENIED;
9166
9167            // Keep track of app op permissions.
9168            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9169                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9170                if (pkgs == null) {
9171                    pkgs = new ArraySet<>();
9172                    mAppOpPermissionPackages.put(bp.name, pkgs);
9173                }
9174                pkgs.add(pkg.packageName);
9175            }
9176
9177            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9178            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9179                    >= Build.VERSION_CODES.M;
9180            switch (level) {
9181                case PermissionInfo.PROTECTION_NORMAL: {
9182                    // For all apps normal permissions are install time ones.
9183                    grant = GRANT_INSTALL;
9184                } break;
9185
9186                case PermissionInfo.PROTECTION_DANGEROUS: {
9187                    // If a permission review is required for legacy apps we represent
9188                    // their permissions as always granted runtime ones since we need
9189                    // to keep the review required permission flag per user while an
9190                    // install permission's state is shared across all users.
9191                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9192                        // For legacy apps dangerous permissions are install time ones.
9193                        grant = GRANT_INSTALL;
9194                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9195                        // For legacy apps that became modern, install becomes runtime.
9196                        grant = GRANT_UPGRADE;
9197                    } else if (mPromoteSystemApps
9198                            && isSystemApp(ps)
9199                            && mExistingSystemPackages.contains(ps.name)) {
9200                        // For legacy system apps, install becomes runtime.
9201                        // We cannot check hasInstallPermission() for system apps since those
9202                        // permissions were granted implicitly and not persisted pre-M.
9203                        grant = GRANT_UPGRADE;
9204                    } else {
9205                        // For modern apps keep runtime permissions unchanged.
9206                        grant = GRANT_RUNTIME;
9207                    }
9208                } break;
9209
9210                case PermissionInfo.PROTECTION_SIGNATURE: {
9211                    // For all apps signature permissions are install time ones.
9212                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9213                    if (allowedSig) {
9214                        grant = GRANT_INSTALL;
9215                    }
9216                } break;
9217            }
9218
9219            if (DEBUG_INSTALL) {
9220                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9221            }
9222
9223            if (grant != GRANT_DENIED) {
9224                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9225                    // If this is an existing, non-system package, then
9226                    // we can't add any new permissions to it.
9227                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9228                        // Except...  if this is a permission that was added
9229                        // to the platform (note: need to only do this when
9230                        // updating the platform).
9231                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9232                            grant = GRANT_DENIED;
9233                        }
9234                    }
9235                }
9236
9237                switch (grant) {
9238                    case GRANT_INSTALL: {
9239                        // Revoke this as runtime permission to handle the case of
9240                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9241                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9242                            if (origPermissions.getRuntimePermissionState(
9243                                    bp.name, userId) != null) {
9244                                // Revoke the runtime permission and clear the flags.
9245                                origPermissions.revokeRuntimePermission(bp, userId);
9246                                origPermissions.updatePermissionFlags(bp, userId,
9247                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9248                                // If we revoked a permission permission, we have to write.
9249                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9250                                        changedRuntimePermissionUserIds, userId);
9251                            }
9252                        }
9253                        // Grant an install permission.
9254                        if (permissionsState.grantInstallPermission(bp) !=
9255                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9256                            changedInstallPermission = true;
9257                        }
9258                    } break;
9259
9260                    case GRANT_RUNTIME: {
9261                        // Grant previously granted runtime permissions.
9262                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9263                            PermissionState permissionState = origPermissions
9264                                    .getRuntimePermissionState(bp.name, userId);
9265                            int flags = permissionState != null
9266                                    ? permissionState.getFlags() : 0;
9267                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9268                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9269                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9270                                    // If we cannot put the permission as it was, we have to write.
9271                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9272                                            changedRuntimePermissionUserIds, userId);
9273                                }
9274                                // If the app supports runtime permissions no need for a review.
9275                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9276                                        && appSupportsRuntimePermissions
9277                                        && (flags & PackageManager
9278                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9279                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9280                                    // Since we changed the flags, we have to write.
9281                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9282                                            changedRuntimePermissionUserIds, userId);
9283                                }
9284                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9285                                    && !appSupportsRuntimePermissions) {
9286                                // For legacy apps that need a permission review, every new
9287                                // runtime permission is granted but it is pending a review.
9288                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9289                                    permissionsState.grantRuntimePermission(bp, userId);
9290                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9291                                    // We changed the permission and flags, hence have to write.
9292                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9293                                            changedRuntimePermissionUserIds, userId);
9294                                }
9295                            }
9296                            // Propagate the permission flags.
9297                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9298                        }
9299                    } break;
9300
9301                    case GRANT_UPGRADE: {
9302                        // Grant runtime permissions for a previously held install permission.
9303                        PermissionState permissionState = origPermissions
9304                                .getInstallPermissionState(bp.name);
9305                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9306
9307                        if (origPermissions.revokeInstallPermission(bp)
9308                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9309                            // We will be transferring the permission flags, so clear them.
9310                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9311                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9312                            changedInstallPermission = true;
9313                        }
9314
9315                        // If the permission is not to be promoted to runtime we ignore it and
9316                        // also its other flags as they are not applicable to install permissions.
9317                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9318                            for (int userId : currentUserIds) {
9319                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9320                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9321                                    // Transfer the permission flags.
9322                                    permissionsState.updatePermissionFlags(bp, userId,
9323                                            flags, flags);
9324                                    // If we granted the permission, we have to write.
9325                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9326                                            changedRuntimePermissionUserIds, userId);
9327                                }
9328                            }
9329                        }
9330                    } break;
9331
9332                    default: {
9333                        if (packageOfInterest == null
9334                                || packageOfInterest.equals(pkg.packageName)) {
9335                            Slog.w(TAG, "Not granting permission " + perm
9336                                    + " to package " + pkg.packageName
9337                                    + " because it was previously installed without");
9338                        }
9339                    } break;
9340                }
9341            } else {
9342                if (permissionsState.revokeInstallPermission(bp) !=
9343                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9344                    // Also drop the permission flags.
9345                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9346                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9347                    changedInstallPermission = true;
9348                    Slog.i(TAG, "Un-granting permission " + perm
9349                            + " from package " + pkg.packageName
9350                            + " (protectionLevel=" + bp.protectionLevel
9351                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9352                            + ")");
9353                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9354                    // Don't print warning for app op permissions, since it is fine for them
9355                    // not to be granted, there is a UI for the user to decide.
9356                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9357                        Slog.w(TAG, "Not granting permission " + perm
9358                                + " to package " + pkg.packageName
9359                                + " (protectionLevel=" + bp.protectionLevel
9360                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9361                                + ")");
9362                    }
9363                }
9364            }
9365        }
9366
9367        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9368                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9369            // This is the first that we have heard about this package, so the
9370            // permissions we have now selected are fixed until explicitly
9371            // changed.
9372            ps.installPermissionsFixed = true;
9373        }
9374
9375        // Persist the runtime permissions state for users with changes. If permissions
9376        // were revoked because no app in the shared user declares them we have to
9377        // write synchronously to avoid losing runtime permissions state.
9378        for (int userId : changedRuntimePermissionUserIds) {
9379            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9380        }
9381
9382        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9383    }
9384
9385    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9386        boolean allowed = false;
9387        final int NP = PackageParser.NEW_PERMISSIONS.length;
9388        for (int ip=0; ip<NP; ip++) {
9389            final PackageParser.NewPermissionInfo npi
9390                    = PackageParser.NEW_PERMISSIONS[ip];
9391            if (npi.name.equals(perm)
9392                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9393                allowed = true;
9394                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9395                        + pkg.packageName);
9396                break;
9397            }
9398        }
9399        return allowed;
9400    }
9401
9402    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9403            BasePermission bp, PermissionsState origPermissions) {
9404        boolean allowed;
9405        allowed = (compareSignatures(
9406                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9407                        == PackageManager.SIGNATURE_MATCH)
9408                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9409                        == PackageManager.SIGNATURE_MATCH);
9410        if (!allowed && (bp.protectionLevel
9411                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9412            if (isSystemApp(pkg)) {
9413                // For updated system applications, a system permission
9414                // is granted only if it had been defined by the original application.
9415                if (pkg.isUpdatedSystemApp()) {
9416                    final PackageSetting sysPs = mSettings
9417                            .getDisabledSystemPkgLPr(pkg.packageName);
9418                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9419                        // If the original was granted this permission, we take
9420                        // that grant decision as read and propagate it to the
9421                        // update.
9422                        if (sysPs.isPrivileged()) {
9423                            allowed = true;
9424                        }
9425                    } else {
9426                        // The system apk may have been updated with an older
9427                        // version of the one on the data partition, but which
9428                        // granted a new system permission that it didn't have
9429                        // before.  In this case we do want to allow the app to
9430                        // now get the new permission if the ancestral apk is
9431                        // privileged to get it.
9432                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9433                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9434                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9435                                    allowed = true;
9436                                    break;
9437                                }
9438                            }
9439                        }
9440                        // Also if a privileged parent package on the system image or any of
9441                        // its children requested a privileged permission, the updated child
9442                        // packages can also get the permission.
9443                        if (pkg.parentPackage != null) {
9444                            final PackageSetting disabledSysParentPs = mSettings
9445                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9446                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9447                                    && disabledSysParentPs.isPrivileged()) {
9448                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9449                                    allowed = true;
9450                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9451                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9452                                    for (int i = 0; i < count; i++) {
9453                                        PackageParser.Package disabledSysChildPkg =
9454                                                disabledSysParentPs.pkg.childPackages.get(i);
9455                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9456                                                perm)) {
9457                                            allowed = true;
9458                                            break;
9459                                        }
9460                                    }
9461                                }
9462                            }
9463                        }
9464                    }
9465                } else {
9466                    allowed = isPrivilegedApp(pkg);
9467                }
9468            }
9469        }
9470        if (!allowed) {
9471            if (!allowed && (bp.protectionLevel
9472                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9473                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9474                // If this was a previously normal/dangerous permission that got moved
9475                // to a system permission as part of the runtime permission redesign, then
9476                // we still want to blindly grant it to old apps.
9477                allowed = true;
9478            }
9479            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9480                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9481                // If this permission is to be granted to the system installer and
9482                // this app is an installer, then it gets the permission.
9483                allowed = true;
9484            }
9485            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9486                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9487                // If this permission is to be granted to the system verifier and
9488                // this app is a verifier, then it gets the permission.
9489                allowed = true;
9490            }
9491            if (!allowed && (bp.protectionLevel
9492                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9493                    && isSystemApp(pkg)) {
9494                // Any pre-installed system app is allowed to get this permission.
9495                allowed = true;
9496            }
9497            if (!allowed && (bp.protectionLevel
9498                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9499                // For development permissions, a development permission
9500                // is granted only if it was already granted.
9501                allowed = origPermissions.hasInstallPermission(perm);
9502            }
9503        }
9504        return allowed;
9505    }
9506
9507    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9508        final int permCount = pkg.requestedPermissions.size();
9509        for (int j = 0; j < permCount; j++) {
9510            String requestedPermission = pkg.requestedPermissions.get(j);
9511            if (permission.equals(requestedPermission)) {
9512                return true;
9513            }
9514        }
9515        return false;
9516    }
9517
9518    final class ActivityIntentResolver
9519            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9520        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9521                boolean defaultOnly, int userId) {
9522            if (!sUserManager.exists(userId)) return null;
9523            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9524            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9525        }
9526
9527        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9528                int userId) {
9529            if (!sUserManager.exists(userId)) return null;
9530            mFlags = flags;
9531            return super.queryIntent(intent, resolvedType,
9532                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9533        }
9534
9535        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9536                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9537            if (!sUserManager.exists(userId)) return null;
9538            if (packageActivities == null) {
9539                return null;
9540            }
9541            mFlags = flags;
9542            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9543            final int N = packageActivities.size();
9544            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9545                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9546
9547            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9548            for (int i = 0; i < N; ++i) {
9549                intentFilters = packageActivities.get(i).intents;
9550                if (intentFilters != null && intentFilters.size() > 0) {
9551                    PackageParser.ActivityIntentInfo[] array =
9552                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9553                    intentFilters.toArray(array);
9554                    listCut.add(array);
9555                }
9556            }
9557            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9558        }
9559
9560        public final void addActivity(PackageParser.Activity a, String type) {
9561            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9562            mActivities.put(a.getComponentName(), a);
9563            if (DEBUG_SHOW_INFO)
9564                Log.v(
9565                TAG, "  " + type + " " +
9566                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9567            if (DEBUG_SHOW_INFO)
9568                Log.v(TAG, "    Class=" + a.info.name);
9569            final int NI = a.intents.size();
9570            for (int j=0; j<NI; j++) {
9571                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9572                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9573                    intent.setPriority(0);
9574                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9575                            + a.className + " with priority > 0, forcing to 0");
9576                }
9577                if (DEBUG_SHOW_INFO) {
9578                    Log.v(TAG, "    IntentFilter:");
9579                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9580                }
9581                if (!intent.debugCheck()) {
9582                    Log.w(TAG, "==> For Activity " + a.info.name);
9583                }
9584                addFilter(intent);
9585            }
9586        }
9587
9588        public final void removeActivity(PackageParser.Activity a, String type) {
9589            mActivities.remove(a.getComponentName());
9590            if (DEBUG_SHOW_INFO) {
9591                Log.v(TAG, "  " + type + " "
9592                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9593                                : a.info.name) + ":");
9594                Log.v(TAG, "    Class=" + a.info.name);
9595            }
9596            final int NI = a.intents.size();
9597            for (int j=0; j<NI; j++) {
9598                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9599                if (DEBUG_SHOW_INFO) {
9600                    Log.v(TAG, "    IntentFilter:");
9601                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9602                }
9603                removeFilter(intent);
9604            }
9605        }
9606
9607        @Override
9608        protected boolean allowFilterResult(
9609                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9610            ActivityInfo filterAi = filter.activity.info;
9611            for (int i=dest.size()-1; i>=0; i--) {
9612                ActivityInfo destAi = dest.get(i).activityInfo;
9613                if (destAi.name == filterAi.name
9614                        && destAi.packageName == filterAi.packageName) {
9615                    return false;
9616                }
9617            }
9618            return true;
9619        }
9620
9621        @Override
9622        protected ActivityIntentInfo[] newArray(int size) {
9623            return new ActivityIntentInfo[size];
9624        }
9625
9626        @Override
9627        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9628            if (!sUserManager.exists(userId)) return true;
9629            PackageParser.Package p = filter.activity.owner;
9630            if (p != null) {
9631                PackageSetting ps = (PackageSetting)p.mExtras;
9632                if (ps != null) {
9633                    // System apps are never considered stopped for purposes of
9634                    // filtering, because there may be no way for the user to
9635                    // actually re-launch them.
9636                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9637                            && ps.getStopped(userId);
9638                }
9639            }
9640            return false;
9641        }
9642
9643        @Override
9644        protected boolean isPackageForFilter(String packageName,
9645                PackageParser.ActivityIntentInfo info) {
9646            return packageName.equals(info.activity.owner.packageName);
9647        }
9648
9649        @Override
9650        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9651                int match, int userId) {
9652            if (!sUserManager.exists(userId)) return null;
9653            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9654                return null;
9655            }
9656            final PackageParser.Activity activity = info.activity;
9657            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9658            if (ps == null) {
9659                return null;
9660            }
9661            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9662                    ps.readUserState(userId), userId);
9663            if (ai == null) {
9664                return null;
9665            }
9666            final ResolveInfo res = new ResolveInfo();
9667            res.activityInfo = ai;
9668            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9669                res.filter = info;
9670            }
9671            if (info != null) {
9672                res.handleAllWebDataURI = info.handleAllWebDataURI();
9673            }
9674            res.priority = info.getPriority();
9675            res.preferredOrder = activity.owner.mPreferredOrder;
9676            //System.out.println("Result: " + res.activityInfo.className +
9677            //                   " = " + res.priority);
9678            res.match = match;
9679            res.isDefault = info.hasDefault;
9680            res.labelRes = info.labelRes;
9681            res.nonLocalizedLabel = info.nonLocalizedLabel;
9682            if (userNeedsBadging(userId)) {
9683                res.noResourceId = true;
9684            } else {
9685                res.icon = info.icon;
9686            }
9687            res.iconResourceId = info.icon;
9688            res.system = res.activityInfo.applicationInfo.isSystemApp();
9689            return res;
9690        }
9691
9692        @Override
9693        protected void sortResults(List<ResolveInfo> results) {
9694            Collections.sort(results, mResolvePrioritySorter);
9695        }
9696
9697        @Override
9698        protected void dumpFilter(PrintWriter out, String prefix,
9699                PackageParser.ActivityIntentInfo filter) {
9700            out.print(prefix); out.print(
9701                    Integer.toHexString(System.identityHashCode(filter.activity)));
9702                    out.print(' ');
9703                    filter.activity.printComponentShortName(out);
9704                    out.print(" filter ");
9705                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9706        }
9707
9708        @Override
9709        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9710            return filter.activity;
9711        }
9712
9713        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9714            PackageParser.Activity activity = (PackageParser.Activity)label;
9715            out.print(prefix); out.print(
9716                    Integer.toHexString(System.identityHashCode(activity)));
9717                    out.print(' ');
9718                    activity.printComponentShortName(out);
9719            if (count > 1) {
9720                out.print(" ("); out.print(count); out.print(" filters)");
9721            }
9722            out.println();
9723        }
9724
9725//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9726//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9727//            final List<ResolveInfo> retList = Lists.newArrayList();
9728//            while (i.hasNext()) {
9729//                final ResolveInfo resolveInfo = i.next();
9730//                if (isEnabledLP(resolveInfo.activityInfo)) {
9731//                    retList.add(resolveInfo);
9732//                }
9733//            }
9734//            return retList;
9735//        }
9736
9737        // Keys are String (activity class name), values are Activity.
9738        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9739                = new ArrayMap<ComponentName, PackageParser.Activity>();
9740        private int mFlags;
9741    }
9742
9743    private final class ServiceIntentResolver
9744            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9745        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9746                boolean defaultOnly, int userId) {
9747            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9748            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9749        }
9750
9751        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9752                int userId) {
9753            if (!sUserManager.exists(userId)) return null;
9754            mFlags = flags;
9755            return super.queryIntent(intent, resolvedType,
9756                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9757        }
9758
9759        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9760                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9761            if (!sUserManager.exists(userId)) return null;
9762            if (packageServices == null) {
9763                return null;
9764            }
9765            mFlags = flags;
9766            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9767            final int N = packageServices.size();
9768            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9769                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9770
9771            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9772            for (int i = 0; i < N; ++i) {
9773                intentFilters = packageServices.get(i).intents;
9774                if (intentFilters != null && intentFilters.size() > 0) {
9775                    PackageParser.ServiceIntentInfo[] array =
9776                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9777                    intentFilters.toArray(array);
9778                    listCut.add(array);
9779                }
9780            }
9781            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9782        }
9783
9784        public final void addService(PackageParser.Service s) {
9785            mServices.put(s.getComponentName(), s);
9786            if (DEBUG_SHOW_INFO) {
9787                Log.v(TAG, "  "
9788                        + (s.info.nonLocalizedLabel != null
9789                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9790                Log.v(TAG, "    Class=" + s.info.name);
9791            }
9792            final int NI = s.intents.size();
9793            int j;
9794            for (j=0; j<NI; j++) {
9795                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9796                if (DEBUG_SHOW_INFO) {
9797                    Log.v(TAG, "    IntentFilter:");
9798                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9799                }
9800                if (!intent.debugCheck()) {
9801                    Log.w(TAG, "==> For Service " + s.info.name);
9802                }
9803                addFilter(intent);
9804            }
9805        }
9806
9807        public final void removeService(PackageParser.Service s) {
9808            mServices.remove(s.getComponentName());
9809            if (DEBUG_SHOW_INFO) {
9810                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9811                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9812                Log.v(TAG, "    Class=" + s.info.name);
9813            }
9814            final int NI = s.intents.size();
9815            int j;
9816            for (j=0; j<NI; j++) {
9817                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9818                if (DEBUG_SHOW_INFO) {
9819                    Log.v(TAG, "    IntentFilter:");
9820                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9821                }
9822                removeFilter(intent);
9823            }
9824        }
9825
9826        @Override
9827        protected boolean allowFilterResult(
9828                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9829            ServiceInfo filterSi = filter.service.info;
9830            for (int i=dest.size()-1; i>=0; i--) {
9831                ServiceInfo destAi = dest.get(i).serviceInfo;
9832                if (destAi.name == filterSi.name
9833                        && destAi.packageName == filterSi.packageName) {
9834                    return false;
9835                }
9836            }
9837            return true;
9838        }
9839
9840        @Override
9841        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9842            return new PackageParser.ServiceIntentInfo[size];
9843        }
9844
9845        @Override
9846        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9847            if (!sUserManager.exists(userId)) return true;
9848            PackageParser.Package p = filter.service.owner;
9849            if (p != null) {
9850                PackageSetting ps = (PackageSetting)p.mExtras;
9851                if (ps != null) {
9852                    // System apps are never considered stopped for purposes of
9853                    // filtering, because there may be no way for the user to
9854                    // actually re-launch them.
9855                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9856                            && ps.getStopped(userId);
9857                }
9858            }
9859            return false;
9860        }
9861
9862        @Override
9863        protected boolean isPackageForFilter(String packageName,
9864                PackageParser.ServiceIntentInfo info) {
9865            return packageName.equals(info.service.owner.packageName);
9866        }
9867
9868        @Override
9869        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9870                int match, int userId) {
9871            if (!sUserManager.exists(userId)) return null;
9872            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9873            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9874                return null;
9875            }
9876            final PackageParser.Service service = info.service;
9877            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9878            if (ps == null) {
9879                return null;
9880            }
9881            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9882                    ps.readUserState(userId), userId);
9883            if (si == null) {
9884                return null;
9885            }
9886            final ResolveInfo res = new ResolveInfo();
9887            res.serviceInfo = si;
9888            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9889                res.filter = filter;
9890            }
9891            res.priority = info.getPriority();
9892            res.preferredOrder = service.owner.mPreferredOrder;
9893            res.match = match;
9894            res.isDefault = info.hasDefault;
9895            res.labelRes = info.labelRes;
9896            res.nonLocalizedLabel = info.nonLocalizedLabel;
9897            res.icon = info.icon;
9898            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9899            return res;
9900        }
9901
9902        @Override
9903        protected void sortResults(List<ResolveInfo> results) {
9904            Collections.sort(results, mResolvePrioritySorter);
9905        }
9906
9907        @Override
9908        protected void dumpFilter(PrintWriter out, String prefix,
9909                PackageParser.ServiceIntentInfo filter) {
9910            out.print(prefix); out.print(
9911                    Integer.toHexString(System.identityHashCode(filter.service)));
9912                    out.print(' ');
9913                    filter.service.printComponentShortName(out);
9914                    out.print(" filter ");
9915                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9916        }
9917
9918        @Override
9919        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9920            return filter.service;
9921        }
9922
9923        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9924            PackageParser.Service service = (PackageParser.Service)label;
9925            out.print(prefix); out.print(
9926                    Integer.toHexString(System.identityHashCode(service)));
9927                    out.print(' ');
9928                    service.printComponentShortName(out);
9929            if (count > 1) {
9930                out.print(" ("); out.print(count); out.print(" filters)");
9931            }
9932            out.println();
9933        }
9934
9935//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9936//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9937//            final List<ResolveInfo> retList = Lists.newArrayList();
9938//            while (i.hasNext()) {
9939//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9940//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9941//                    retList.add(resolveInfo);
9942//                }
9943//            }
9944//            return retList;
9945//        }
9946
9947        // Keys are String (activity class name), values are Activity.
9948        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9949                = new ArrayMap<ComponentName, PackageParser.Service>();
9950        private int mFlags;
9951    };
9952
9953    private final class ProviderIntentResolver
9954            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9955        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9956                boolean defaultOnly, int userId) {
9957            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9958            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9959        }
9960
9961        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9962                int userId) {
9963            if (!sUserManager.exists(userId))
9964                return null;
9965            mFlags = flags;
9966            return super.queryIntent(intent, resolvedType,
9967                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9968        }
9969
9970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9971                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9972            if (!sUserManager.exists(userId))
9973                return null;
9974            if (packageProviders == null) {
9975                return null;
9976            }
9977            mFlags = flags;
9978            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9979            final int N = packageProviders.size();
9980            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9981                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9982
9983            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9984            for (int i = 0; i < N; ++i) {
9985                intentFilters = packageProviders.get(i).intents;
9986                if (intentFilters != null && intentFilters.size() > 0) {
9987                    PackageParser.ProviderIntentInfo[] array =
9988                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9989                    intentFilters.toArray(array);
9990                    listCut.add(array);
9991                }
9992            }
9993            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9994        }
9995
9996        public final void addProvider(PackageParser.Provider p) {
9997            if (mProviders.containsKey(p.getComponentName())) {
9998                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9999                return;
10000            }
10001
10002            mProviders.put(p.getComponentName(), p);
10003            if (DEBUG_SHOW_INFO) {
10004                Log.v(TAG, "  "
10005                        + (p.info.nonLocalizedLabel != null
10006                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10007                Log.v(TAG, "    Class=" + p.info.name);
10008            }
10009            final int NI = p.intents.size();
10010            int j;
10011            for (j = 0; j < NI; j++) {
10012                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10013                if (DEBUG_SHOW_INFO) {
10014                    Log.v(TAG, "    IntentFilter:");
10015                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10016                }
10017                if (!intent.debugCheck()) {
10018                    Log.w(TAG, "==> For Provider " + p.info.name);
10019                }
10020                addFilter(intent);
10021            }
10022        }
10023
10024        public final void removeProvider(PackageParser.Provider p) {
10025            mProviders.remove(p.getComponentName());
10026            if (DEBUG_SHOW_INFO) {
10027                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10028                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10029                Log.v(TAG, "    Class=" + p.info.name);
10030            }
10031            final int NI = p.intents.size();
10032            int j;
10033            for (j = 0; j < NI; j++) {
10034                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10035                if (DEBUG_SHOW_INFO) {
10036                    Log.v(TAG, "    IntentFilter:");
10037                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10038                }
10039                removeFilter(intent);
10040            }
10041        }
10042
10043        @Override
10044        protected boolean allowFilterResult(
10045                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10046            ProviderInfo filterPi = filter.provider.info;
10047            for (int i = dest.size() - 1; i >= 0; i--) {
10048                ProviderInfo destPi = dest.get(i).providerInfo;
10049                if (destPi.name == filterPi.name
10050                        && destPi.packageName == filterPi.packageName) {
10051                    return false;
10052                }
10053            }
10054            return true;
10055        }
10056
10057        @Override
10058        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10059            return new PackageParser.ProviderIntentInfo[size];
10060        }
10061
10062        @Override
10063        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10064            if (!sUserManager.exists(userId))
10065                return true;
10066            PackageParser.Package p = filter.provider.owner;
10067            if (p != null) {
10068                PackageSetting ps = (PackageSetting) p.mExtras;
10069                if (ps != null) {
10070                    // System apps are never considered stopped for purposes of
10071                    // filtering, because there may be no way for the user to
10072                    // actually re-launch them.
10073                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10074                            && ps.getStopped(userId);
10075                }
10076            }
10077            return false;
10078        }
10079
10080        @Override
10081        protected boolean isPackageForFilter(String packageName,
10082                PackageParser.ProviderIntentInfo info) {
10083            return packageName.equals(info.provider.owner.packageName);
10084        }
10085
10086        @Override
10087        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10088                int match, int userId) {
10089            if (!sUserManager.exists(userId))
10090                return null;
10091            final PackageParser.ProviderIntentInfo info = filter;
10092            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10093                return null;
10094            }
10095            final PackageParser.Provider provider = info.provider;
10096            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10097            if (ps == null) {
10098                return null;
10099            }
10100            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10101                    ps.readUserState(userId), userId);
10102            if (pi == null) {
10103                return null;
10104            }
10105            final ResolveInfo res = new ResolveInfo();
10106            res.providerInfo = pi;
10107            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10108                res.filter = filter;
10109            }
10110            res.priority = info.getPriority();
10111            res.preferredOrder = provider.owner.mPreferredOrder;
10112            res.match = match;
10113            res.isDefault = info.hasDefault;
10114            res.labelRes = info.labelRes;
10115            res.nonLocalizedLabel = info.nonLocalizedLabel;
10116            res.icon = info.icon;
10117            res.system = res.providerInfo.applicationInfo.isSystemApp();
10118            return res;
10119        }
10120
10121        @Override
10122        protected void sortResults(List<ResolveInfo> results) {
10123            Collections.sort(results, mResolvePrioritySorter);
10124        }
10125
10126        @Override
10127        protected void dumpFilter(PrintWriter out, String prefix,
10128                PackageParser.ProviderIntentInfo filter) {
10129            out.print(prefix);
10130            out.print(
10131                    Integer.toHexString(System.identityHashCode(filter.provider)));
10132            out.print(' ');
10133            filter.provider.printComponentShortName(out);
10134            out.print(" filter ");
10135            out.println(Integer.toHexString(System.identityHashCode(filter)));
10136        }
10137
10138        @Override
10139        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10140            return filter.provider;
10141        }
10142
10143        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10144            PackageParser.Provider provider = (PackageParser.Provider)label;
10145            out.print(prefix); out.print(
10146                    Integer.toHexString(System.identityHashCode(provider)));
10147                    out.print(' ');
10148                    provider.printComponentShortName(out);
10149            if (count > 1) {
10150                out.print(" ("); out.print(count); out.print(" filters)");
10151            }
10152            out.println();
10153        }
10154
10155        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10156                = new ArrayMap<ComponentName, PackageParser.Provider>();
10157        private int mFlags;
10158    }
10159
10160    private static final class EphemeralIntentResolver
10161            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10162        @Override
10163        protected EphemeralResolveIntentInfo[] newArray(int size) {
10164            return new EphemeralResolveIntentInfo[size];
10165        }
10166
10167        @Override
10168        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10169            return true;
10170        }
10171
10172        @Override
10173        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10174                int userId) {
10175            if (!sUserManager.exists(userId)) {
10176                return null;
10177            }
10178            return info.getEphemeralResolveInfo();
10179        }
10180    }
10181
10182    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10183            new Comparator<ResolveInfo>() {
10184        public int compare(ResolveInfo r1, ResolveInfo r2) {
10185            int v1 = r1.priority;
10186            int v2 = r2.priority;
10187            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10188            if (v1 != v2) {
10189                return (v1 > v2) ? -1 : 1;
10190            }
10191            v1 = r1.preferredOrder;
10192            v2 = r2.preferredOrder;
10193            if (v1 != v2) {
10194                return (v1 > v2) ? -1 : 1;
10195            }
10196            if (r1.isDefault != r2.isDefault) {
10197                return r1.isDefault ? -1 : 1;
10198            }
10199            v1 = r1.match;
10200            v2 = r2.match;
10201            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10202            if (v1 != v2) {
10203                return (v1 > v2) ? -1 : 1;
10204            }
10205            if (r1.system != r2.system) {
10206                return r1.system ? -1 : 1;
10207            }
10208            if (r1.activityInfo != null) {
10209                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10210            }
10211            if (r1.serviceInfo != null) {
10212                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10213            }
10214            if (r1.providerInfo != null) {
10215                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10216            }
10217            return 0;
10218        }
10219    };
10220
10221    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10222            new Comparator<ProviderInfo>() {
10223        public int compare(ProviderInfo p1, ProviderInfo p2) {
10224            final int v1 = p1.initOrder;
10225            final int v2 = p2.initOrder;
10226            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10227        }
10228    };
10229
10230    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10231            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10232            final int[] userIds) {
10233        mHandler.post(new Runnable() {
10234            @Override
10235            public void run() {
10236                try {
10237                    final IActivityManager am = ActivityManagerNative.getDefault();
10238                    if (am == null) return;
10239                    final int[] resolvedUserIds;
10240                    if (userIds == null) {
10241                        resolvedUserIds = am.getRunningUserIds();
10242                    } else {
10243                        resolvedUserIds = userIds;
10244                    }
10245                    for (int id : resolvedUserIds) {
10246                        final Intent intent = new Intent(action,
10247                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10248                        if (extras != null) {
10249                            intent.putExtras(extras);
10250                        }
10251                        if (targetPkg != null) {
10252                            intent.setPackage(targetPkg);
10253                        }
10254                        // Modify the UID when posting to other users
10255                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10256                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10257                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10258                            intent.putExtra(Intent.EXTRA_UID, uid);
10259                        }
10260                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10261                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10262                        if (DEBUG_BROADCASTS) {
10263                            RuntimeException here = new RuntimeException("here");
10264                            here.fillInStackTrace();
10265                            Slog.d(TAG, "Sending to user " + id + ": "
10266                                    + intent.toShortString(false, true, false, false)
10267                                    + " " + intent.getExtras(), here);
10268                        }
10269                        am.broadcastIntent(null, intent, null, finishedReceiver,
10270                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10271                                null, finishedReceiver != null, false, id);
10272                    }
10273                } catch (RemoteException ex) {
10274                }
10275            }
10276        });
10277    }
10278
10279    /**
10280     * Check if the external storage media is available. This is true if there
10281     * is a mounted external storage medium or if the external storage is
10282     * emulated.
10283     */
10284    private boolean isExternalMediaAvailable() {
10285        return mMediaMounted || Environment.isExternalStorageEmulated();
10286    }
10287
10288    @Override
10289    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10290        // writer
10291        synchronized (mPackages) {
10292            if (!isExternalMediaAvailable()) {
10293                // If the external storage is no longer mounted at this point,
10294                // the caller may not have been able to delete all of this
10295                // packages files and can not delete any more.  Bail.
10296                return null;
10297            }
10298            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10299            if (lastPackage != null) {
10300                pkgs.remove(lastPackage);
10301            }
10302            if (pkgs.size() > 0) {
10303                return pkgs.get(0);
10304            }
10305        }
10306        return null;
10307    }
10308
10309    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10310        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10311                userId, andCode ? 1 : 0, packageName);
10312        if (mSystemReady) {
10313            msg.sendToTarget();
10314        } else {
10315            if (mPostSystemReadyMessages == null) {
10316                mPostSystemReadyMessages = new ArrayList<>();
10317            }
10318            mPostSystemReadyMessages.add(msg);
10319        }
10320    }
10321
10322    void startCleaningPackages() {
10323        // reader
10324        synchronized (mPackages) {
10325            if (!isExternalMediaAvailable()) {
10326                return;
10327            }
10328            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10329                return;
10330            }
10331        }
10332        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10333        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10334        IActivityManager am = ActivityManagerNative.getDefault();
10335        if (am != null) {
10336            try {
10337                am.startService(null, intent, null, mContext.getOpPackageName(),
10338                        UserHandle.USER_SYSTEM);
10339            } catch (RemoteException e) {
10340            }
10341        }
10342    }
10343
10344    @Override
10345    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10346            int installFlags, String installerPackageName, VerificationParams verificationParams,
10347            String packageAbiOverride) {
10348        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10349                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10350    }
10351
10352    @Override
10353    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10354            int installFlags, String installerPackageName, VerificationParams verificationParams,
10355            String packageAbiOverride, int userId) {
10356        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10357
10358        final int callingUid = Binder.getCallingUid();
10359        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10360
10361        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10362            try {
10363                if (observer != null) {
10364                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10365                }
10366            } catch (RemoteException re) {
10367            }
10368            return;
10369        }
10370
10371        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10372            installFlags |= PackageManager.INSTALL_FROM_ADB;
10373
10374        } else {
10375            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10376            // about installerPackageName.
10377
10378            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10379            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10380        }
10381
10382        UserHandle user;
10383        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10384            user = UserHandle.ALL;
10385        } else {
10386            user = new UserHandle(userId);
10387        }
10388
10389        // Only system components can circumvent runtime permissions when installing.
10390        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10391                && mContext.checkCallingOrSelfPermission(Manifest.permission
10392                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10393            throw new SecurityException("You need the "
10394                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10395                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10396        }
10397
10398        verificationParams.setInstallerUid(callingUid);
10399
10400        final File originFile = new File(originPath);
10401        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10402
10403        final Message msg = mHandler.obtainMessage(INIT_COPY);
10404        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10405                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10406        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10407        msg.obj = params;
10408
10409        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10410                System.identityHashCode(msg.obj));
10411        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10412                System.identityHashCode(msg.obj));
10413
10414        mHandler.sendMessage(msg);
10415    }
10416
10417    void installStage(String packageName, File stagedDir, String stagedCid,
10418            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10419            String installerPackageName, int installerUid, UserHandle user) {
10420        if (DEBUG_EPHEMERAL) {
10421            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10422                Slog.d(TAG, "Ephemeral install of " + packageName);
10423            }
10424        }
10425        final VerificationParams verifParams = new VerificationParams(
10426                null, sessionParams.originatingUri, sessionParams.referrerUri,
10427                sessionParams.originatingUid);
10428        verifParams.setInstallerUid(installerUid);
10429
10430        final OriginInfo origin;
10431        if (stagedDir != null) {
10432            origin = OriginInfo.fromStagedFile(stagedDir);
10433        } else {
10434            origin = OriginInfo.fromStagedContainer(stagedCid);
10435        }
10436
10437        final Message msg = mHandler.obtainMessage(INIT_COPY);
10438        final InstallParams params = new InstallParams(origin, null, observer,
10439                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10440                verifParams, user, sessionParams.abiOverride,
10441                sessionParams.grantedRuntimePermissions);
10442        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10443        msg.obj = params;
10444
10445        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10446                System.identityHashCode(msg.obj));
10447        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10448                System.identityHashCode(msg.obj));
10449
10450        mHandler.sendMessage(msg);
10451    }
10452
10453    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10454        Bundle extras = new Bundle(1);
10455        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10456
10457        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10458                packageName, extras, 0, null, null, new int[] {userId});
10459        try {
10460            IActivityManager am = ActivityManagerNative.getDefault();
10461            final boolean isSystem =
10462                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10463            if (isSystem && am.isUserRunning(userId, 0)) {
10464                // The just-installed/enabled app is bundled on the system, so presumed
10465                // to be able to run automatically without needing an explicit launch.
10466                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10467                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10468                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10469                        .setPackage(packageName);
10470                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10471                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10472            }
10473        } catch (RemoteException e) {
10474            // shouldn't happen
10475            Slog.w(TAG, "Unable to bootstrap installed package", e);
10476        }
10477    }
10478
10479    @Override
10480    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10481            int userId) {
10482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10483        PackageSetting pkgSetting;
10484        final int uid = Binder.getCallingUid();
10485        enforceCrossUserPermission(uid, userId, true, true,
10486                "setApplicationHiddenSetting for user " + userId);
10487
10488        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10489            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10490            return false;
10491        }
10492
10493        long callingId = Binder.clearCallingIdentity();
10494        try {
10495            boolean sendAdded = false;
10496            boolean sendRemoved = false;
10497            // writer
10498            synchronized (mPackages) {
10499                pkgSetting = mSettings.mPackages.get(packageName);
10500                if (pkgSetting == null) {
10501                    return false;
10502                }
10503                if (pkgSetting.getHidden(userId) != hidden) {
10504                    pkgSetting.setHidden(hidden, userId);
10505                    mSettings.writePackageRestrictionsLPr(userId);
10506                    if (hidden) {
10507                        sendRemoved = true;
10508                    } else {
10509                        sendAdded = true;
10510                    }
10511                }
10512            }
10513            if (sendAdded) {
10514                sendPackageAddedForUser(packageName, pkgSetting, userId);
10515                return true;
10516            }
10517            if (sendRemoved) {
10518                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10519                        "hiding pkg");
10520                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10521                return true;
10522            }
10523        } finally {
10524            Binder.restoreCallingIdentity(callingId);
10525        }
10526        return false;
10527    }
10528
10529    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10530            int userId) {
10531        final PackageRemovedInfo info = new PackageRemovedInfo();
10532        info.removedPackage = packageName;
10533        info.removedUsers = new int[] {userId};
10534        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10535        info.sendBroadcast(false, false, false);
10536    }
10537
10538    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10539        if (pkgList.length > 0) {
10540            Bundle extras = new Bundle(1);
10541            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10542
10543            sendPackageBroadcast(
10544                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10545                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10546                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10547                    new int[] {userId});
10548        }
10549    }
10550
10551    /**
10552     * Returns true if application is not found or there was an error. Otherwise it returns
10553     * the hidden state of the package for the given user.
10554     */
10555    @Override
10556    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10557        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10558        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10559                false, "getApplicationHidden for user " + userId);
10560        PackageSetting pkgSetting;
10561        long callingId = Binder.clearCallingIdentity();
10562        try {
10563            // writer
10564            synchronized (mPackages) {
10565                pkgSetting = mSettings.mPackages.get(packageName);
10566                if (pkgSetting == null) {
10567                    return true;
10568                }
10569                return pkgSetting.getHidden(userId);
10570            }
10571        } finally {
10572            Binder.restoreCallingIdentity(callingId);
10573        }
10574    }
10575
10576    /**
10577     * @hide
10578     */
10579    @Override
10580    public int installExistingPackageAsUser(String packageName, int userId) {
10581        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10582                null);
10583        PackageSetting pkgSetting;
10584        final int uid = Binder.getCallingUid();
10585        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10586                + userId);
10587        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10588            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10589        }
10590
10591        long callingId = Binder.clearCallingIdentity();
10592        try {
10593            boolean installed = false;
10594
10595            // writer
10596            synchronized (mPackages) {
10597                pkgSetting = mSettings.mPackages.get(packageName);
10598                if (pkgSetting == null) {
10599                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10600                }
10601                if (!pkgSetting.getInstalled(userId)) {
10602                    pkgSetting.setInstalled(true, userId);
10603                    pkgSetting.setHidden(false, userId);
10604                    mSettings.writePackageRestrictionsLPr(userId);
10605                    if (pkgSetting.pkg != null) {
10606                        prepareAppDataAfterInstall(pkgSetting.pkg);
10607                    }
10608                    installed = true;
10609                }
10610            }
10611
10612            if (installed) {
10613                sendPackageAddedForUser(packageName, pkgSetting, userId);
10614            }
10615        } finally {
10616            Binder.restoreCallingIdentity(callingId);
10617        }
10618
10619        return PackageManager.INSTALL_SUCCEEDED;
10620    }
10621
10622    boolean isUserRestricted(int userId, String restrictionKey) {
10623        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10624        if (restrictions.getBoolean(restrictionKey, false)) {
10625            Log.w(TAG, "User is restricted: " + restrictionKey);
10626            return true;
10627        }
10628        return false;
10629    }
10630
10631    @Override
10632    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10633        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10634        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10635                "setPackageSuspended for user " + userId);
10636
10637        // TODO: investigate and add more restrictions for suspending crucial packages.
10638        if (isPackageDeviceAdmin(packageName, userId)) {
10639            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10640                    + "\": has active device admin");
10641            return false;
10642        }
10643
10644        long callingId = Binder.clearCallingIdentity();
10645        try {
10646            boolean changed = false;
10647            boolean success = false;
10648            int appId = -1;
10649            synchronized (mPackages) {
10650                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10651                if (pkgSetting != null) {
10652                    if (pkgSetting.getSuspended(userId) != suspended) {
10653                        pkgSetting.setSuspended(suspended, userId);
10654                        mSettings.writePackageRestrictionsLPr(userId);
10655                        appId = pkgSetting.appId;
10656                        changed = true;
10657                    }
10658                    success = true;
10659                }
10660            }
10661
10662            if (changed) {
10663                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10664                if (suspended) {
10665                    killApplication(packageName, UserHandle.getUid(userId, appId),
10666                            "suspending package");
10667                }
10668            }
10669            return success;
10670        } finally {
10671            Binder.restoreCallingIdentity(callingId);
10672        }
10673    }
10674
10675    @Override
10676    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10677        mContext.enforceCallingOrSelfPermission(
10678                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10679                "Only package verification agents can verify applications");
10680
10681        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10682        final PackageVerificationResponse response = new PackageVerificationResponse(
10683                verificationCode, Binder.getCallingUid());
10684        msg.arg1 = id;
10685        msg.obj = response;
10686        mHandler.sendMessage(msg);
10687    }
10688
10689    @Override
10690    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10691            long millisecondsToDelay) {
10692        mContext.enforceCallingOrSelfPermission(
10693                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10694                "Only package verification agents can extend verification timeouts");
10695
10696        final PackageVerificationState state = mPendingVerification.get(id);
10697        final PackageVerificationResponse response = new PackageVerificationResponse(
10698                verificationCodeAtTimeout, Binder.getCallingUid());
10699
10700        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10701            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10702        }
10703        if (millisecondsToDelay < 0) {
10704            millisecondsToDelay = 0;
10705        }
10706        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10707                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10708            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10709        }
10710
10711        if ((state != null) && !state.timeoutExtended()) {
10712            state.extendTimeout();
10713
10714            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10715            msg.arg1 = id;
10716            msg.obj = response;
10717            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10718        }
10719    }
10720
10721    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10722            int verificationCode, UserHandle user) {
10723        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10724        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10725        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10726        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10727        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10728
10729        mContext.sendBroadcastAsUser(intent, user,
10730                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10731    }
10732
10733    private ComponentName matchComponentForVerifier(String packageName,
10734            List<ResolveInfo> receivers) {
10735        ActivityInfo targetReceiver = null;
10736
10737        final int NR = receivers.size();
10738        for (int i = 0; i < NR; i++) {
10739            final ResolveInfo info = receivers.get(i);
10740            if (info.activityInfo == null) {
10741                continue;
10742            }
10743
10744            if (packageName.equals(info.activityInfo.packageName)) {
10745                targetReceiver = info.activityInfo;
10746                break;
10747            }
10748        }
10749
10750        if (targetReceiver == null) {
10751            return null;
10752        }
10753
10754        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10755    }
10756
10757    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10758            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10759        if (pkgInfo.verifiers.length == 0) {
10760            return null;
10761        }
10762
10763        final int N = pkgInfo.verifiers.length;
10764        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10765        for (int i = 0; i < N; i++) {
10766            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10767
10768            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10769                    receivers);
10770            if (comp == null) {
10771                continue;
10772            }
10773
10774            final int verifierUid = getUidForVerifier(verifierInfo);
10775            if (verifierUid == -1) {
10776                continue;
10777            }
10778
10779            if (DEBUG_VERIFY) {
10780                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10781                        + " with the correct signature");
10782            }
10783            sufficientVerifiers.add(comp);
10784            verificationState.addSufficientVerifier(verifierUid);
10785        }
10786
10787        return sufficientVerifiers;
10788    }
10789
10790    private int getUidForVerifier(VerifierInfo verifierInfo) {
10791        synchronized (mPackages) {
10792            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10793            if (pkg == null) {
10794                return -1;
10795            } else if (pkg.mSignatures.length != 1) {
10796                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10797                        + " has more than one signature; ignoring");
10798                return -1;
10799            }
10800
10801            /*
10802             * If the public key of the package's signature does not match
10803             * our expected public key, then this is a different package and
10804             * we should skip.
10805             */
10806
10807            final byte[] expectedPublicKey;
10808            try {
10809                final Signature verifierSig = pkg.mSignatures[0];
10810                final PublicKey publicKey = verifierSig.getPublicKey();
10811                expectedPublicKey = publicKey.getEncoded();
10812            } catch (CertificateException e) {
10813                return -1;
10814            }
10815
10816            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10817
10818            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10819                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10820                        + " does not have the expected public key; ignoring");
10821                return -1;
10822            }
10823
10824            return pkg.applicationInfo.uid;
10825        }
10826    }
10827
10828    @Override
10829    public void finishPackageInstall(int token) {
10830        enforceSystemOrRoot("Only the system is allowed to finish installs");
10831
10832        if (DEBUG_INSTALL) {
10833            Slog.v(TAG, "BM finishing package install for " + token);
10834        }
10835        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10836
10837        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10838        mHandler.sendMessage(msg);
10839    }
10840
10841    /**
10842     * Get the verification agent timeout.
10843     *
10844     * @return verification timeout in milliseconds
10845     */
10846    private long getVerificationTimeout() {
10847        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10848                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10849                DEFAULT_VERIFICATION_TIMEOUT);
10850    }
10851
10852    /**
10853     * Get the default verification agent response code.
10854     *
10855     * @return default verification response code
10856     */
10857    private int getDefaultVerificationResponse() {
10858        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10859                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10860                DEFAULT_VERIFICATION_RESPONSE);
10861    }
10862
10863    /**
10864     * Check whether or not package verification has been enabled.
10865     *
10866     * @return true if verification should be performed
10867     */
10868    private boolean isVerificationEnabled(int userId, int installFlags) {
10869        if (!DEFAULT_VERIFY_ENABLE) {
10870            return false;
10871        }
10872        // Ephemeral apps don't get the full verification treatment
10873        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10874            if (DEBUG_EPHEMERAL) {
10875                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10876            }
10877            return false;
10878        }
10879
10880        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10881
10882        // Check if installing from ADB
10883        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10884            // Do not run verification in a test harness environment
10885            if (ActivityManager.isRunningInTestHarness()) {
10886                return false;
10887            }
10888            if (ensureVerifyAppsEnabled) {
10889                return true;
10890            }
10891            // Check if the developer does not want package verification for ADB installs
10892            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10893                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10894                return false;
10895            }
10896        }
10897
10898        if (ensureVerifyAppsEnabled) {
10899            return true;
10900        }
10901
10902        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10903                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10904    }
10905
10906    @Override
10907    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10908            throws RemoteException {
10909        mContext.enforceCallingOrSelfPermission(
10910                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10911                "Only intentfilter verification agents can verify applications");
10912
10913        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10914        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10915                Binder.getCallingUid(), verificationCode, failedDomains);
10916        msg.arg1 = id;
10917        msg.obj = response;
10918        mHandler.sendMessage(msg);
10919    }
10920
10921    @Override
10922    public int getIntentVerificationStatus(String packageName, int userId) {
10923        synchronized (mPackages) {
10924            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10925        }
10926    }
10927
10928    @Override
10929    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10930        mContext.enforceCallingOrSelfPermission(
10931                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10932
10933        boolean result = false;
10934        synchronized (mPackages) {
10935            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10936        }
10937        if (result) {
10938            scheduleWritePackageRestrictionsLocked(userId);
10939        }
10940        return result;
10941    }
10942
10943    @Override
10944    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10945        synchronized (mPackages) {
10946            return mSettings.getIntentFilterVerificationsLPr(packageName);
10947        }
10948    }
10949
10950    @Override
10951    public List<IntentFilter> getAllIntentFilters(String packageName) {
10952        if (TextUtils.isEmpty(packageName)) {
10953            return Collections.<IntentFilter>emptyList();
10954        }
10955        synchronized (mPackages) {
10956            PackageParser.Package pkg = mPackages.get(packageName);
10957            if (pkg == null || pkg.activities == null) {
10958                return Collections.<IntentFilter>emptyList();
10959            }
10960            final int count = pkg.activities.size();
10961            ArrayList<IntentFilter> result = new ArrayList<>();
10962            for (int n=0; n<count; n++) {
10963                PackageParser.Activity activity = pkg.activities.get(n);
10964                if (activity.intents != null && activity.intents.size() > 0) {
10965                    result.addAll(activity.intents);
10966                }
10967            }
10968            return result;
10969        }
10970    }
10971
10972    @Override
10973    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10974        mContext.enforceCallingOrSelfPermission(
10975                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10976
10977        synchronized (mPackages) {
10978            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10979            if (packageName != null) {
10980                result |= updateIntentVerificationStatus(packageName,
10981                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10982                        userId);
10983                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10984                        packageName, userId);
10985            }
10986            return result;
10987        }
10988    }
10989
10990    @Override
10991    public String getDefaultBrowserPackageName(int userId) {
10992        synchronized (mPackages) {
10993            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10994        }
10995    }
10996
10997    /**
10998     * Get the "allow unknown sources" setting.
10999     *
11000     * @return the current "allow unknown sources" setting
11001     */
11002    private int getUnknownSourcesSettings() {
11003        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11004                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11005                -1);
11006    }
11007
11008    @Override
11009    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11010        final int uid = Binder.getCallingUid();
11011        // writer
11012        synchronized (mPackages) {
11013            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11014            if (targetPackageSetting == null) {
11015                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11016            }
11017
11018            PackageSetting installerPackageSetting;
11019            if (installerPackageName != null) {
11020                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11021                if (installerPackageSetting == null) {
11022                    throw new IllegalArgumentException("Unknown installer package: "
11023                            + installerPackageName);
11024                }
11025            } else {
11026                installerPackageSetting = null;
11027            }
11028
11029            Signature[] callerSignature;
11030            Object obj = mSettings.getUserIdLPr(uid);
11031            if (obj != null) {
11032                if (obj instanceof SharedUserSetting) {
11033                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11034                } else if (obj instanceof PackageSetting) {
11035                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11036                } else {
11037                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11038                }
11039            } else {
11040                throw new SecurityException("Unknown calling UID: " + uid);
11041            }
11042
11043            // Verify: can't set installerPackageName to a package that is
11044            // not signed with the same cert as the caller.
11045            if (installerPackageSetting != null) {
11046                if (compareSignatures(callerSignature,
11047                        installerPackageSetting.signatures.mSignatures)
11048                        != PackageManager.SIGNATURE_MATCH) {
11049                    throw new SecurityException(
11050                            "Caller does not have same cert as new installer package "
11051                            + installerPackageName);
11052                }
11053            }
11054
11055            // Verify: if target already has an installer package, it must
11056            // be signed with the same cert as the caller.
11057            if (targetPackageSetting.installerPackageName != null) {
11058                PackageSetting setting = mSettings.mPackages.get(
11059                        targetPackageSetting.installerPackageName);
11060                // If the currently set package isn't valid, then it's always
11061                // okay to change it.
11062                if (setting != null) {
11063                    if (compareSignatures(callerSignature,
11064                            setting.signatures.mSignatures)
11065                            != PackageManager.SIGNATURE_MATCH) {
11066                        throw new SecurityException(
11067                                "Caller does not have same cert as old installer package "
11068                                + targetPackageSetting.installerPackageName);
11069                    }
11070                }
11071            }
11072
11073            // Okay!
11074            targetPackageSetting.installerPackageName = installerPackageName;
11075            scheduleWriteSettingsLocked();
11076        }
11077    }
11078
11079    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11080        // Queue up an async operation since the package installation may take a little while.
11081        mHandler.post(new Runnable() {
11082            public void run() {
11083                mHandler.removeCallbacks(this);
11084                 // Result object to be returned
11085                PackageInstalledInfo res = new PackageInstalledInfo();
11086                res.returnCode = currentStatus;
11087                res.uid = -1;
11088                res.pkg = null;
11089                res.removedInfo = new PackageRemovedInfo();
11090                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11091                    args.doPreInstall(res.returnCode);
11092                    synchronized (mInstallLock) {
11093                        installPackageTracedLI(args, res);
11094                    }
11095                    args.doPostInstall(res.returnCode, res.uid);
11096                }
11097
11098                // A restore should be performed at this point if (a) the install
11099                // succeeded, (b) the operation is not an update, and (c) the new
11100                // package has not opted out of backup participation.
11101                final boolean update = res.removedInfo.removedPackage != null;
11102                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11103                boolean doRestore = !update
11104                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11105
11106                // Set up the post-install work request bookkeeping.  This will be used
11107                // and cleaned up by the post-install event handling regardless of whether
11108                // there's a restore pass performed.  Token values are >= 1.
11109                int token;
11110                if (mNextInstallToken < 0) mNextInstallToken = 1;
11111                token = mNextInstallToken++;
11112
11113                PostInstallData data = new PostInstallData(args, res);
11114                mRunningInstalls.put(token, data);
11115                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11116
11117                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11118                    // Pass responsibility to the Backup Manager.  It will perform a
11119                    // restore if appropriate, then pass responsibility back to the
11120                    // Package Manager to run the post-install observer callbacks
11121                    // and broadcasts.
11122                    IBackupManager bm = IBackupManager.Stub.asInterface(
11123                            ServiceManager.getService(Context.BACKUP_SERVICE));
11124                    if (bm != null) {
11125                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11126                                + " to BM for possible restore");
11127                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11128                        try {
11129                            // TODO: http://b/22388012
11130                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11131                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11132                            } else {
11133                                doRestore = false;
11134                            }
11135                        } catch (RemoteException e) {
11136                            // can't happen; the backup manager is local
11137                        } catch (Exception e) {
11138                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11139                            doRestore = false;
11140                        }
11141                    } else {
11142                        Slog.e(TAG, "Backup Manager not found!");
11143                        doRestore = false;
11144                    }
11145                }
11146
11147                if (!doRestore) {
11148                    // No restore possible, or the Backup Manager was mysteriously not
11149                    // available -- just fire the post-install work request directly.
11150                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11151
11152                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11153
11154                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11155                    mHandler.sendMessage(msg);
11156                }
11157            }
11158        });
11159    }
11160
11161    private abstract class HandlerParams {
11162        private static final int MAX_RETRIES = 4;
11163
11164        /**
11165         * Number of times startCopy() has been attempted and had a non-fatal
11166         * error.
11167         */
11168        private int mRetries = 0;
11169
11170        /** User handle for the user requesting the information or installation. */
11171        private final UserHandle mUser;
11172        String traceMethod;
11173        int traceCookie;
11174
11175        HandlerParams(UserHandle user) {
11176            mUser = user;
11177        }
11178
11179        UserHandle getUser() {
11180            return mUser;
11181        }
11182
11183        HandlerParams setTraceMethod(String traceMethod) {
11184            this.traceMethod = traceMethod;
11185            return this;
11186        }
11187
11188        HandlerParams setTraceCookie(int traceCookie) {
11189            this.traceCookie = traceCookie;
11190            return this;
11191        }
11192
11193        final boolean startCopy() {
11194            boolean res;
11195            try {
11196                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11197
11198                if (++mRetries > MAX_RETRIES) {
11199                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11200                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11201                    handleServiceError();
11202                    return false;
11203                } else {
11204                    handleStartCopy();
11205                    res = true;
11206                }
11207            } catch (RemoteException e) {
11208                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11209                mHandler.sendEmptyMessage(MCS_RECONNECT);
11210                res = false;
11211            }
11212            handleReturnCode();
11213            return res;
11214        }
11215
11216        final void serviceError() {
11217            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11218            handleServiceError();
11219            handleReturnCode();
11220        }
11221
11222        abstract void handleStartCopy() throws RemoteException;
11223        abstract void handleServiceError();
11224        abstract void handleReturnCode();
11225    }
11226
11227    class MeasureParams extends HandlerParams {
11228        private final PackageStats mStats;
11229        private boolean mSuccess;
11230
11231        private final IPackageStatsObserver mObserver;
11232
11233        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11234            super(new UserHandle(stats.userHandle));
11235            mObserver = observer;
11236            mStats = stats;
11237        }
11238
11239        @Override
11240        public String toString() {
11241            return "MeasureParams{"
11242                + Integer.toHexString(System.identityHashCode(this))
11243                + " " + mStats.packageName + "}";
11244        }
11245
11246        @Override
11247        void handleStartCopy() throws RemoteException {
11248            synchronized (mInstallLock) {
11249                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11250            }
11251
11252            if (mSuccess) {
11253                final boolean mounted;
11254                if (Environment.isExternalStorageEmulated()) {
11255                    mounted = true;
11256                } else {
11257                    final String status = Environment.getExternalStorageState();
11258                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11259                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11260                }
11261
11262                if (mounted) {
11263                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11264
11265                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11266                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11267
11268                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11269                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11270
11271                    // Always subtract cache size, since it's a subdirectory
11272                    mStats.externalDataSize -= mStats.externalCacheSize;
11273
11274                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11275                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11276
11277                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11278                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11279                }
11280            }
11281        }
11282
11283        @Override
11284        void handleReturnCode() {
11285            if (mObserver != null) {
11286                try {
11287                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11288                } catch (RemoteException e) {
11289                    Slog.i(TAG, "Observer no longer exists.");
11290                }
11291            }
11292        }
11293
11294        @Override
11295        void handleServiceError() {
11296            Slog.e(TAG, "Could not measure application " + mStats.packageName
11297                            + " external storage");
11298        }
11299    }
11300
11301    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11302            throws RemoteException {
11303        long result = 0;
11304        for (File path : paths) {
11305            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11306        }
11307        return result;
11308    }
11309
11310    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11311        for (File path : paths) {
11312            try {
11313                mcs.clearDirectory(path.getAbsolutePath());
11314            } catch (RemoteException e) {
11315            }
11316        }
11317    }
11318
11319    static class OriginInfo {
11320        /**
11321         * Location where install is coming from, before it has been
11322         * copied/renamed into place. This could be a single monolithic APK
11323         * file, or a cluster directory. This location may be untrusted.
11324         */
11325        final File file;
11326        final String cid;
11327
11328        /**
11329         * Flag indicating that {@link #file} or {@link #cid} has already been
11330         * staged, meaning downstream users don't need to defensively copy the
11331         * contents.
11332         */
11333        final boolean staged;
11334
11335        /**
11336         * Flag indicating that {@link #file} or {@link #cid} is an already
11337         * installed app that is being moved.
11338         */
11339        final boolean existing;
11340
11341        final String resolvedPath;
11342        final File resolvedFile;
11343
11344        static OriginInfo fromNothing() {
11345            return new OriginInfo(null, null, false, false);
11346        }
11347
11348        static OriginInfo fromUntrustedFile(File file) {
11349            return new OriginInfo(file, null, false, false);
11350        }
11351
11352        static OriginInfo fromExistingFile(File file) {
11353            return new OriginInfo(file, null, false, true);
11354        }
11355
11356        static OriginInfo fromStagedFile(File file) {
11357            return new OriginInfo(file, null, true, false);
11358        }
11359
11360        static OriginInfo fromStagedContainer(String cid) {
11361            return new OriginInfo(null, cid, true, false);
11362        }
11363
11364        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11365            this.file = file;
11366            this.cid = cid;
11367            this.staged = staged;
11368            this.existing = existing;
11369
11370            if (cid != null) {
11371                resolvedPath = PackageHelper.getSdDir(cid);
11372                resolvedFile = new File(resolvedPath);
11373            } else if (file != null) {
11374                resolvedPath = file.getAbsolutePath();
11375                resolvedFile = file;
11376            } else {
11377                resolvedPath = null;
11378                resolvedFile = null;
11379            }
11380        }
11381    }
11382
11383    static class MoveInfo {
11384        final int moveId;
11385        final String fromUuid;
11386        final String toUuid;
11387        final String packageName;
11388        final String dataAppName;
11389        final int appId;
11390        final String seinfo;
11391        final int targetSdkVersion;
11392
11393        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11394                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11395            this.moveId = moveId;
11396            this.fromUuid = fromUuid;
11397            this.toUuid = toUuid;
11398            this.packageName = packageName;
11399            this.dataAppName = dataAppName;
11400            this.appId = appId;
11401            this.seinfo = seinfo;
11402            this.targetSdkVersion = targetSdkVersion;
11403        }
11404    }
11405
11406    class InstallParams extends HandlerParams {
11407        final OriginInfo origin;
11408        final MoveInfo move;
11409        final IPackageInstallObserver2 observer;
11410        int installFlags;
11411        final String installerPackageName;
11412        final String volumeUuid;
11413        final VerificationParams verificationParams;
11414        private InstallArgs mArgs;
11415        private int mRet;
11416        final String packageAbiOverride;
11417        final String[] grantedRuntimePermissions;
11418
11419        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11420                int installFlags, String installerPackageName, String volumeUuid,
11421                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11422                String[] grantedPermissions) {
11423            super(user);
11424            this.origin = origin;
11425            this.move = move;
11426            this.observer = observer;
11427            this.installFlags = installFlags;
11428            this.installerPackageName = installerPackageName;
11429            this.volumeUuid = volumeUuid;
11430            this.verificationParams = verificationParams;
11431            this.packageAbiOverride = packageAbiOverride;
11432            this.grantedRuntimePermissions = grantedPermissions;
11433        }
11434
11435        @Override
11436        public String toString() {
11437            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11438                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11439        }
11440
11441        private int installLocationPolicy(PackageInfoLite pkgLite) {
11442            String packageName = pkgLite.packageName;
11443            int installLocation = pkgLite.installLocation;
11444            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11445            // reader
11446            synchronized (mPackages) {
11447                PackageParser.Package pkg = mPackages.get(packageName);
11448                if (pkg != null) {
11449                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11450                        // Check for downgrading.
11451                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11452                            try {
11453                                checkDowngrade(pkg, pkgLite);
11454                            } catch (PackageManagerException e) {
11455                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11456                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11457                            }
11458                        }
11459                        // Check for updated system application.
11460                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11461                            if (onSd) {
11462                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11463                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11464                            }
11465                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11466                        } else {
11467                            if (onSd) {
11468                                // Install flag overrides everything.
11469                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11470                            }
11471                            // If current upgrade specifies particular preference
11472                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11473                                // Application explicitly specified internal.
11474                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11475                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11476                                // App explictly prefers external. Let policy decide
11477                            } else {
11478                                // Prefer previous location
11479                                if (isExternal(pkg)) {
11480                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11481                                }
11482                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11483                            }
11484                        }
11485                    } else {
11486                        // Invalid install. Return error code
11487                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11488                    }
11489                }
11490            }
11491            // All the special cases have been taken care of.
11492            // Return result based on recommended install location.
11493            if (onSd) {
11494                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11495            }
11496            return pkgLite.recommendedInstallLocation;
11497        }
11498
11499        /*
11500         * Invoke remote method to get package information and install
11501         * location values. Override install location based on default
11502         * policy if needed and then create install arguments based
11503         * on the install location.
11504         */
11505        public void handleStartCopy() throws RemoteException {
11506            int ret = PackageManager.INSTALL_SUCCEEDED;
11507
11508            // If we're already staged, we've firmly committed to an install location
11509            if (origin.staged) {
11510                if (origin.file != null) {
11511                    installFlags |= PackageManager.INSTALL_INTERNAL;
11512                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11513                } else if (origin.cid != null) {
11514                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11515                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11516                } else {
11517                    throw new IllegalStateException("Invalid stage location");
11518                }
11519            }
11520
11521            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11522            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11523            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11524            PackageInfoLite pkgLite = null;
11525
11526            if (onInt && onSd) {
11527                // Check if both bits are set.
11528                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11529                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11530            } else if (onSd && ephemeral) {
11531                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11532                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11533            } else {
11534                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11535                        packageAbiOverride);
11536
11537                if (DEBUG_EPHEMERAL && ephemeral) {
11538                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11539                }
11540
11541                /*
11542                 * If we have too little free space, try to free cache
11543                 * before giving up.
11544                 */
11545                if (!origin.staged && pkgLite.recommendedInstallLocation
11546                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11547                    // TODO: focus freeing disk space on the target device
11548                    final StorageManager storage = StorageManager.from(mContext);
11549                    final long lowThreshold = storage.getStorageLowBytes(
11550                            Environment.getDataDirectory());
11551
11552                    final long sizeBytes = mContainerService.calculateInstalledSize(
11553                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11554
11555                    try {
11556                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11557                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11558                                installFlags, packageAbiOverride);
11559                    } catch (InstallerException e) {
11560                        Slog.w(TAG, "Failed to free cache", e);
11561                    }
11562
11563                    /*
11564                     * The cache free must have deleted the file we
11565                     * downloaded to install.
11566                     *
11567                     * TODO: fix the "freeCache" call to not delete
11568                     *       the file we care about.
11569                     */
11570                    if (pkgLite.recommendedInstallLocation
11571                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11572                        pkgLite.recommendedInstallLocation
11573                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11574                    }
11575                }
11576            }
11577
11578            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11579                int loc = pkgLite.recommendedInstallLocation;
11580                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11581                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11582                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11583                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11584                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11585                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11586                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11587                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11588                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11589                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11590                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11591                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11592                } else {
11593                    // Override with defaults if needed.
11594                    loc = installLocationPolicy(pkgLite);
11595                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11596                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11597                    } else if (!onSd && !onInt) {
11598                        // Override install location with flags
11599                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11600                            // Set the flag to install on external media.
11601                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11602                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11603                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11604                            if (DEBUG_EPHEMERAL) {
11605                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11606                            }
11607                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11608                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11609                                    |PackageManager.INSTALL_INTERNAL);
11610                        } else {
11611                            // Make sure the flag for installing on external
11612                            // media is unset
11613                            installFlags |= PackageManager.INSTALL_INTERNAL;
11614                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11615                        }
11616                    }
11617                }
11618            }
11619
11620            final InstallArgs args = createInstallArgs(this);
11621            mArgs = args;
11622
11623            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11624                // TODO: http://b/22976637
11625                // Apps installed for "all" users use the device owner to verify the app
11626                UserHandle verifierUser = getUser();
11627                if (verifierUser == UserHandle.ALL) {
11628                    verifierUser = UserHandle.SYSTEM;
11629                }
11630
11631                /*
11632                 * Determine if we have any installed package verifiers. If we
11633                 * do, then we'll defer to them to verify the packages.
11634                 */
11635                final int requiredUid = mRequiredVerifierPackage == null ? -1
11636                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11637                                verifierUser.getIdentifier());
11638                if (!origin.existing && requiredUid != -1
11639                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11640                    final Intent verification = new Intent(
11641                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11642                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11643                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11644                            PACKAGE_MIME_TYPE);
11645                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11646
11647                    // Query all live verifiers based on current user state
11648                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11649                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11650
11651                    if (DEBUG_VERIFY) {
11652                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11653                                + verification.toString() + " with " + pkgLite.verifiers.length
11654                                + " optional verifiers");
11655                    }
11656
11657                    final int verificationId = mPendingVerificationToken++;
11658
11659                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11660
11661                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11662                            installerPackageName);
11663
11664                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11665                            installFlags);
11666
11667                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11668                            pkgLite.packageName);
11669
11670                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11671                            pkgLite.versionCode);
11672
11673                    if (verificationParams != null) {
11674                        if (verificationParams.getVerificationURI() != null) {
11675                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11676                                 verificationParams.getVerificationURI());
11677                        }
11678                        if (verificationParams.getOriginatingURI() != null) {
11679                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11680                                  verificationParams.getOriginatingURI());
11681                        }
11682                        if (verificationParams.getReferrer() != null) {
11683                            verification.putExtra(Intent.EXTRA_REFERRER,
11684                                  verificationParams.getReferrer());
11685                        }
11686                        if (verificationParams.getOriginatingUid() >= 0) {
11687                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11688                                  verificationParams.getOriginatingUid());
11689                        }
11690                        if (verificationParams.getInstallerUid() >= 0) {
11691                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11692                                  verificationParams.getInstallerUid());
11693                        }
11694                    }
11695
11696                    final PackageVerificationState verificationState = new PackageVerificationState(
11697                            requiredUid, args);
11698
11699                    mPendingVerification.append(verificationId, verificationState);
11700
11701                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11702                            receivers, verificationState);
11703
11704                    /*
11705                     * If any sufficient verifiers were listed in the package
11706                     * manifest, attempt to ask them.
11707                     */
11708                    if (sufficientVerifiers != null) {
11709                        final int N = sufficientVerifiers.size();
11710                        if (N == 0) {
11711                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11712                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11713                        } else {
11714                            for (int i = 0; i < N; i++) {
11715                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11716
11717                                final Intent sufficientIntent = new Intent(verification);
11718                                sufficientIntent.setComponent(verifierComponent);
11719                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11720                            }
11721                        }
11722                    }
11723
11724                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11725                            mRequiredVerifierPackage, receivers);
11726                    if (ret == PackageManager.INSTALL_SUCCEEDED
11727                            && mRequiredVerifierPackage != null) {
11728                        Trace.asyncTraceBegin(
11729                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11730                        /*
11731                         * Send the intent to the required verification agent,
11732                         * but only start the verification timeout after the
11733                         * target BroadcastReceivers have run.
11734                         */
11735                        verification.setComponent(requiredVerifierComponent);
11736                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11737                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11738                                new BroadcastReceiver() {
11739                                    @Override
11740                                    public void onReceive(Context context, Intent intent) {
11741                                        final Message msg = mHandler
11742                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11743                                        msg.arg1 = verificationId;
11744                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11745                                    }
11746                                }, null, 0, null, null);
11747
11748                        /*
11749                         * We don't want the copy to proceed until verification
11750                         * succeeds, so null out this field.
11751                         */
11752                        mArgs = null;
11753                    }
11754                } else {
11755                    /*
11756                     * No package verification is enabled, so immediately start
11757                     * the remote call to initiate copy using temporary file.
11758                     */
11759                    ret = args.copyApk(mContainerService, true);
11760                }
11761            }
11762
11763            mRet = ret;
11764        }
11765
11766        @Override
11767        void handleReturnCode() {
11768            // If mArgs is null, then MCS couldn't be reached. When it
11769            // reconnects, it will try again to install. At that point, this
11770            // will succeed.
11771            if (mArgs != null) {
11772                processPendingInstall(mArgs, mRet);
11773            }
11774        }
11775
11776        @Override
11777        void handleServiceError() {
11778            mArgs = createInstallArgs(this);
11779            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11780        }
11781
11782        public boolean isForwardLocked() {
11783            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11784        }
11785    }
11786
11787    /**
11788     * Used during creation of InstallArgs
11789     *
11790     * @param installFlags package installation flags
11791     * @return true if should be installed on external storage
11792     */
11793    private static boolean installOnExternalAsec(int installFlags) {
11794        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11795            return false;
11796        }
11797        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11798            return true;
11799        }
11800        return false;
11801    }
11802
11803    /**
11804     * Used during creation of InstallArgs
11805     *
11806     * @param installFlags package installation flags
11807     * @return true if should be installed as forward locked
11808     */
11809    private static boolean installForwardLocked(int installFlags) {
11810        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11811    }
11812
11813    private InstallArgs createInstallArgs(InstallParams params) {
11814        if (params.move != null) {
11815            return new MoveInstallArgs(params);
11816        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11817            return new AsecInstallArgs(params);
11818        } else {
11819            return new FileInstallArgs(params);
11820        }
11821    }
11822
11823    /**
11824     * Create args that describe an existing installed package. Typically used
11825     * when cleaning up old installs, or used as a move source.
11826     */
11827    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11828            String resourcePath, String[] instructionSets) {
11829        final boolean isInAsec;
11830        if (installOnExternalAsec(installFlags)) {
11831            /* Apps on SD card are always in ASEC containers. */
11832            isInAsec = true;
11833        } else if (installForwardLocked(installFlags)
11834                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11835            /*
11836             * Forward-locked apps are only in ASEC containers if they're the
11837             * new style
11838             */
11839            isInAsec = true;
11840        } else {
11841            isInAsec = false;
11842        }
11843
11844        if (isInAsec) {
11845            return new AsecInstallArgs(codePath, instructionSets,
11846                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11847        } else {
11848            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11849        }
11850    }
11851
11852    static abstract class InstallArgs {
11853        /** @see InstallParams#origin */
11854        final OriginInfo origin;
11855        /** @see InstallParams#move */
11856        final MoveInfo move;
11857
11858        final IPackageInstallObserver2 observer;
11859        // Always refers to PackageManager flags only
11860        final int installFlags;
11861        final String installerPackageName;
11862        final String volumeUuid;
11863        final UserHandle user;
11864        final String abiOverride;
11865        final String[] installGrantPermissions;
11866        /** If non-null, drop an async trace when the install completes */
11867        final String traceMethod;
11868        final int traceCookie;
11869
11870        // The list of instruction sets supported by this app. This is currently
11871        // only used during the rmdex() phase to clean up resources. We can get rid of this
11872        // if we move dex files under the common app path.
11873        /* nullable */ String[] instructionSets;
11874
11875        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11876                int installFlags, String installerPackageName, String volumeUuid,
11877                UserHandle user, String[] instructionSets,
11878                String abiOverride, String[] installGrantPermissions,
11879                String traceMethod, int traceCookie) {
11880            this.origin = origin;
11881            this.move = move;
11882            this.installFlags = installFlags;
11883            this.observer = observer;
11884            this.installerPackageName = installerPackageName;
11885            this.volumeUuid = volumeUuid;
11886            this.user = user;
11887            this.instructionSets = instructionSets;
11888            this.abiOverride = abiOverride;
11889            this.installGrantPermissions = installGrantPermissions;
11890            this.traceMethod = traceMethod;
11891            this.traceCookie = traceCookie;
11892        }
11893
11894        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11895        abstract int doPreInstall(int status);
11896
11897        /**
11898         * Rename package into final resting place. All paths on the given
11899         * scanned package should be updated to reflect the rename.
11900         */
11901        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11902        abstract int doPostInstall(int status, int uid);
11903
11904        /** @see PackageSettingBase#codePathString */
11905        abstract String getCodePath();
11906        /** @see PackageSettingBase#resourcePathString */
11907        abstract String getResourcePath();
11908
11909        // Need installer lock especially for dex file removal.
11910        abstract void cleanUpResourcesLI();
11911        abstract boolean doPostDeleteLI(boolean delete);
11912
11913        /**
11914         * Called before the source arguments are copied. This is used mostly
11915         * for MoveParams when it needs to read the source file to put it in the
11916         * destination.
11917         */
11918        int doPreCopy() {
11919            return PackageManager.INSTALL_SUCCEEDED;
11920        }
11921
11922        /**
11923         * Called after the source arguments are copied. This is used mostly for
11924         * MoveParams when it needs to read the source file to put it in the
11925         * destination.
11926         *
11927         * @return
11928         */
11929        int doPostCopy(int uid) {
11930            return PackageManager.INSTALL_SUCCEEDED;
11931        }
11932
11933        protected boolean isFwdLocked() {
11934            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11935        }
11936
11937        protected boolean isExternalAsec() {
11938            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11939        }
11940
11941        protected boolean isEphemeral() {
11942            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11943        }
11944
11945        UserHandle getUser() {
11946            return user;
11947        }
11948    }
11949
11950    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11951        if (!allCodePaths.isEmpty()) {
11952            if (instructionSets == null) {
11953                throw new IllegalStateException("instructionSet == null");
11954            }
11955            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11956            for (String codePath : allCodePaths) {
11957                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11958                    try {
11959                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11960                    } catch (InstallerException ignored) {
11961                    }
11962                }
11963            }
11964        }
11965    }
11966
11967    /**
11968     * Logic to handle installation of non-ASEC applications, including copying
11969     * and renaming logic.
11970     */
11971    class FileInstallArgs extends InstallArgs {
11972        private File codeFile;
11973        private File resourceFile;
11974
11975        // Example topology:
11976        // /data/app/com.example/base.apk
11977        // /data/app/com.example/split_foo.apk
11978        // /data/app/com.example/lib/arm/libfoo.so
11979        // /data/app/com.example/lib/arm64/libfoo.so
11980        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11981
11982        /** New install */
11983        FileInstallArgs(InstallParams params) {
11984            super(params.origin, params.move, params.observer, params.installFlags,
11985                    params.installerPackageName, params.volumeUuid,
11986                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11987                    params.grantedRuntimePermissions,
11988                    params.traceMethod, params.traceCookie);
11989            if (isFwdLocked()) {
11990                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11991            }
11992        }
11993
11994        /** Existing install */
11995        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11996            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11997                    null, null, null, 0);
11998            this.codeFile = (codePath != null) ? new File(codePath) : null;
11999            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12000        }
12001
12002        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12003            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12004            try {
12005                return doCopyApk(imcs, temp);
12006            } finally {
12007                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12008            }
12009        }
12010
12011        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12012            if (origin.staged) {
12013                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12014                codeFile = origin.file;
12015                resourceFile = origin.file;
12016                return PackageManager.INSTALL_SUCCEEDED;
12017            }
12018
12019            try {
12020                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12021                final File tempDir =
12022                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12023                codeFile = tempDir;
12024                resourceFile = tempDir;
12025            } catch (IOException e) {
12026                Slog.w(TAG, "Failed to create copy file: " + e);
12027                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12028            }
12029
12030            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12031                @Override
12032                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12033                    if (!FileUtils.isValidExtFilename(name)) {
12034                        throw new IllegalArgumentException("Invalid filename: " + name);
12035                    }
12036                    try {
12037                        final File file = new File(codeFile, name);
12038                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12039                                O_RDWR | O_CREAT, 0644);
12040                        Os.chmod(file.getAbsolutePath(), 0644);
12041                        return new ParcelFileDescriptor(fd);
12042                    } catch (ErrnoException e) {
12043                        throw new RemoteException("Failed to open: " + e.getMessage());
12044                    }
12045                }
12046            };
12047
12048            int ret = PackageManager.INSTALL_SUCCEEDED;
12049            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12050            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12051                Slog.e(TAG, "Failed to copy package");
12052                return ret;
12053            }
12054
12055            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12056            NativeLibraryHelper.Handle handle = null;
12057            try {
12058                handle = NativeLibraryHelper.Handle.create(codeFile);
12059                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12060                        abiOverride);
12061            } catch (IOException e) {
12062                Slog.e(TAG, "Copying native libraries failed", e);
12063                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12064            } finally {
12065                IoUtils.closeQuietly(handle);
12066            }
12067
12068            return ret;
12069        }
12070
12071        int doPreInstall(int status) {
12072            if (status != PackageManager.INSTALL_SUCCEEDED) {
12073                cleanUp();
12074            }
12075            return status;
12076        }
12077
12078        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12079            if (status != PackageManager.INSTALL_SUCCEEDED) {
12080                cleanUp();
12081                return false;
12082            }
12083
12084            final File targetDir = codeFile.getParentFile();
12085            final File beforeCodeFile = codeFile;
12086            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12087
12088            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12089            try {
12090                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12091            } catch (ErrnoException e) {
12092                Slog.w(TAG, "Failed to rename", e);
12093                return false;
12094            }
12095
12096            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12097                Slog.w(TAG, "Failed to restorecon");
12098                return false;
12099            }
12100
12101            // Reflect the rename internally
12102            codeFile = afterCodeFile;
12103            resourceFile = afterCodeFile;
12104
12105            // Reflect the rename in scanned details
12106            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12107            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12108                    afterCodeFile, pkg.baseCodePath));
12109            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12110                    afterCodeFile, pkg.splitCodePaths));
12111
12112            // Reflect the rename in app info
12113            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12114            pkg.setApplicationInfoCodePath(pkg.codePath);
12115            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12116            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12117            pkg.setApplicationInfoResourcePath(pkg.codePath);
12118            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12119            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12120
12121            return true;
12122        }
12123
12124        int doPostInstall(int status, int uid) {
12125            if (status != PackageManager.INSTALL_SUCCEEDED) {
12126                cleanUp();
12127            }
12128            return status;
12129        }
12130
12131        @Override
12132        String getCodePath() {
12133            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12134        }
12135
12136        @Override
12137        String getResourcePath() {
12138            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12139        }
12140
12141        private boolean cleanUp() {
12142            if (codeFile == null || !codeFile.exists()) {
12143                return false;
12144            }
12145
12146            removeCodePathLI(codeFile);
12147
12148            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12149                resourceFile.delete();
12150            }
12151
12152            return true;
12153        }
12154
12155        void cleanUpResourcesLI() {
12156            // Try enumerating all code paths before deleting
12157            List<String> allCodePaths = Collections.EMPTY_LIST;
12158            if (codeFile != null && codeFile.exists()) {
12159                try {
12160                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12161                    allCodePaths = pkg.getAllCodePaths();
12162                } catch (PackageParserException e) {
12163                    // Ignored; we tried our best
12164                }
12165            }
12166
12167            cleanUp();
12168            removeDexFiles(allCodePaths, instructionSets);
12169        }
12170
12171        boolean doPostDeleteLI(boolean delete) {
12172            // XXX err, shouldn't we respect the delete flag?
12173            cleanUpResourcesLI();
12174            return true;
12175        }
12176    }
12177
12178    private boolean isAsecExternal(String cid) {
12179        final String asecPath = PackageHelper.getSdFilesystem(cid);
12180        return !asecPath.startsWith(mAsecInternalPath);
12181    }
12182
12183    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12184            PackageManagerException {
12185        if (copyRet < 0) {
12186            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12187                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12188                throw new PackageManagerException(copyRet, message);
12189            }
12190        }
12191    }
12192
12193    /**
12194     * Extract the MountService "container ID" from the full code path of an
12195     * .apk.
12196     */
12197    static String cidFromCodePath(String fullCodePath) {
12198        int eidx = fullCodePath.lastIndexOf("/");
12199        String subStr1 = fullCodePath.substring(0, eidx);
12200        int sidx = subStr1.lastIndexOf("/");
12201        return subStr1.substring(sidx+1, eidx);
12202    }
12203
12204    /**
12205     * Logic to handle installation of ASEC applications, including copying and
12206     * renaming logic.
12207     */
12208    class AsecInstallArgs extends InstallArgs {
12209        static final String RES_FILE_NAME = "pkg.apk";
12210        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12211
12212        String cid;
12213        String packagePath;
12214        String resourcePath;
12215
12216        /** New install */
12217        AsecInstallArgs(InstallParams params) {
12218            super(params.origin, params.move, params.observer, params.installFlags,
12219                    params.installerPackageName, params.volumeUuid,
12220                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12221                    params.grantedRuntimePermissions,
12222                    params.traceMethod, params.traceCookie);
12223        }
12224
12225        /** Existing install */
12226        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12227                        boolean isExternal, boolean isForwardLocked) {
12228            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12229                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12230                    instructionSets, null, null, null, 0);
12231            // Hackily pretend we're still looking at a full code path
12232            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12233                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12234            }
12235
12236            // Extract cid from fullCodePath
12237            int eidx = fullCodePath.lastIndexOf("/");
12238            String subStr1 = fullCodePath.substring(0, eidx);
12239            int sidx = subStr1.lastIndexOf("/");
12240            cid = subStr1.substring(sidx+1, eidx);
12241            setMountPath(subStr1);
12242        }
12243
12244        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12245            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12246                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12247                    instructionSets, null, null, null, 0);
12248            this.cid = cid;
12249            setMountPath(PackageHelper.getSdDir(cid));
12250        }
12251
12252        void createCopyFile() {
12253            cid = mInstallerService.allocateExternalStageCidLegacy();
12254        }
12255
12256        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12257            if (origin.staged && origin.cid != null) {
12258                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12259                cid = origin.cid;
12260                setMountPath(PackageHelper.getSdDir(cid));
12261                return PackageManager.INSTALL_SUCCEEDED;
12262            }
12263
12264            if (temp) {
12265                createCopyFile();
12266            } else {
12267                /*
12268                 * Pre-emptively destroy the container since it's destroyed if
12269                 * copying fails due to it existing anyway.
12270                 */
12271                PackageHelper.destroySdDir(cid);
12272            }
12273
12274            final String newMountPath = imcs.copyPackageToContainer(
12275                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12276                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12277
12278            if (newMountPath != null) {
12279                setMountPath(newMountPath);
12280                return PackageManager.INSTALL_SUCCEEDED;
12281            } else {
12282                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12283            }
12284        }
12285
12286        @Override
12287        String getCodePath() {
12288            return packagePath;
12289        }
12290
12291        @Override
12292        String getResourcePath() {
12293            return resourcePath;
12294        }
12295
12296        int doPreInstall(int status) {
12297            if (status != PackageManager.INSTALL_SUCCEEDED) {
12298                // Destroy container
12299                PackageHelper.destroySdDir(cid);
12300            } else {
12301                boolean mounted = PackageHelper.isContainerMounted(cid);
12302                if (!mounted) {
12303                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12304                            Process.SYSTEM_UID);
12305                    if (newMountPath != null) {
12306                        setMountPath(newMountPath);
12307                    } else {
12308                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12309                    }
12310                }
12311            }
12312            return status;
12313        }
12314
12315        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12316            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12317            String newMountPath = null;
12318            if (PackageHelper.isContainerMounted(cid)) {
12319                // Unmount the container
12320                if (!PackageHelper.unMountSdDir(cid)) {
12321                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12322                    return false;
12323                }
12324            }
12325            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12326                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12327                        " which might be stale. Will try to clean up.");
12328                // Clean up the stale container and proceed to recreate.
12329                if (!PackageHelper.destroySdDir(newCacheId)) {
12330                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12331                    return false;
12332                }
12333                // Successfully cleaned up stale container. Try to rename again.
12334                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12335                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12336                            + " inspite of cleaning it up.");
12337                    return false;
12338                }
12339            }
12340            if (!PackageHelper.isContainerMounted(newCacheId)) {
12341                Slog.w(TAG, "Mounting container " + newCacheId);
12342                newMountPath = PackageHelper.mountSdDir(newCacheId,
12343                        getEncryptKey(), Process.SYSTEM_UID);
12344            } else {
12345                newMountPath = PackageHelper.getSdDir(newCacheId);
12346            }
12347            if (newMountPath == null) {
12348                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12349                return false;
12350            }
12351            Log.i(TAG, "Succesfully renamed " + cid +
12352                    " to " + newCacheId +
12353                    " at new path: " + newMountPath);
12354            cid = newCacheId;
12355
12356            final File beforeCodeFile = new File(packagePath);
12357            setMountPath(newMountPath);
12358            final File afterCodeFile = new File(packagePath);
12359
12360            // Reflect the rename in scanned details
12361            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12362            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12363                    afterCodeFile, pkg.baseCodePath));
12364            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12365                    afterCodeFile, pkg.splitCodePaths));
12366
12367            // Reflect the rename in app info
12368            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12369            pkg.setApplicationInfoCodePath(pkg.codePath);
12370            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12371            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12372            pkg.setApplicationInfoResourcePath(pkg.codePath);
12373            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12374            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12375
12376            return true;
12377        }
12378
12379        private void setMountPath(String mountPath) {
12380            final File mountFile = new File(mountPath);
12381
12382            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12383            if (monolithicFile.exists()) {
12384                packagePath = monolithicFile.getAbsolutePath();
12385                if (isFwdLocked()) {
12386                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12387                } else {
12388                    resourcePath = packagePath;
12389                }
12390            } else {
12391                packagePath = mountFile.getAbsolutePath();
12392                resourcePath = packagePath;
12393            }
12394        }
12395
12396        int doPostInstall(int status, int uid) {
12397            if (status != PackageManager.INSTALL_SUCCEEDED) {
12398                cleanUp();
12399            } else {
12400                final int groupOwner;
12401                final String protectedFile;
12402                if (isFwdLocked()) {
12403                    groupOwner = UserHandle.getSharedAppGid(uid);
12404                    protectedFile = RES_FILE_NAME;
12405                } else {
12406                    groupOwner = -1;
12407                    protectedFile = null;
12408                }
12409
12410                if (uid < Process.FIRST_APPLICATION_UID
12411                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12412                    Slog.e(TAG, "Failed to finalize " + cid);
12413                    PackageHelper.destroySdDir(cid);
12414                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12415                }
12416
12417                boolean mounted = PackageHelper.isContainerMounted(cid);
12418                if (!mounted) {
12419                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12420                }
12421            }
12422            return status;
12423        }
12424
12425        private void cleanUp() {
12426            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12427
12428            // Destroy secure container
12429            PackageHelper.destroySdDir(cid);
12430        }
12431
12432        private List<String> getAllCodePaths() {
12433            final File codeFile = new File(getCodePath());
12434            if (codeFile != null && codeFile.exists()) {
12435                try {
12436                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12437                    return pkg.getAllCodePaths();
12438                } catch (PackageParserException e) {
12439                    // Ignored; we tried our best
12440                }
12441            }
12442            return Collections.EMPTY_LIST;
12443        }
12444
12445        void cleanUpResourcesLI() {
12446            // Enumerate all code paths before deleting
12447            cleanUpResourcesLI(getAllCodePaths());
12448        }
12449
12450        private void cleanUpResourcesLI(List<String> allCodePaths) {
12451            cleanUp();
12452            removeDexFiles(allCodePaths, instructionSets);
12453        }
12454
12455        String getPackageName() {
12456            return getAsecPackageName(cid);
12457        }
12458
12459        boolean doPostDeleteLI(boolean delete) {
12460            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12461            final List<String> allCodePaths = getAllCodePaths();
12462            boolean mounted = PackageHelper.isContainerMounted(cid);
12463            if (mounted) {
12464                // Unmount first
12465                if (PackageHelper.unMountSdDir(cid)) {
12466                    mounted = false;
12467                }
12468            }
12469            if (!mounted && delete) {
12470                cleanUpResourcesLI(allCodePaths);
12471            }
12472            return !mounted;
12473        }
12474
12475        @Override
12476        int doPreCopy() {
12477            if (isFwdLocked()) {
12478                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12479                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12480                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12481                }
12482            }
12483
12484            return PackageManager.INSTALL_SUCCEEDED;
12485        }
12486
12487        @Override
12488        int doPostCopy(int uid) {
12489            if (isFwdLocked()) {
12490                if (uid < Process.FIRST_APPLICATION_UID
12491                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12492                                RES_FILE_NAME)) {
12493                    Slog.e(TAG, "Failed to finalize " + cid);
12494                    PackageHelper.destroySdDir(cid);
12495                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12496                }
12497            }
12498
12499            return PackageManager.INSTALL_SUCCEEDED;
12500        }
12501    }
12502
12503    /**
12504     * Logic to handle movement of existing installed applications.
12505     */
12506    class MoveInstallArgs extends InstallArgs {
12507        private File codeFile;
12508        private File resourceFile;
12509
12510        /** New install */
12511        MoveInstallArgs(InstallParams params) {
12512            super(params.origin, params.move, params.observer, params.installFlags,
12513                    params.installerPackageName, params.volumeUuid,
12514                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12515                    params.grantedRuntimePermissions,
12516                    params.traceMethod, params.traceCookie);
12517        }
12518
12519        int copyApk(IMediaContainerService imcs, boolean temp) {
12520            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12521                    + move.fromUuid + " to " + move.toUuid);
12522            synchronized (mInstaller) {
12523                try {
12524                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12525                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12526                } catch (InstallerException e) {
12527                    Slog.w(TAG, "Failed to move app", e);
12528                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12529                }
12530            }
12531
12532            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12533            resourceFile = codeFile;
12534            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12535
12536            return PackageManager.INSTALL_SUCCEEDED;
12537        }
12538
12539        int doPreInstall(int status) {
12540            if (status != PackageManager.INSTALL_SUCCEEDED) {
12541                cleanUp(move.toUuid);
12542            }
12543            return status;
12544        }
12545
12546        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12547            if (status != PackageManager.INSTALL_SUCCEEDED) {
12548                cleanUp(move.toUuid);
12549                return false;
12550            }
12551
12552            // Reflect the move in app info
12553            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12554            pkg.setApplicationInfoCodePath(pkg.codePath);
12555            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12556            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12557            pkg.setApplicationInfoResourcePath(pkg.codePath);
12558            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12559            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12560
12561            return true;
12562        }
12563
12564        int doPostInstall(int status, int uid) {
12565            if (status == PackageManager.INSTALL_SUCCEEDED) {
12566                cleanUp(move.fromUuid);
12567            } else {
12568                cleanUp(move.toUuid);
12569            }
12570            return status;
12571        }
12572
12573        @Override
12574        String getCodePath() {
12575            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12576        }
12577
12578        @Override
12579        String getResourcePath() {
12580            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12581        }
12582
12583        private boolean cleanUp(String volumeUuid) {
12584            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12585                    move.dataAppName);
12586            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12587            synchronized (mInstallLock) {
12588                // Clean up both app data and code
12589                removeDataDirsLI(volumeUuid, move.packageName);
12590                removeCodePathLI(codeFile);
12591            }
12592            return true;
12593        }
12594
12595        void cleanUpResourcesLI() {
12596            throw new UnsupportedOperationException();
12597        }
12598
12599        boolean doPostDeleteLI(boolean delete) {
12600            throw new UnsupportedOperationException();
12601        }
12602    }
12603
12604    static String getAsecPackageName(String packageCid) {
12605        int idx = packageCid.lastIndexOf("-");
12606        if (idx == -1) {
12607            return packageCid;
12608        }
12609        return packageCid.substring(0, idx);
12610    }
12611
12612    // Utility method used to create code paths based on package name and available index.
12613    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12614        String idxStr = "";
12615        int idx = 1;
12616        // Fall back to default value of idx=1 if prefix is not
12617        // part of oldCodePath
12618        if (oldCodePath != null) {
12619            String subStr = oldCodePath;
12620            // Drop the suffix right away
12621            if (suffix != null && subStr.endsWith(suffix)) {
12622                subStr = subStr.substring(0, subStr.length() - suffix.length());
12623            }
12624            // If oldCodePath already contains prefix find out the
12625            // ending index to either increment or decrement.
12626            int sidx = subStr.lastIndexOf(prefix);
12627            if (sidx != -1) {
12628                subStr = subStr.substring(sidx + prefix.length());
12629                if (subStr != null) {
12630                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12631                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12632                    }
12633                    try {
12634                        idx = Integer.parseInt(subStr);
12635                        if (idx <= 1) {
12636                            idx++;
12637                        } else {
12638                            idx--;
12639                        }
12640                    } catch(NumberFormatException e) {
12641                    }
12642                }
12643            }
12644        }
12645        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12646        return prefix + idxStr;
12647    }
12648
12649    private File getNextCodePath(File targetDir, String packageName) {
12650        int suffix = 1;
12651        File result;
12652        do {
12653            result = new File(targetDir, packageName + "-" + suffix);
12654            suffix++;
12655        } while (result.exists());
12656        return result;
12657    }
12658
12659    // Utility method that returns the relative package path with respect
12660    // to the installation directory. Like say for /data/data/com.test-1.apk
12661    // string com.test-1 is returned.
12662    static String deriveCodePathName(String codePath) {
12663        if (codePath == null) {
12664            return null;
12665        }
12666        final File codeFile = new File(codePath);
12667        final String name = codeFile.getName();
12668        if (codeFile.isDirectory()) {
12669            return name;
12670        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12671            final int lastDot = name.lastIndexOf('.');
12672            return name.substring(0, lastDot);
12673        } else {
12674            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12675            return null;
12676        }
12677    }
12678
12679    static class PackageInstalledInfo {
12680        String name;
12681        int uid;
12682        // The set of users that originally had this package installed.
12683        int[] origUsers;
12684        // The set of users that now have this package installed.
12685        int[] newUsers;
12686        PackageParser.Package pkg;
12687        int returnCode;
12688        String returnMsg;
12689        PackageRemovedInfo removedInfo;
12690
12691        public void setError(int code, String msg) {
12692            returnCode = code;
12693            returnMsg = msg;
12694            Slog.w(TAG, msg);
12695        }
12696
12697        public void setError(String msg, PackageParserException e) {
12698            returnCode = e.error;
12699            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12700            Slog.w(TAG, msg, e);
12701        }
12702
12703        public void setError(String msg, PackageManagerException e) {
12704            returnCode = e.error;
12705            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12706            Slog.w(TAG, msg, e);
12707        }
12708
12709        // In some error cases we want to convey more info back to the observer
12710        String origPackage;
12711        String origPermission;
12712    }
12713
12714    /*
12715     * Install a non-existing package.
12716     */
12717    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12718            UserHandle user, String installerPackageName, String volumeUuid,
12719            PackageInstalledInfo res) {
12720        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12721
12722        // Remember this for later, in case we need to rollback this install
12723        String pkgName = pkg.packageName;
12724
12725        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12726        // TODO: b/23350563
12727        final boolean dataDirExists = Environment
12728                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12729
12730        synchronized(mPackages) {
12731            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12732                // A package with the same name is already installed, though
12733                // it has been renamed to an older name.  The package we
12734                // are trying to install should be installed as an update to
12735                // the existing one, but that has not been requested, so bail.
12736                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12737                        + " without first uninstalling package running as "
12738                        + mSettings.mRenamedPackages.get(pkgName));
12739                return;
12740            }
12741            if (mPackages.containsKey(pkgName)) {
12742                // Don't allow installation over an existing package with the same name.
12743                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12744                        + " without first uninstalling.");
12745                return;
12746            }
12747        }
12748
12749        try {
12750            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12751                    System.currentTimeMillis(), user);
12752
12753            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
12754            prepareAppDataAfterInstall(newPackage);
12755
12756            // delete the partially installed application. the data directory will have to be
12757            // restored if it was already existing
12758            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12759                // remove package from internal structures.  Note that we want deletePackageX to
12760                // delete the package data and cache directories that it created in
12761                // scanPackageLocked, unless those directories existed before we even tried to
12762                // install.
12763                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12764                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12765                                res.removedInfo, true, null);
12766            }
12767
12768        } catch (PackageManagerException e) {
12769            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12770        }
12771
12772        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12773    }
12774
12775    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12776        // Can't rotate keys during boot or if sharedUser.
12777        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12778                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12779            return false;
12780        }
12781        // app is using upgradeKeySets; make sure all are valid
12782        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12783        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12784        for (int i = 0; i < upgradeKeySets.length; i++) {
12785            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12786                Slog.wtf(TAG, "Package "
12787                         + (oldPs.name != null ? oldPs.name : "<null>")
12788                         + " contains upgrade-key-set reference to unknown key-set: "
12789                         + upgradeKeySets[i]
12790                         + " reverting to signatures check.");
12791                return false;
12792            }
12793        }
12794        return true;
12795    }
12796
12797    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12798        // Upgrade keysets are being used.  Determine if new package has a superset of the
12799        // required keys.
12800        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12801        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12802        for (int i = 0; i < upgradeKeySets.length; i++) {
12803            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12804            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12805                return true;
12806            }
12807        }
12808        return false;
12809    }
12810
12811    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12812            UserHandle user, String installerPackageName, String volumeUuid,
12813            PackageInstalledInfo res) {
12814        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12815
12816        final PackageParser.Package oldPackage;
12817        final String pkgName = pkg.packageName;
12818        final int[] allUsers;
12819        final boolean[] perUserInstalled;
12820
12821        // First find the old package info and check signatures
12822        synchronized(mPackages) {
12823            oldPackage = mPackages.get(pkgName);
12824            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12825            if (isEphemeral && !oldIsEphemeral) {
12826                // can't downgrade from full to ephemeral
12827                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12828                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12829                return;
12830            }
12831            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12832            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12833            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12834                if (!checkUpgradeKeySetLP(ps, pkg)) {
12835                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12836                            "New package not signed by keys specified by upgrade-keysets: "
12837                                    + pkgName);
12838                    return;
12839                }
12840            } else {
12841                // default to original signature matching
12842                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12843                        != PackageManager.SIGNATURE_MATCH) {
12844                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12845                            "New package has a different signature: " + pkgName);
12846                    return;
12847                }
12848            }
12849
12850            // In case of rollback, remember per-user/profile install state
12851            allUsers = sUserManager.getUserIds();
12852            perUserInstalled = new boolean[allUsers.length];
12853            for (int i = 0; i < allUsers.length; i++) {
12854                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12855            }
12856        }
12857
12858        boolean sysPkg = (isSystemApp(oldPackage));
12859        if (sysPkg) {
12860            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12861                    user, allUsers, perUserInstalled, installerPackageName, res);
12862        } else {
12863            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12864                    user, allUsers, perUserInstalled, installerPackageName, res);
12865        }
12866    }
12867
12868    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12869            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12870            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12871            PackageInstalledInfo res) {
12872        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12873                + deletedPackage);
12874
12875        String pkgName = deletedPackage.packageName;
12876        boolean deletedPkg = true;
12877        boolean addedPkg = false;
12878
12879        final long origUpdateTime = (pkg.mExtras != null)
12880                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
12881
12882        // First delete the existing package while retaining the data directory
12883        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12884                res.removedInfo, true, pkg)) {
12885            // If the existing package wasn't successfully deleted
12886            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12887            deletedPkg = false;
12888        } else {
12889            // Successfully deleted the old package; proceed with replace.
12890
12891            // If deleted package lived in a container, give users a chance to
12892            // relinquish resources before killing.
12893            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12894                if (DEBUG_INSTALL) {
12895                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12896                }
12897                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12898                final ArrayList<String> pkgList = new ArrayList<String>(1);
12899                pkgList.add(deletedPackage.applicationInfo.packageName);
12900                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12901            }
12902
12903            deleteCodeCacheDirsLI(pkg);
12904
12905            try {
12906                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12907                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12908                updateSettingsLI(newPackage, installerPackageName, allUsers,
12909                        perUserInstalled, res, user);
12910                prepareAppDataAfterInstall(newPackage);
12911                addedPkg = true;
12912            } catch (PackageManagerException e) {
12913                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12914            }
12915        }
12916
12917        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12918            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12919
12920            // Revert all internal state mutations and added folders for the failed install
12921            if (addedPkg) {
12922                deletePackageLI(pkgName, null, true, allUsers, perUserInstalled,
12923                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12924            }
12925
12926            // Restore the old package
12927            if (deletedPkg) {
12928                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12929                File restoreFile = new File(deletedPackage.codePath);
12930                // Parse old package
12931                boolean oldExternal = isExternal(deletedPackage);
12932                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12933                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12934                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12935                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12936                try {
12937                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12938                            null);
12939                } catch (PackageManagerException e) {
12940                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12941                            + e.getMessage());
12942                    return;
12943                }
12944
12945                synchronized (mPackages) {
12946                    // Ensure the installer package name up to date
12947                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
12948
12949                    // Update permissions for restored package
12950                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
12951
12952                    mSettings.writeLPr();
12953                }
12954
12955                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12956            }
12957        }
12958    }
12959
12960    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12961            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12962            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12963            PackageInstalledInfo res) {
12964        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12965                + ", old=" + deletedPackage);
12966
12967        final boolean disabledSystem;
12968
12969        // Set the system/privileged flags as needed
12970        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12971        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12972                != 0) {
12973            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12974        }
12975
12976        // Kill package processes including services, providers, etc.
12977        killPackage(deletedPackage, "replace sys pkg");
12978
12979        // Report the result for the parent package only
12980        res.removedInfo.uid = deletedPackage.applicationInfo.uid;
12981        res.removedInfo.removedPackage = deletedPackage.packageName;
12982
12983        // Remove existing system package
12984        removePackageSettingLI(deletedPackage, true);
12985
12986        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
12987        if (!disabledSystem) {
12988            // We didn't need to disable the .apk as a current system package,
12989            // which means we are replacing another update that is already
12990            // installed.  We need to make sure to delete the older one's .apk.
12991            res.removedInfo.args = createInstallArgsForExisting(0,
12992                    deletedPackage.applicationInfo.getCodePath(),
12993                    deletedPackage.applicationInfo.getResourcePath(),
12994                    getAppDexInstructionSets(deletedPackage.applicationInfo));
12995        } else {
12996            res.removedInfo.args = null;
12997        }
12998
12999        // Successfully disabled the old package. Now proceed with re-installation
13000        deleteCodeCacheDirsLI(pkg);
13001
13002        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13003        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13004                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13005
13006        PackageParser.Package newPackage = null;
13007        try {
13008            // Add the package to the internal data structures
13009            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13010
13011            // Set the update and install times
13012            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13013            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13014                    System.currentTimeMillis());
13015
13016            // Check for shared user id changes
13017            String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage);
13018            if (invalidPackageName != null) {
13019                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13020                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13021                                + " to " + invalidPackageName);
13022            }
13023
13024            // Update the package dynamic state if succeeded
13025            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13026                // Now that the install succeeded make sure we remove data
13027                // directories for any child package the update removed.
13028                final int deletedChildCount = (deletedPackage.childPackages != null)
13029                        ? deletedPackage.childPackages.size() : 0;
13030                final int newChildCount = (newPackage.childPackages != null)
13031                        ? newPackage.childPackages.size() : 0;
13032                for (int i = 0; i < deletedChildCount; i++) {
13033                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13034                    boolean childPackageDeleted = true;
13035                    for (int j = 0; j < newChildCount; j++) {
13036                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13037                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13038                            childPackageDeleted = false;
13039                            break;
13040                        }
13041                    }
13042                    if (childPackageDeleted) {
13043                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13044                                deletedChildPkg.packageName);
13045                        if (ps != null) {
13046                            removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false);
13047                        }
13048                    }
13049                }
13050
13051                updateSettingsLI(newPackage, installerPackageName, allUsers,
13052                        perUserInstalled, res, user);
13053                prepareAppDataAfterInstall(newPackage);
13054            }
13055        } catch (PackageManagerException e) {
13056            res.returnCode = INSTALL_FAILED_INTERNAL_ERROR;
13057            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13058        }
13059
13060        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13061            // Re installation failed. Restore old information
13062            // Remove new pkg information
13063            if (newPackage != null) {
13064                removeInstalledPackageLI(newPackage, true);
13065            }
13066            // Add back the old system package
13067            try {
13068                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13069            } catch (PackageManagerException e) {
13070                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13071            }
13072
13073            synchronized (mPackages) {
13074                if (disabledSystem) {
13075                    enableSystemPackageLPw(deletedPackage);
13076                }
13077
13078                // Ensure the installer package name up to date
13079                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13080
13081                // Update permissions for restored package
13082                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13083
13084                mSettings.writeLPr();
13085            }
13086
13087            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13088                    + " after failed upgrade");
13089        }
13090    }
13091
13092    /**
13093     * Checks whether the parent or any of the child packages have a change shared
13094     * user. For a package to be a valid update the shred users of the parent and
13095     * the children should match. We may later support changing child shared users.
13096     * @param oldPkg The updated package.
13097     * @param newPkg The update package.
13098     * @return The shared user that change between the versions.
13099     */
13100    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13101            PackageParser.Package newPkg) {
13102        // Check parent shared user
13103        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13104            return newPkg.packageName;
13105        }
13106        // Check child shared users
13107        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13108        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13109        for (int i = 0; i < newChildCount; i++) {
13110            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13111            // If this child was present, did it have the same shared user?
13112            for (int j = 0; j < oldChildCount; j++) {
13113                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13114                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13115                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13116                    return newChildPkg.packageName;
13117                }
13118            }
13119        }
13120        return null;
13121    }
13122
13123    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13124        // Remove the lib path for the parent package
13125        PackageSetting ps = (PackageSetting) pkg.mExtras;
13126        if (ps != null) {
13127            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13128        }
13129        // Remove the lib path for the child packages
13130        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13131        for (int i = 0; i < childCount; i++) {
13132            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13133            if (ps != null) {
13134                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13135            }
13136        }
13137    }
13138
13139    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13140        // Enable the parent package
13141        mSettings.enableSystemPackageLPw(pkg.packageName);
13142        // Enable the child packages
13143        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13144        for (int i = 0; i < childCount; i++) {
13145            PackageParser.Package childPkg = pkg.childPackages.get(i);
13146            mSettings.enableSystemPackageLPw(childPkg.packageName);
13147        }
13148    }
13149
13150    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13151            PackageParser.Package newPkg) {
13152        // Disable the parent package (parent always replaced)
13153        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13154        // Disable the child packages
13155        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13156        for (int i = 0; i < childCount; i++) {
13157            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13158            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13159            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13160        }
13161        return disabled;
13162    }
13163
13164    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13165            String installerPackageName) {
13166        // Enable the parent package
13167        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13168        // Enable the child packages
13169        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13170        for (int i = 0; i < childCount; i++) {
13171            PackageParser.Package childPkg = pkg.childPackages.get(i);
13172            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13173        }
13174    }
13175
13176    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13177        // Collect all used permissions in the UID
13178        ArraySet<String> usedPermissions = new ArraySet<>();
13179        final int packageCount = su.packages.size();
13180        for (int i = 0; i < packageCount; i++) {
13181            PackageSetting ps = su.packages.valueAt(i);
13182            if (ps.pkg == null) {
13183                continue;
13184            }
13185            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13186            for (int j = 0; j < requestedPermCount; j++) {
13187                String permission = ps.pkg.requestedPermissions.get(j);
13188                BasePermission bp = mSettings.mPermissions.get(permission);
13189                if (bp != null) {
13190                    usedPermissions.add(permission);
13191                }
13192            }
13193        }
13194
13195        PermissionsState permissionsState = su.getPermissionsState();
13196        // Prune install permissions
13197        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13198        final int installPermCount = installPermStates.size();
13199        for (int i = installPermCount - 1; i >= 0;  i--) {
13200            PermissionState permissionState = installPermStates.get(i);
13201            if (!usedPermissions.contains(permissionState.getName())) {
13202                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13203                if (bp != null) {
13204                    permissionsState.revokeInstallPermission(bp);
13205                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13206                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13207                }
13208            }
13209        }
13210
13211        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13212
13213        // Prune runtime permissions
13214        for (int userId : allUserIds) {
13215            List<PermissionState> runtimePermStates = permissionsState
13216                    .getRuntimePermissionStates(userId);
13217            final int runtimePermCount = runtimePermStates.size();
13218            for (int i = runtimePermCount - 1; i >= 0; i--) {
13219                PermissionState permissionState = runtimePermStates.get(i);
13220                if (!usedPermissions.contains(permissionState.getName())) {
13221                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13222                    if (bp != null) {
13223                        permissionsState.revokeRuntimePermission(bp, userId);
13224                        permissionsState.updatePermissionFlags(bp, userId,
13225                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13226                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13227                                runtimePermissionChangedUserIds, userId);
13228                    }
13229                }
13230            }
13231        }
13232
13233        return runtimePermissionChangedUserIds;
13234    }
13235
13236    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13237            int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) {
13238        // Update the parent package setting
13239        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled,
13240                res, user);
13241        // Update the child packages setting
13242        final int childCount = (newPackage.childPackages != null)
13243                ? newPackage.childPackages.size() : 0;
13244        for (int i = 0; i < childCount; i++) {
13245            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13246            updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled,
13247                    res, user);
13248        }
13249    }
13250
13251    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13252            String installerPackageName, int[] allUsers, boolean[] perUserInstalled,
13253            PackageInstalledInfo res, UserHandle user) {
13254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13255
13256        String pkgName = newPackage.packageName;
13257        synchronized (mPackages) {
13258            //write settings. the installStatus will be incomplete at this stage.
13259            //note that the new package setting would have already been
13260            //added to mPackages. It hasn't been persisted yet.
13261            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13262            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13263            mSettings.writeLPr();
13264            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13265        }
13266
13267        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13268        synchronized (mPackages) {
13269            updatePermissionsLPw(newPackage.packageName, newPackage,
13270                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13271                            ? UPDATE_PERMISSIONS_ALL : 0));
13272            // For system-bundled packages, we assume that installing an upgraded version
13273            // of the package implies that the user actually wants to run that new code,
13274            // so we enable the package.
13275            PackageSetting ps = mSettings.mPackages.get(pkgName);
13276            if (ps != null) {
13277                if (isSystemApp(newPackage)) {
13278                    // NB: implicit assumption that system package upgrades apply to all users
13279                    if (DEBUG_INSTALL) {
13280                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13281                    }
13282                    if (res.origUsers != null) {
13283                        for (int userHandle : res.origUsers) {
13284                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13285                                    userHandle, installerPackageName);
13286                        }
13287                    }
13288                    // Also convey the prior install/uninstall state
13289                    if (allUsers != null && perUserInstalled != null) {
13290                        for (int i = 0; i < allUsers.length; i++) {
13291                            if (DEBUG_INSTALL) {
13292                                Slog.d(TAG, "    user " + allUsers[i]
13293                                        + " => " + perUserInstalled[i]);
13294                            }
13295                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
13296                        }
13297                        // these install state changes will be persisted in the
13298                        // upcoming call to mSettings.writeLPr().
13299                    }
13300                }
13301                // It's implied that when a user requests installation, they want the app to be
13302                // installed and enabled.
13303                int userId = user.getIdentifier();
13304                if (userId != UserHandle.USER_ALL) {
13305                    ps.setInstalled(true, userId);
13306                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13307                }
13308            }
13309            res.name = pkgName;
13310            res.uid = newPackage.applicationInfo.uid;
13311            res.pkg = newPackage;
13312            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13313            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13314            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13315            //to update install status
13316            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13317            mSettings.writeLPr();
13318            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13319        }
13320
13321        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13322    }
13323
13324    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13325        try {
13326            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13327            installPackageLI(args, res);
13328        } finally {
13329            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13330        }
13331    }
13332
13333    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13334        final int installFlags = args.installFlags;
13335        final String installerPackageName = args.installerPackageName;
13336        final String volumeUuid = args.volumeUuid;
13337        final File tmpPackageFile = new File(args.getCodePath());
13338        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13339        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13340                || (args.volumeUuid != null));
13341        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13342        boolean replace = false;
13343        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13344        if (args.move != null) {
13345            // moving a complete application; perfom an initial scan on the new install location
13346            scanFlags |= SCAN_INITIAL;
13347        }
13348        // Result object to be returned
13349        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13350
13351        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13352
13353        // Sanity check
13354        if (ephemeral && (forwardLocked || onExternal)) {
13355            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13356                    + " external=" + onExternal);
13357            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
13358            return;
13359        }
13360
13361        // Retrieve PackageSettings and parse package
13362        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13363                | PackageParser.PARSE_ENFORCE_CODE
13364                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13365                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13366                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13367        PackageParser pp = new PackageParser();
13368        pp.setSeparateProcesses(mSeparateProcesses);
13369        pp.setDisplayMetrics(mMetrics);
13370
13371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13372        final PackageParser.Package pkg;
13373        try {
13374            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13375        } catch (PackageParserException e) {
13376            res.setError("Failed parse during installPackageLI", e);
13377            return;
13378        } finally {
13379            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13380        }
13381
13382        // If package doesn't declare API override, mark that we have an install
13383        // time CPU ABI override.
13384        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13385            pkg.cpuAbiOverride = args.abiOverride;
13386        }
13387
13388        String pkgName = res.name = pkg.packageName;
13389        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13390            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13391                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13392                return;
13393            }
13394        }
13395
13396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13397        try {
13398            PackageParser.collectCertificates(pkg, parseFlags);
13399        } catch (PackageParserException e) {
13400            res.setError("Failed collect during installPackageLI", e);
13401            return;
13402        } finally {
13403            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13404        }
13405
13406        // Get rid of all references to package scan path via parser.
13407        pp = null;
13408        String oldCodePath = null;
13409        boolean systemApp = false;
13410        synchronized (mPackages) {
13411            // Check if installing already existing package
13412            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13413                String oldName = mSettings.mRenamedPackages.get(pkgName);
13414                if (pkg.mOriginalPackages != null
13415                        && pkg.mOriginalPackages.contains(oldName)
13416                        && mPackages.containsKey(oldName)) {
13417                    // This package is derived from an original package,
13418                    // and this device has been updating from that original
13419                    // name.  We must continue using the original name, so
13420                    // rename the new package here.
13421                    pkg.setPackageName(oldName);
13422                    pkgName = pkg.packageName;
13423                    replace = true;
13424                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13425                            + oldName + " pkgName=" + pkgName);
13426                } else if (mPackages.containsKey(pkgName)) {
13427                    // This package, under its official name, already exists
13428                    // on the device; we should replace it.
13429                    replace = true;
13430                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13431                }
13432
13433                // Child packages are installed through the parent package
13434                if (pkg.parentPackage != null) {
13435                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13436                            "Package " + pkg.packageName + " is child of package "
13437                                    + pkg.parentPackage.parentPackage + ". Child packages "
13438                                    + "can be updated only through the parent package.");
13439                    return;
13440                }
13441
13442                if (replace) {
13443                    // Prevent apps opting out from runtime permissions
13444                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13445                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13446                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13447                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13448                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13449                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13450                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13451                                        + " doesn't support runtime permissions but the old"
13452                                        + " target SDK " + oldTargetSdk + " does.");
13453                        return;
13454                    }
13455
13456                    // Prevent installing of child packages
13457                    if (oldPackage.parentPackage != null) {
13458                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13459                                "Package " + pkg.packageName + " is child of package "
13460                                        + oldPackage.parentPackage + ". Child packages "
13461                                        + "can be updated only through the parent package.");
13462                        return;
13463                    }
13464                }
13465            }
13466
13467            PackageSetting ps = mSettings.mPackages.get(pkgName);
13468            if (ps != null) {
13469                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13470
13471                // Quick sanity check that we're signed correctly if updating;
13472                // we'll check this again later when scanning, but we want to
13473                // bail early here before tripping over redefined permissions.
13474                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13475                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13476                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13477                                + pkg.packageName + " upgrade keys do not match the "
13478                                + "previously installed version");
13479                        return;
13480                    }
13481                } else {
13482                    try {
13483                        verifySignaturesLP(ps, pkg);
13484                    } catch (PackageManagerException e) {
13485                        res.setError(e.error, e.getMessage());
13486                        return;
13487                    }
13488                }
13489
13490                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13491                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13492                    systemApp = (ps.pkg.applicationInfo.flags &
13493                            ApplicationInfo.FLAG_SYSTEM) != 0;
13494                }
13495                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13496            }
13497
13498            // Check whether the newly-scanned package wants to define an already-defined perm
13499            int N = pkg.permissions.size();
13500            for (int i = N-1; i >= 0; i--) {
13501                PackageParser.Permission perm = pkg.permissions.get(i);
13502                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13503                if (bp != null) {
13504                    // If the defining package is signed with our cert, it's okay.  This
13505                    // also includes the "updating the same package" case, of course.
13506                    // "updating same package" could also involve key-rotation.
13507                    final boolean sigsOk;
13508                    if (bp.sourcePackage.equals(pkg.packageName)
13509                            && (bp.packageSetting instanceof PackageSetting)
13510                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13511                                    scanFlags))) {
13512                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13513                    } else {
13514                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13515                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13516                    }
13517                    if (!sigsOk) {
13518                        // If the owning package is the system itself, we log but allow
13519                        // install to proceed; we fail the install on all other permission
13520                        // redefinitions.
13521                        if (!bp.sourcePackage.equals("android")) {
13522                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13523                                    + pkg.packageName + " attempting to redeclare permission "
13524                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13525                            res.origPermission = perm.info.name;
13526                            res.origPackage = bp.sourcePackage;
13527                            return;
13528                        } else {
13529                            Slog.w(TAG, "Package " + pkg.packageName
13530                                    + " attempting to redeclare system permission "
13531                                    + perm.info.name + "; ignoring new declaration");
13532                            pkg.permissions.remove(i);
13533                        }
13534                    }
13535                }
13536            }
13537        }
13538
13539        if (systemApp) {
13540            if (onExternal) {
13541                // Abort update; system app can't be replaced with app on sdcard
13542                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13543                        "Cannot install updates to system apps on sdcard");
13544                return;
13545            } else if (ephemeral) {
13546                // Abort update; system app can't be replaced with an ephemeral app
13547                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13548                        "Cannot update a system app with an ephemeral app");
13549                return;
13550            }
13551        }
13552
13553        if (args.move != null) {
13554            // We did an in-place move, so dex is ready to roll
13555            scanFlags |= SCAN_NO_DEX;
13556            scanFlags |= SCAN_MOVE;
13557
13558            synchronized (mPackages) {
13559                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13560                if (ps == null) {
13561                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13562                            "Missing settings for moved package " + pkgName);
13563                }
13564
13565                // We moved the entire application as-is, so bring over the
13566                // previously derived ABI information.
13567                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13568                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13569            }
13570
13571        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13572            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13573            scanFlags |= SCAN_NO_DEX;
13574
13575            try {
13576                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13577                    args.abiOverride : pkg.cpuAbiOverride);
13578                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13579                        true /* extract libs */);
13580            } catch (PackageManagerException pme) {
13581                Slog.e(TAG, "Error deriving application ABI", pme);
13582                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13583                return;
13584            }
13585
13586            // Extract package to save the VM unzipping the APK in memory during
13587            // launch. Only do this if profile-guided compilation is enabled because
13588            // otherwise BackgroundDexOptService will not dexopt the package later.
13589            if (mUseJitProfiles) {
13590                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13591                // Do not run PackageDexOptimizer through the local performDexOpt
13592                // method because `pkg` is not in `mPackages` yet.
13593                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13594                        false /* useProfiles */, true /* extractOnly */);
13595                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13596                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13597                    String msg = "Extracking package failed for " + pkgName;
13598                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13599                    return;
13600                }
13601            }
13602        }
13603
13604        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13605            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13606            return;
13607        }
13608
13609        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13610
13611        if (replace) {
13612            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13613                    installerPackageName, volumeUuid, res);
13614        } else {
13615            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13616                    args.user, installerPackageName, volumeUuid, res);
13617        }
13618        synchronized (mPackages) {
13619            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13620            if (ps != null) {
13621                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13622            }
13623        }
13624    }
13625
13626    private void startIntentFilterVerifications(int userId, boolean replacing,
13627            PackageParser.Package pkg) {
13628        if (mIntentFilterVerifierComponent == null) {
13629            Slog.w(TAG, "No IntentFilter verification will not be done as "
13630                    + "there is no IntentFilterVerifier available!");
13631            return;
13632        }
13633
13634        final int verifierUid = getPackageUid(
13635                mIntentFilterVerifierComponent.getPackageName(),
13636                MATCH_DEBUG_TRIAGED_MISSING,
13637                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13638
13639        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13640        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13641        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13642        mHandler.sendMessage(msg);
13643    }
13644
13645    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13646            PackageParser.Package pkg) {
13647        int size = pkg.activities.size();
13648        if (size == 0) {
13649            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13650                    "No activity, so no need to verify any IntentFilter!");
13651            return;
13652        }
13653
13654        final boolean hasDomainURLs = hasDomainURLs(pkg);
13655        if (!hasDomainURLs) {
13656            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13657                    "No domain URLs, so no need to verify any IntentFilter!");
13658            return;
13659        }
13660
13661        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13662                + " if any IntentFilter from the " + size
13663                + " Activities needs verification ...");
13664
13665        int count = 0;
13666        final String packageName = pkg.packageName;
13667
13668        synchronized (mPackages) {
13669            // If this is a new install and we see that we've already run verification for this
13670            // package, we have nothing to do: it means the state was restored from backup.
13671            if (!replacing) {
13672                IntentFilterVerificationInfo ivi =
13673                        mSettings.getIntentFilterVerificationLPr(packageName);
13674                if (ivi != null) {
13675                    if (DEBUG_DOMAIN_VERIFICATION) {
13676                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13677                                + ivi.getStatusString());
13678                    }
13679                    return;
13680                }
13681            }
13682
13683            // If any filters need to be verified, then all need to be.
13684            boolean needToVerify = false;
13685            for (PackageParser.Activity a : pkg.activities) {
13686                for (ActivityIntentInfo filter : a.intents) {
13687                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13688                        if (DEBUG_DOMAIN_VERIFICATION) {
13689                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13690                        }
13691                        needToVerify = true;
13692                        break;
13693                    }
13694                }
13695            }
13696
13697            if (needToVerify) {
13698                final int verificationId = mIntentFilterVerificationToken++;
13699                for (PackageParser.Activity a : pkg.activities) {
13700                    for (ActivityIntentInfo filter : a.intents) {
13701                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13702                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13703                                    "Verification needed for IntentFilter:" + filter.toString());
13704                            mIntentFilterVerifier.addOneIntentFilterVerification(
13705                                    verifierUid, userId, verificationId, filter, packageName);
13706                            count++;
13707                        }
13708                    }
13709                }
13710            }
13711        }
13712
13713        if (count > 0) {
13714            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13715                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13716                    +  " for userId:" + userId);
13717            mIntentFilterVerifier.startVerifications(userId);
13718        } else {
13719            if (DEBUG_DOMAIN_VERIFICATION) {
13720                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13721            }
13722        }
13723    }
13724
13725    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13726        final ComponentName cn  = filter.activity.getComponentName();
13727        final String packageName = cn.getPackageName();
13728
13729        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13730                packageName);
13731        if (ivi == null) {
13732            return true;
13733        }
13734        int status = ivi.getStatus();
13735        switch (status) {
13736            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13737            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13738                return true;
13739
13740            default:
13741                // Nothing to do
13742                return false;
13743        }
13744    }
13745
13746    private static boolean isMultiArch(ApplicationInfo info) {
13747        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13748    }
13749
13750    private static boolean isExternal(PackageParser.Package pkg) {
13751        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13752    }
13753
13754    private static boolean isExternal(PackageSetting ps) {
13755        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13756    }
13757
13758    private static boolean isEphemeral(PackageParser.Package pkg) {
13759        return pkg.applicationInfo.isEphemeralApp();
13760    }
13761
13762    private static boolean isEphemeral(PackageSetting ps) {
13763        return ps.pkg != null && isEphemeral(ps.pkg);
13764    }
13765
13766    private static boolean isSystemApp(PackageParser.Package pkg) {
13767        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13768    }
13769
13770    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13771        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13772    }
13773
13774    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13775        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13776    }
13777
13778    private static boolean isSystemApp(PackageSetting ps) {
13779        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13780    }
13781
13782    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13783        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13784    }
13785
13786    private int packageFlagsToInstallFlags(PackageSetting ps) {
13787        int installFlags = 0;
13788        if (isEphemeral(ps)) {
13789            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13790        }
13791        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13792            // This existing package was an external ASEC install when we have
13793            // the external flag without a UUID
13794            installFlags |= PackageManager.INSTALL_EXTERNAL;
13795        }
13796        if (ps.isForwardLocked()) {
13797            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13798        }
13799        return installFlags;
13800    }
13801
13802    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13803        if (isExternal(pkg)) {
13804            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13805                return StorageManager.UUID_PRIMARY_PHYSICAL;
13806            } else {
13807                return pkg.volumeUuid;
13808            }
13809        } else {
13810            return StorageManager.UUID_PRIVATE_INTERNAL;
13811        }
13812    }
13813
13814    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13815        if (isExternal(pkg)) {
13816            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13817                return mSettings.getExternalVersion();
13818            } else {
13819                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13820            }
13821        } else {
13822            return mSettings.getInternalVersion();
13823        }
13824    }
13825
13826    private void deleteTempPackageFiles() {
13827        final FilenameFilter filter = new FilenameFilter() {
13828            public boolean accept(File dir, String name) {
13829                return name.startsWith("vmdl") && name.endsWith(".tmp");
13830            }
13831        };
13832        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13833            file.delete();
13834        }
13835    }
13836
13837    @Override
13838    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13839            int flags) {
13840        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13841                flags);
13842    }
13843
13844    @Override
13845    public void deletePackage(final String packageName,
13846            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13847        mContext.enforceCallingOrSelfPermission(
13848                android.Manifest.permission.DELETE_PACKAGES, null);
13849        Preconditions.checkNotNull(packageName);
13850        Preconditions.checkNotNull(observer);
13851        final int uid = Binder.getCallingUid();
13852        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13853        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13854        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13855            mContext.enforceCallingOrSelfPermission(
13856                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13857                    "deletePackage for user " + userId);
13858        }
13859
13860        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13861            try {
13862                observer.onPackageDeleted(packageName,
13863                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13864            } catch (RemoteException re) {
13865            }
13866            return;
13867        }
13868
13869        for (int currentUserId : users) {
13870            if (getBlockUninstallForUser(packageName, currentUserId)) {
13871                try {
13872                    observer.onPackageDeleted(packageName,
13873                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13874                } catch (RemoteException re) {
13875                }
13876                return;
13877            }
13878        }
13879
13880        if (DEBUG_REMOVE) {
13881            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13882        }
13883        // Queue up an async operation since the package deletion may take a little while.
13884        mHandler.post(new Runnable() {
13885            public void run() {
13886                mHandler.removeCallbacks(this);
13887                final int returnCode = deletePackageX(packageName, userId, flags);
13888                try {
13889                    observer.onPackageDeleted(packageName, returnCode, null);
13890                } catch (RemoteException e) {
13891                    Log.i(TAG, "Observer no longer exists.");
13892                } //end catch
13893            } //end run
13894        });
13895    }
13896
13897    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13898        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13899                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13900        try {
13901            if (dpm != null) {
13902                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13903                        /* callingUserOnly =*/ false);
13904                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13905                        : deviceOwnerComponentName.getPackageName();
13906                // Does the package contains the device owner?
13907                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13908                // this check is probably not needed, since DO should be registered as a device
13909                // admin on some user too. (Original bug for this: b/17657954)
13910                if (packageName.equals(deviceOwnerPackageName)) {
13911                    return true;
13912                }
13913                // Does it contain a device admin for any user?
13914                int[] users;
13915                if (userId == UserHandle.USER_ALL) {
13916                    users = sUserManager.getUserIds();
13917                } else {
13918                    users = new int[]{userId};
13919                }
13920                for (int i = 0; i < users.length; ++i) {
13921                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13922                        return true;
13923                    }
13924                }
13925            }
13926        } catch (RemoteException e) {
13927        }
13928        return false;
13929    }
13930
13931    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13932        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13933    }
13934
13935    /**
13936     *  This method is an internal method that could be get invoked either
13937     *  to delete an installed package or to clean up a failed installation.
13938     *  After deleting an installed package, a broadcast is sent to notify any
13939     *  listeners that the package has been installed. For cleaning up a failed
13940     *  installation, the broadcast is not necessary since the package's
13941     *  installation wouldn't have sent the initial broadcast either
13942     *  The key steps in deleting a package are
13943     *  deleting the package information in internal structures like mPackages,
13944     *  deleting the packages base directories through installd
13945     *  updating mSettings to reflect current status
13946     *  persisting settings for later use
13947     *  sending a broadcast if necessary
13948     */
13949    private int deletePackageX(String packageName, int userId, int flags) {
13950        final PackageRemovedInfo info = new PackageRemovedInfo();
13951        final boolean res;
13952
13953        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13954                ? UserHandle.ALL : new UserHandle(userId);
13955
13956        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13957            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13958            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13959        }
13960
13961        boolean removedForAllUsers = false;
13962        boolean systemUpdate = false;
13963
13964        PackageParser.Package uninstalledPkg;
13965
13966        // for the uninstall-updates case and restricted profiles, remember the per-
13967        // userhandle installed state
13968        int[] allUsers;
13969        boolean[] perUserInstalled;
13970        synchronized (mPackages) {
13971            uninstalledPkg = mPackages.get(packageName);
13972            PackageSetting ps = mSettings.mPackages.get(packageName);
13973            allUsers = sUserManager.getUserIds();
13974            perUserInstalled = new boolean[allUsers.length];
13975            for (int i = 0; i < allUsers.length; i++) {
13976                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13977            }
13978        }
13979
13980        synchronized (mInstallLock) {
13981            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13982            res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled,
13983                    flags | REMOVE_CHATTY, info, true, null);
13984            systemUpdate = info.isRemovedPackageSystemUpdate;
13985            synchronized (mPackages) {
13986                if (res) {
13987                    if (!systemUpdate && mPackages.get(packageName) == null) {
13988                        removedForAllUsers = true;
13989                    }
13990                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13991                }
13992            }
13993            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13994                    + " removedForAllUsers=" + removedForAllUsers);
13995        }
13996
13997        if (res) {
13998            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13999
14000            // If the removed package was a system update, the old system package
14001            // was re-enabled; we need to broadcast this information
14002            if (systemUpdate) {
14003                Bundle extras = new Bundle(1);
14004                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
14005                        ? info.removedAppId : info.uid);
14006                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14007
14008                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
14009                        extras, 0, null, null, null);
14010                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
14011                        extras, 0, null, null, null);
14012                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14013                        null, 0, packageName, null, null);
14014            }
14015        }
14016        // Force a gc here.
14017        Runtime.getRuntime().gc();
14018        // Delete the resources here after sending the broadcast to let
14019        // other processes clean up before deleting resources.
14020        if (info.args != null) {
14021            synchronized (mInstallLock) {
14022                info.args.doPostDeleteLI(true);
14023            }
14024        }
14025
14026        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14027    }
14028
14029    class PackageRemovedInfo {
14030        String removedPackage;
14031        int uid = -1;
14032        int removedAppId = -1;
14033        int[] removedUsers = null;
14034        boolean isRemovedPackageSystemUpdate = false;
14035        // Clean up resources deleted packages.
14036        InstallArgs args = null;
14037
14038        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
14039            Bundle extras = new Bundle(1);
14040            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14041            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
14042            if (replacing) {
14043                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14044            }
14045            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14046            if (removedPackage != null) {
14047                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14048                        extras, 0, null, null, removedUsers);
14049                if (fullRemove && !replacing) {
14050                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
14051                            extras, 0, null, null, removedUsers);
14052                }
14053            }
14054            if (removedAppId >= 0) {
14055                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14056                        removedUsers);
14057            }
14058        }
14059    }
14060
14061    /*
14062     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14063     * flag is not set, the data directory is removed as well.
14064     * make sure this flag is set for partially installed apps. If not its meaningless to
14065     * delete a partially installed application.
14066     */
14067    private void removePackageDataLI(PackageSetting ps,
14068            int[] allUserHandles, boolean[] perUserInstalled,
14069            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14070        String packageName = ps.name;
14071        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14072        removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0);
14073        // Retrieve object to delete permissions for shared user later on
14074        final PackageSetting deletedPs;
14075        // reader
14076        synchronized (mPackages) {
14077            deletedPs = mSettings.mPackages.get(packageName);
14078            if (outInfo != null) {
14079                outInfo.removedPackage = packageName;
14080                outInfo.removedUsers = deletedPs != null
14081                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14082                        : null;
14083            }
14084        }
14085        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14086            removeDataDirsLI(ps.volumeUuid, packageName);
14087            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14088        }
14089        // writer
14090        synchronized (mPackages) {
14091            if (deletedPs != null) {
14092                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14093                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14094                    clearDefaultBrowserIfNeeded(packageName);
14095                    if (outInfo != null) {
14096                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14097                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14098                    }
14099                    updatePermissionsLPw(deletedPs.name, null, 0);
14100                    if (deletedPs.sharedUser != null) {
14101                        // Remove permissions associated with package. Since runtime
14102                        // permissions are per user we have to kill the removed package
14103                        // or packages running under the shared user of the removed
14104                        // package if revoking the permissions requested only by the removed
14105                        // package is successful and this causes a change in gids.
14106                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14107                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14108                                    userId);
14109                            if (userIdToKill == UserHandle.USER_ALL
14110                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14111                                // If gids changed for this user, kill all affected packages.
14112                                mHandler.post(new Runnable() {
14113                                    @Override
14114                                    public void run() {
14115                                        // This has to happen with no lock held.
14116                                        killApplication(deletedPs.name, deletedPs.appId,
14117                                                KILL_APP_REASON_GIDS_CHANGED);
14118                                    }
14119                                });
14120                                break;
14121                            }
14122                        }
14123                    }
14124                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14125                }
14126                // make sure to preserve per-user disabled state if this removal was just
14127                // a downgrade of a system app to the factory package
14128                if (allUserHandles != null && perUserInstalled != null) {
14129                    if (DEBUG_REMOVE) {
14130                        Slog.d(TAG, "Propagating install state across downgrade");
14131                    }
14132                    for (int i = 0; i < allUserHandles.length; i++) {
14133                        if (DEBUG_REMOVE) {
14134                            Slog.d(TAG, "    user " + allUserHandles[i]
14135                                    + " => " + perUserInstalled[i]);
14136                        }
14137                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14138                    }
14139                }
14140            }
14141            // can downgrade to reader
14142            if (writeSettings) {
14143                // Save settings now
14144                mSettings.writeLPr();
14145            }
14146        }
14147        if (outInfo != null) {
14148            // A user ID was deleted here. Go through all users and remove it
14149            // from KeyStore.
14150            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14151        }
14152    }
14153
14154    static boolean locationIsPrivileged(File path) {
14155        try {
14156            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14157                    .getCanonicalPath();
14158            return path.getCanonicalPath().startsWith(privilegedAppDir);
14159        } catch (IOException e) {
14160            Slog.e(TAG, "Unable to access code path " + path);
14161        }
14162        return false;
14163    }
14164
14165    /*
14166     * Tries to delete system package.
14167     */
14168    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14169            PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled,
14170            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14171            PackageParser.Package replacingPackage) {
14172        if (deletedPkg.parentPackage != null) {
14173            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14174            return false;
14175        }
14176
14177        final boolean applyUserRestrictions
14178                = (allUserHandles != null) && (perUserInstalled != null);
14179        final PackageSetting disabledPs;
14180        // Confirm if the system package has been updated
14181        // An updated system app can be deleted. This will also have to restore
14182        // the system pkg from system partition
14183        // reader
14184        synchronized (mPackages) {
14185            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14186        }
14187
14188        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14189                + " disabledPs=" + disabledPs);
14190
14191        if (disabledPs == null) {
14192            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14193            return false;
14194        } else if (DEBUG_REMOVE) {
14195            Slog.d(TAG, "Deleting system pkg from data partition");
14196        }
14197
14198        if (DEBUG_REMOVE) {
14199            if (applyUserRestrictions) {
14200                Slog.d(TAG, "Remembering install states:");
14201                for (int i = 0; i < allUserHandles.length; i++) {
14202                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
14203                }
14204            }
14205        }
14206
14207        // Delete the updated package
14208        outInfo.isRemovedPackageSystemUpdate = true;
14209        if (disabledPs.versionCode < deletedPs.versionCode) {
14210            // Delete data for downgrades
14211            flags &= ~PackageManager.DELETE_KEEP_DATA;
14212        } else {
14213            // Preserve data by setting flag
14214            flags |= PackageManager.DELETE_KEEP_DATA;
14215        }
14216        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14217                perUserInstalled, outInfo, writeSettings, replacingPackage);
14218        if (!ret) {
14219            return false;
14220        }
14221
14222        // writer
14223        synchronized (mPackages) {
14224            // Reinstate the old system package
14225            enableSystemPackageLPw(disabledPs.pkg);
14226            // Remove any native libraries from the upgraded package.
14227            removeNativeBinariesLI(deletedPkg);
14228        }
14229
14230        // Install the system package
14231        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14232        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14233        if (locationIsPrivileged(disabledPs.codePath)) {
14234            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14235        }
14236
14237        final PackageParser.Package newPkg;
14238        try {
14239            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14240        } catch (PackageManagerException e) {
14241            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14242                    + e.getMessage());
14243            return false;
14244        }
14245
14246        prepareAppDataAfterInstall(newPkg);
14247
14248        // writer
14249        synchronized (mPackages) {
14250            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14251
14252            // Propagate the permissions state as we do not want to drop on the floor
14253            // runtime permissions. The update permissions method below will take
14254            // care of removing obsolete permissions and grant install permissions.
14255            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14256            updatePermissionsLPw(newPkg.packageName, newPkg,
14257                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14258
14259            if (applyUserRestrictions) {
14260                if (DEBUG_REMOVE) {
14261                    Slog.d(TAG, "Propagating install state across reinstall");
14262                }
14263                for (int i = 0; i < allUserHandles.length; i++) {
14264                    if (DEBUG_REMOVE) {
14265                        Slog.d(TAG, "    user " + allUserHandles[i]
14266                                + " => " + perUserInstalled[i]);
14267                    }
14268                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14269
14270                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
14271                }
14272                // Regardless of writeSettings we need to ensure that this restriction
14273                // state propagation is persisted
14274                mSettings.writeAllUsersPackageRestrictionsLPr();
14275            }
14276            // can downgrade to reader here
14277            if (writeSettings) {
14278                mSettings.writeLPr();
14279            }
14280        }
14281        return true;
14282    }
14283
14284    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14285            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14286            boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings,
14287            PackageParser.Package replacingPackage) {
14288        PackageSetting ps = null;
14289
14290        synchronized (mPackages) {
14291            pkg = mPackages.get(pkg.packageName);
14292            if (pkg == null) {
14293                return false;
14294            }
14295
14296            ps = mSettings.mPackages.get(pkg.packageName);
14297            if (ps == null) {
14298                return false;
14299            }
14300
14301            if (outInfo != null) {
14302                outInfo.uid = ps.appId;
14303            }
14304        }
14305
14306        // Delete package data from internal structures and also remove data if flag is set
14307        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags,
14308                    writeSettings);
14309
14310        // Delete the child packages data
14311        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14312        for (int i = 0; i < childCount; i++) {
14313            PackageSetting childPs;
14314            synchronized (mPackages) {
14315                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14316            }
14317            if (childPs != null) {
14318                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14319                        && (replacingPackage != null
14320                        && !replacingPackage.hasChildPackage(childPs.name))
14321                        ? flags & ~DELETE_KEEP_DATA : flags;
14322                removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo,
14323                        deleteFlags, writeSettings);
14324            }
14325        }
14326
14327        // Delete application code and resources only for parent packages
14328        if (ps.pkg.parentPackage == null) {
14329                if (deleteCodeAndResources && (outInfo != null)) {
14330                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14331                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14332                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14333            }
14334        }
14335
14336        return true;
14337    }
14338
14339    @Override
14340    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14341            int userId) {
14342        mContext.enforceCallingOrSelfPermission(
14343                android.Manifest.permission.DELETE_PACKAGES, null);
14344        synchronized (mPackages) {
14345            PackageSetting ps = mSettings.mPackages.get(packageName);
14346            if (ps == null) {
14347                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14348                return false;
14349            }
14350            if (!ps.getInstalled(userId)) {
14351                // Can't block uninstall for an app that is not installed or enabled.
14352                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14353                return false;
14354            }
14355            ps.setBlockUninstall(blockUninstall, userId);
14356            mSettings.writePackageRestrictionsLPr(userId);
14357        }
14358        return true;
14359    }
14360
14361    @Override
14362    public boolean getBlockUninstallForUser(String packageName, int userId) {
14363        synchronized (mPackages) {
14364            PackageSetting ps = mSettings.mPackages.get(packageName);
14365            if (ps == null) {
14366                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14367                return false;
14368            }
14369            return ps.getBlockUninstall(userId);
14370        }
14371    }
14372
14373    @Override
14374    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14375        int callingUid = Binder.getCallingUid();
14376        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14377            throw new SecurityException(
14378                    "setRequiredForSystemUser can only be run by the system or root");
14379        }
14380        synchronized (mPackages) {
14381            PackageSetting ps = mSettings.mPackages.get(packageName);
14382            if (ps == null) {
14383                Log.w(TAG, "Package doesn't exist: " + packageName);
14384                return false;
14385            }
14386            if (systemUserApp) {
14387                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14388            } else {
14389                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14390            }
14391            mSettings.writeLPr();
14392        }
14393        return true;
14394    }
14395
14396    /*
14397     * This method handles package deletion in general
14398     */
14399    private boolean deletePackageLI(String packageName, UserHandle user,
14400            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
14401            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14402            PackageParser.Package replacingPackage) {
14403        if (packageName == null) {
14404            Slog.w(TAG, "Attempt to delete null packageName.");
14405            return false;
14406        }
14407
14408        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14409
14410        PackageSetting ps;
14411        int removeUser = -1;
14412
14413        synchronized (mPackages) {
14414            ps = mSettings.mPackages.get(packageName);
14415            if (ps == null) {
14416                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14417                return false;
14418            }
14419
14420            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14421                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14422                if (DEBUG_REMOVE) {
14423                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14424                            + ((user == null) ? UserHandle.USER_ALL : user));
14425                }
14426                if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14427                    return false;
14428                }
14429                markPackageUninstalledForUserLPw(ps, user);
14430                scheduleWritePackageRestrictionsLocked(user);
14431                return true;
14432            }
14433        }
14434
14435        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14436                && user.getIdentifier() != UserHandle.USER_ALL)) {
14437            // The caller is asking that the package only be deleted for a single
14438            // user.  To do this, we just mark its uninstalled state and delete
14439            // its data. If this is a system app, we only allow this to happen if
14440            // they have set the special DELETE_SYSTEM_APP which requests different
14441            // semantics than normal for uninstalling system apps.
14442            markPackageUninstalledForUserLPw(ps, user);
14443
14444            if (!isSystemApp(ps)) {
14445                // Do not uninstall the APK if an app should be cached
14446                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14447                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14448                    // Other user still have this package installed, so all
14449                    // we need to do is clear this user's data and save that
14450                // it is uninstalled.
14451                if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14452                    if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14453                        return false;
14454                    }
14455                    scheduleWritePackageRestrictionsLocked(user);
14456                    return true;
14457                } else {
14458                    // We need to set it back to 'installed' so the uninstall
14459                    // broadcasts will be sent correctly.
14460                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14461                    ps.setInstalled(true, user.getIdentifier());
14462                }
14463            } else {
14464                // This is a system app, so we assume that the
14465                // other users still have this package installed, so all
14466                // we need to do is clear this user's data and save that
14467                // it is uninstalled.
14468                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14469                if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14470                    return false;
14471                }
14472                scheduleWritePackageRestrictionsLocked(user);
14473                return true;
14474            }
14475        }
14476
14477        boolean ret = false;
14478        if (isSystemApp(ps)) {
14479            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14480            // When an updated system application is deleted we delete the existing resources as well and
14481            // fall back to existing code in system partition
14482            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled,
14483                    flags, outInfo, writeSettings, replacingPackage);
14484        } else {
14485            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14486            // Kill application pre-emptively especially for apps on sd.
14487            killApplication(packageName, ps.appId, "uninstall pkg");
14488            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14489                    perUserInstalled, outInfo, writeSettings, replacingPackage);
14490        }
14491
14492        return ret;
14493    }
14494
14495    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14496        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14497                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14498        for (int nextUserId : userIds) {
14499            if (DEBUG_REMOVE) {
14500                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14501            }
14502            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14503                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14504                    false /*hidden*/, false /*suspended*/, null, null, null,
14505                    false /*blockUninstall*/,
14506                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14507        }
14508    }
14509
14510    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14511            PackageRemovedInfo outInfo) {
14512        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14513                : new int[] {userId};
14514        for (int nextUserId : userIds) {
14515            if (DEBUG_REMOVE) {
14516                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14517                        + nextUserId);
14518            }
14519            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14520            try {
14521                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14522            } catch (InstallerException e) {
14523                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14524                return false;
14525            }
14526            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14527            schedulePackageCleaning(ps.name, nextUserId, false);
14528            synchronized (mPackages) {
14529                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14530                    scheduleWritePackageRestrictionsLocked(nextUserId);
14531                }
14532                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14533            }
14534        }
14535
14536        if (outInfo != null) {
14537            outInfo.removedPackage = ps.name;
14538            outInfo.removedAppId = ps.appId;
14539            outInfo.removedUsers = userIds;
14540        }
14541
14542        return true;
14543    }
14544
14545    private final class ClearStorageConnection implements ServiceConnection {
14546        IMediaContainerService mContainerService;
14547
14548        @Override
14549        public void onServiceConnected(ComponentName name, IBinder service) {
14550            synchronized (this) {
14551                mContainerService = IMediaContainerService.Stub.asInterface(service);
14552                notifyAll();
14553            }
14554        }
14555
14556        @Override
14557        public void onServiceDisconnected(ComponentName name) {
14558        }
14559    }
14560
14561    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14562        final boolean mounted;
14563        if (Environment.isExternalStorageEmulated()) {
14564            mounted = true;
14565        } else {
14566            final String status = Environment.getExternalStorageState();
14567
14568            mounted = status.equals(Environment.MEDIA_MOUNTED)
14569                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14570        }
14571
14572        if (!mounted) {
14573            return;
14574        }
14575
14576        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14577        int[] users;
14578        if (userId == UserHandle.USER_ALL) {
14579            users = sUserManager.getUserIds();
14580        } else {
14581            users = new int[] { userId };
14582        }
14583        final ClearStorageConnection conn = new ClearStorageConnection();
14584        if (mContext.bindServiceAsUser(
14585                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14586            try {
14587                for (int curUser : users) {
14588                    long timeout = SystemClock.uptimeMillis() + 5000;
14589                    synchronized (conn) {
14590                        long now = SystemClock.uptimeMillis();
14591                        while (conn.mContainerService == null && now < timeout) {
14592                            try {
14593                                conn.wait(timeout - now);
14594                            } catch (InterruptedException e) {
14595                            }
14596                        }
14597                    }
14598                    if (conn.mContainerService == null) {
14599                        return;
14600                    }
14601
14602                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14603                    clearDirectory(conn.mContainerService,
14604                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14605                    if (allData) {
14606                        clearDirectory(conn.mContainerService,
14607                                userEnv.buildExternalStorageAppDataDirs(packageName));
14608                        clearDirectory(conn.mContainerService,
14609                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14610                    }
14611                }
14612            } finally {
14613                mContext.unbindService(conn);
14614            }
14615        }
14616    }
14617
14618    @Override
14619    public void clearApplicationUserData(final String packageName,
14620            final IPackageDataObserver observer, final int userId) {
14621        mContext.enforceCallingOrSelfPermission(
14622                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14624        // Queue up an async operation since the package deletion may take a little while.
14625        mHandler.post(new Runnable() {
14626            public void run() {
14627                mHandler.removeCallbacks(this);
14628                final boolean succeeded;
14629                synchronized (mInstallLock) {
14630                    succeeded = clearApplicationUserDataLI(packageName, userId);
14631                }
14632                clearExternalStorageDataSync(packageName, userId, true);
14633                if (succeeded) {
14634                    // invoke DeviceStorageMonitor's update method to clear any notifications
14635                    DeviceStorageMonitorInternal
14636                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14637                    if (dsm != null) {
14638                        dsm.checkMemory();
14639                    }
14640                }
14641                if(observer != null) {
14642                    try {
14643                        observer.onRemoveCompleted(packageName, succeeded);
14644                    } catch (RemoteException e) {
14645                        Log.i(TAG, "Observer no longer exists.");
14646                    }
14647                } //end if observer
14648            } //end run
14649        });
14650    }
14651
14652    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14653        if (packageName == null) {
14654            Slog.w(TAG, "Attempt to delete null packageName.");
14655            return false;
14656        }
14657
14658        // Try finding details about the requested package
14659        PackageParser.Package pkg;
14660        synchronized (mPackages) {
14661            pkg = mPackages.get(packageName);
14662            if (pkg == null) {
14663                final PackageSetting ps = mSettings.mPackages.get(packageName);
14664                if (ps != null) {
14665                    pkg = ps.pkg;
14666                }
14667            }
14668
14669            if (pkg == null) {
14670                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14671                return false;
14672            }
14673
14674            PackageSetting ps = (PackageSetting) pkg.mExtras;
14675            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14676        }
14677
14678        // Always delete data directories for package, even if we found no other
14679        // record of app. This helps users recover from UID mismatches without
14680        // resorting to a full data wipe.
14681        // TODO: triage flags as part of 26466827
14682        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14683        try {
14684            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14685        } catch (InstallerException e) {
14686            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14687            return false;
14688        }
14689
14690        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14691        removeKeystoreDataIfNeeded(userId, appId);
14692
14693        // Create a native library symlink only if we have native libraries
14694        // and if the native libraries are 32 bit libraries. We do not provide
14695        // this symlink for 64 bit libraries.
14696        if (pkg.applicationInfo.primaryCpuAbi != null &&
14697                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14698            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14699            try {
14700                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14701                        nativeLibPath, userId);
14702            } catch (InstallerException e) {
14703                Slog.w(TAG, "Failed linking native library dir", e);
14704                return false;
14705            }
14706        }
14707
14708        return true;
14709    }
14710
14711    /**
14712     * Reverts user permission state changes (permissions and flags) in
14713     * all packages for a given user.
14714     *
14715     * @param userId The device user for which to do a reset.
14716     */
14717    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14718        final int packageCount = mPackages.size();
14719        for (int i = 0; i < packageCount; i++) {
14720            PackageParser.Package pkg = mPackages.valueAt(i);
14721            PackageSetting ps = (PackageSetting) pkg.mExtras;
14722            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14723        }
14724    }
14725
14726    /**
14727     * Reverts user permission state changes (permissions and flags).
14728     *
14729     * @param ps The package for which to reset.
14730     * @param userId The device user for which to do a reset.
14731     */
14732    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14733            final PackageSetting ps, final int userId) {
14734        if (ps.pkg == null) {
14735            return;
14736        }
14737
14738        // These are flags that can change base on user actions.
14739        final int userSettableMask = FLAG_PERMISSION_USER_SET
14740                | FLAG_PERMISSION_USER_FIXED
14741                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14742                | FLAG_PERMISSION_REVIEW_REQUIRED;
14743
14744        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14745                | FLAG_PERMISSION_POLICY_FIXED;
14746
14747        boolean writeInstallPermissions = false;
14748        boolean writeRuntimePermissions = false;
14749
14750        final int permissionCount = ps.pkg.requestedPermissions.size();
14751        for (int i = 0; i < permissionCount; i++) {
14752            String permission = ps.pkg.requestedPermissions.get(i);
14753
14754            BasePermission bp = mSettings.mPermissions.get(permission);
14755            if (bp == null) {
14756                continue;
14757            }
14758
14759            // If shared user we just reset the state to which only this app contributed.
14760            if (ps.sharedUser != null) {
14761                boolean used = false;
14762                final int packageCount = ps.sharedUser.packages.size();
14763                for (int j = 0; j < packageCount; j++) {
14764                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14765                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14766                            && pkg.pkg.requestedPermissions.contains(permission)) {
14767                        used = true;
14768                        break;
14769                    }
14770                }
14771                if (used) {
14772                    continue;
14773                }
14774            }
14775
14776            PermissionsState permissionsState = ps.getPermissionsState();
14777
14778            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14779
14780            // Always clear the user settable flags.
14781            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14782                    bp.name) != null;
14783            // If permission review is enabled and this is a legacy app, mark the
14784            // permission as requiring a review as this is the initial state.
14785            int flags = 0;
14786            if (Build.PERMISSIONS_REVIEW_REQUIRED
14787                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14788                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14789            }
14790            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14791                if (hasInstallState) {
14792                    writeInstallPermissions = true;
14793                } else {
14794                    writeRuntimePermissions = true;
14795                }
14796            }
14797
14798            // Below is only runtime permission handling.
14799            if (!bp.isRuntime()) {
14800                continue;
14801            }
14802
14803            // Never clobber system or policy.
14804            if ((oldFlags & policyOrSystemFlags) != 0) {
14805                continue;
14806            }
14807
14808            // If this permission was granted by default, make sure it is.
14809            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14810                if (permissionsState.grantRuntimePermission(bp, userId)
14811                        != PERMISSION_OPERATION_FAILURE) {
14812                    writeRuntimePermissions = true;
14813                }
14814            // If permission review is enabled the permissions for a legacy apps
14815            // are represented as constantly granted runtime ones, so don't revoke.
14816            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14817                // Otherwise, reset the permission.
14818                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14819                switch (revokeResult) {
14820                    case PERMISSION_OPERATION_SUCCESS: {
14821                        writeRuntimePermissions = true;
14822                    } break;
14823
14824                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14825                        writeRuntimePermissions = true;
14826                        final int appId = ps.appId;
14827                        mHandler.post(new Runnable() {
14828                            @Override
14829                            public void run() {
14830                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14831                            }
14832                        });
14833                    } break;
14834                }
14835            }
14836        }
14837
14838        // Synchronously write as we are taking permissions away.
14839        if (writeRuntimePermissions) {
14840            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14841        }
14842
14843        // Synchronously write as we are taking permissions away.
14844        if (writeInstallPermissions) {
14845            mSettings.writeLPr();
14846        }
14847    }
14848
14849    /**
14850     * Remove entries from the keystore daemon. Will only remove it if the
14851     * {@code appId} is valid.
14852     */
14853    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14854        if (appId < 0) {
14855            return;
14856        }
14857
14858        final KeyStore keyStore = KeyStore.getInstance();
14859        if (keyStore != null) {
14860            if (userId == UserHandle.USER_ALL) {
14861                for (final int individual : sUserManager.getUserIds()) {
14862                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14863                }
14864            } else {
14865                keyStore.clearUid(UserHandle.getUid(userId, appId));
14866            }
14867        } else {
14868            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14869        }
14870    }
14871
14872    @Override
14873    public void deleteApplicationCacheFiles(final String packageName,
14874            final IPackageDataObserver observer) {
14875        mContext.enforceCallingOrSelfPermission(
14876                android.Manifest.permission.DELETE_CACHE_FILES, null);
14877        // Queue up an async operation since the package deletion may take a little while.
14878        final int userId = UserHandle.getCallingUserId();
14879        mHandler.post(new Runnable() {
14880            public void run() {
14881                mHandler.removeCallbacks(this);
14882                final boolean succeded;
14883                synchronized (mInstallLock) {
14884                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14885                }
14886                clearExternalStorageDataSync(packageName, userId, false);
14887                if (observer != null) {
14888                    try {
14889                        observer.onRemoveCompleted(packageName, succeded);
14890                    } catch (RemoteException e) {
14891                        Log.i(TAG, "Observer no longer exists.");
14892                    }
14893                } //end if observer
14894            } //end run
14895        });
14896    }
14897
14898    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14899        if (packageName == null) {
14900            Slog.w(TAG, "Attempt to delete null packageName.");
14901            return false;
14902        }
14903        PackageParser.Package p;
14904        synchronized (mPackages) {
14905            p = mPackages.get(packageName);
14906        }
14907        if (p == null) {
14908            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14909            return false;
14910        }
14911        final ApplicationInfo applicationInfo = p.applicationInfo;
14912        if (applicationInfo == null) {
14913            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14914            return false;
14915        }
14916        // TODO: triage flags as part of 26466827
14917        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14918        try {
14919            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14920                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14921        } catch (InstallerException e) {
14922            Slog.w(TAG, "Couldn't remove cache files for package "
14923                    + packageName + " u" + userId, e);
14924            return false;
14925        }
14926        return true;
14927    }
14928
14929    @Override
14930    public void getPackageSizeInfo(final String packageName, int userHandle,
14931            final IPackageStatsObserver observer) {
14932        mContext.enforceCallingOrSelfPermission(
14933                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14934        if (packageName == null) {
14935            throw new IllegalArgumentException("Attempt to get size of null packageName");
14936        }
14937
14938        PackageStats stats = new PackageStats(packageName, userHandle);
14939
14940        /*
14941         * Queue up an async operation since the package measurement may take a
14942         * little while.
14943         */
14944        Message msg = mHandler.obtainMessage(INIT_COPY);
14945        msg.obj = new MeasureParams(stats, observer);
14946        mHandler.sendMessage(msg);
14947    }
14948
14949    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14950            PackageStats pStats) {
14951        if (packageName == null) {
14952            Slog.w(TAG, "Attempt to get size of null packageName.");
14953            return false;
14954        }
14955        PackageParser.Package p;
14956        boolean dataOnly = false;
14957        String libDirRoot = null;
14958        String asecPath = null;
14959        PackageSetting ps = null;
14960        synchronized (mPackages) {
14961            p = mPackages.get(packageName);
14962            ps = mSettings.mPackages.get(packageName);
14963            if(p == null) {
14964                dataOnly = true;
14965                if((ps == null) || (ps.pkg == null)) {
14966                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14967                    return false;
14968                }
14969                p = ps.pkg;
14970            }
14971            if (ps != null) {
14972                libDirRoot = ps.legacyNativeLibraryPathString;
14973            }
14974            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14975                final long token = Binder.clearCallingIdentity();
14976                try {
14977                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14978                    if (secureContainerId != null) {
14979                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14980                    }
14981                } finally {
14982                    Binder.restoreCallingIdentity(token);
14983                }
14984            }
14985        }
14986        String publicSrcDir = null;
14987        if(!dataOnly) {
14988            final ApplicationInfo applicationInfo = p.applicationInfo;
14989            if (applicationInfo == null) {
14990                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14991                return false;
14992            }
14993            if (p.isForwardLocked()) {
14994                publicSrcDir = applicationInfo.getBaseResourcePath();
14995            }
14996        }
14997        // TODO: extend to measure size of split APKs
14998        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14999        // not just the first level.
15000        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15001        // just the primary.
15002        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15003
15004        String apkPath;
15005        File packageDir = new File(p.codePath);
15006
15007        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15008            apkPath = packageDir.getAbsolutePath();
15009            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15010            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15011                libDirRoot = null;
15012            }
15013        } else {
15014            apkPath = p.baseCodePath;
15015        }
15016
15017        // TODO: triage flags as part of 26466827
15018        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15019        try {
15020            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15021                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15022        } catch (InstallerException e) {
15023            return false;
15024        }
15025
15026        // Fix-up for forward-locked applications in ASEC containers.
15027        if (!isExternal(p)) {
15028            pStats.codeSize += pStats.externalCodeSize;
15029            pStats.externalCodeSize = 0L;
15030        }
15031
15032        return true;
15033    }
15034
15035
15036    @Override
15037    public void addPackageToPreferred(String packageName) {
15038        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15039    }
15040
15041    @Override
15042    public void removePackageFromPreferred(String packageName) {
15043        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15044    }
15045
15046    @Override
15047    public List<PackageInfo> getPreferredPackages(int flags) {
15048        return new ArrayList<PackageInfo>();
15049    }
15050
15051    private int getUidTargetSdkVersionLockedLPr(int uid) {
15052        Object obj = mSettings.getUserIdLPr(uid);
15053        if (obj instanceof SharedUserSetting) {
15054            final SharedUserSetting sus = (SharedUserSetting) obj;
15055            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15056            final Iterator<PackageSetting> it = sus.packages.iterator();
15057            while (it.hasNext()) {
15058                final PackageSetting ps = it.next();
15059                if (ps.pkg != null) {
15060                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15061                    if (v < vers) vers = v;
15062                }
15063            }
15064            return vers;
15065        } else if (obj instanceof PackageSetting) {
15066            final PackageSetting ps = (PackageSetting) obj;
15067            if (ps.pkg != null) {
15068                return ps.pkg.applicationInfo.targetSdkVersion;
15069            }
15070        }
15071        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15072    }
15073
15074    @Override
15075    public void addPreferredActivity(IntentFilter filter, int match,
15076            ComponentName[] set, ComponentName activity, int userId) {
15077        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15078                "Adding preferred");
15079    }
15080
15081    private void addPreferredActivityInternal(IntentFilter filter, int match,
15082            ComponentName[] set, ComponentName activity, boolean always, int userId,
15083            String opname) {
15084        // writer
15085        int callingUid = Binder.getCallingUid();
15086        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15087        if (filter.countActions() == 0) {
15088            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15089            return;
15090        }
15091        synchronized (mPackages) {
15092            if (mContext.checkCallingOrSelfPermission(
15093                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15094                    != PackageManager.PERMISSION_GRANTED) {
15095                if (getUidTargetSdkVersionLockedLPr(callingUid)
15096                        < Build.VERSION_CODES.FROYO) {
15097                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15098                            + callingUid);
15099                    return;
15100                }
15101                mContext.enforceCallingOrSelfPermission(
15102                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15103            }
15104
15105            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15106            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15107                    + userId + ":");
15108            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15109            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15110            scheduleWritePackageRestrictionsLocked(userId);
15111        }
15112    }
15113
15114    @Override
15115    public void replacePreferredActivity(IntentFilter filter, int match,
15116            ComponentName[] set, ComponentName activity, int userId) {
15117        if (filter.countActions() != 1) {
15118            throw new IllegalArgumentException(
15119                    "replacePreferredActivity expects filter to have only 1 action.");
15120        }
15121        if (filter.countDataAuthorities() != 0
15122                || filter.countDataPaths() != 0
15123                || filter.countDataSchemes() > 1
15124                || filter.countDataTypes() != 0) {
15125            throw new IllegalArgumentException(
15126                    "replacePreferredActivity expects filter to have no data authorities, " +
15127                    "paths, or types; and at most one scheme.");
15128        }
15129
15130        final int callingUid = Binder.getCallingUid();
15131        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15132        synchronized (mPackages) {
15133            if (mContext.checkCallingOrSelfPermission(
15134                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15135                    != PackageManager.PERMISSION_GRANTED) {
15136                if (getUidTargetSdkVersionLockedLPr(callingUid)
15137                        < Build.VERSION_CODES.FROYO) {
15138                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15139                            + Binder.getCallingUid());
15140                    return;
15141                }
15142                mContext.enforceCallingOrSelfPermission(
15143                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15144            }
15145
15146            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15147            if (pir != null) {
15148                // Get all of the existing entries that exactly match this filter.
15149                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15150                if (existing != null && existing.size() == 1) {
15151                    PreferredActivity cur = existing.get(0);
15152                    if (DEBUG_PREFERRED) {
15153                        Slog.i(TAG, "Checking replace of preferred:");
15154                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15155                        if (!cur.mPref.mAlways) {
15156                            Slog.i(TAG, "  -- CUR; not mAlways!");
15157                        } else {
15158                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15159                            Slog.i(TAG, "  -- CUR: mSet="
15160                                    + Arrays.toString(cur.mPref.mSetComponents));
15161                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15162                            Slog.i(TAG, "  -- NEW: mMatch="
15163                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15164                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15165                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15166                        }
15167                    }
15168                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15169                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15170                            && cur.mPref.sameSet(set)) {
15171                        // Setting the preferred activity to what it happens to be already
15172                        if (DEBUG_PREFERRED) {
15173                            Slog.i(TAG, "Replacing with same preferred activity "
15174                                    + cur.mPref.mShortComponent + " for user "
15175                                    + userId + ":");
15176                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15177                        }
15178                        return;
15179                    }
15180                }
15181
15182                if (existing != null) {
15183                    if (DEBUG_PREFERRED) {
15184                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15185                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15186                    }
15187                    for (int i = 0; i < existing.size(); i++) {
15188                        PreferredActivity pa = existing.get(i);
15189                        if (DEBUG_PREFERRED) {
15190                            Slog.i(TAG, "Removing existing preferred activity "
15191                                    + pa.mPref.mComponent + ":");
15192                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15193                        }
15194                        pir.removeFilter(pa);
15195                    }
15196                }
15197            }
15198            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15199                    "Replacing preferred");
15200        }
15201    }
15202
15203    @Override
15204    public void clearPackagePreferredActivities(String packageName) {
15205        final int uid = Binder.getCallingUid();
15206        // writer
15207        synchronized (mPackages) {
15208            PackageParser.Package pkg = mPackages.get(packageName);
15209            if (pkg == null || pkg.applicationInfo.uid != uid) {
15210                if (mContext.checkCallingOrSelfPermission(
15211                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15212                        != PackageManager.PERMISSION_GRANTED) {
15213                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15214                            < Build.VERSION_CODES.FROYO) {
15215                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15216                                + Binder.getCallingUid());
15217                        return;
15218                    }
15219                    mContext.enforceCallingOrSelfPermission(
15220                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15221                }
15222            }
15223
15224            int user = UserHandle.getCallingUserId();
15225            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15226                scheduleWritePackageRestrictionsLocked(user);
15227            }
15228        }
15229    }
15230
15231    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15232    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15233        ArrayList<PreferredActivity> removed = null;
15234        boolean changed = false;
15235        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15236            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15237            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15238            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15239                continue;
15240            }
15241            Iterator<PreferredActivity> it = pir.filterIterator();
15242            while (it.hasNext()) {
15243                PreferredActivity pa = it.next();
15244                // Mark entry for removal only if it matches the package name
15245                // and the entry is of type "always".
15246                if (packageName == null ||
15247                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15248                                && pa.mPref.mAlways)) {
15249                    if (removed == null) {
15250                        removed = new ArrayList<PreferredActivity>();
15251                    }
15252                    removed.add(pa);
15253                }
15254            }
15255            if (removed != null) {
15256                for (int j=0; j<removed.size(); j++) {
15257                    PreferredActivity pa = removed.get(j);
15258                    pir.removeFilter(pa);
15259                }
15260                changed = true;
15261            }
15262        }
15263        return changed;
15264    }
15265
15266    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15267    private void clearIntentFilterVerificationsLPw(int userId) {
15268        final int packageCount = mPackages.size();
15269        for (int i = 0; i < packageCount; i++) {
15270            PackageParser.Package pkg = mPackages.valueAt(i);
15271            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15272        }
15273    }
15274
15275    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15276    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15277        if (userId == UserHandle.USER_ALL) {
15278            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15279                    sUserManager.getUserIds())) {
15280                for (int oneUserId : sUserManager.getUserIds()) {
15281                    scheduleWritePackageRestrictionsLocked(oneUserId);
15282                }
15283            }
15284        } else {
15285            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15286                scheduleWritePackageRestrictionsLocked(userId);
15287            }
15288        }
15289    }
15290
15291    void clearDefaultBrowserIfNeeded(String packageName) {
15292        for (int oneUserId : sUserManager.getUserIds()) {
15293            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15294            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15295            if (packageName.equals(defaultBrowserPackageName)) {
15296                setDefaultBrowserPackageName(null, oneUserId);
15297            }
15298        }
15299    }
15300
15301    @Override
15302    public void resetApplicationPreferences(int userId) {
15303        mContext.enforceCallingOrSelfPermission(
15304                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15305        // writer
15306        synchronized (mPackages) {
15307            final long identity = Binder.clearCallingIdentity();
15308            try {
15309                clearPackagePreferredActivitiesLPw(null, userId);
15310                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15311                // TODO: We have to reset the default SMS and Phone. This requires
15312                // significant refactoring to keep all default apps in the package
15313                // manager (cleaner but more work) or have the services provide
15314                // callbacks to the package manager to request a default app reset.
15315                applyFactoryDefaultBrowserLPw(userId);
15316                clearIntentFilterVerificationsLPw(userId);
15317                primeDomainVerificationsLPw(userId);
15318                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15319                scheduleWritePackageRestrictionsLocked(userId);
15320            } finally {
15321                Binder.restoreCallingIdentity(identity);
15322            }
15323        }
15324    }
15325
15326    @Override
15327    public int getPreferredActivities(List<IntentFilter> outFilters,
15328            List<ComponentName> outActivities, String packageName) {
15329
15330        int num = 0;
15331        final int userId = UserHandle.getCallingUserId();
15332        // reader
15333        synchronized (mPackages) {
15334            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15335            if (pir != null) {
15336                final Iterator<PreferredActivity> it = pir.filterIterator();
15337                while (it.hasNext()) {
15338                    final PreferredActivity pa = it.next();
15339                    if (packageName == null
15340                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15341                                    && pa.mPref.mAlways)) {
15342                        if (outFilters != null) {
15343                            outFilters.add(new IntentFilter(pa));
15344                        }
15345                        if (outActivities != null) {
15346                            outActivities.add(pa.mPref.mComponent);
15347                        }
15348                    }
15349                }
15350            }
15351        }
15352
15353        return num;
15354    }
15355
15356    @Override
15357    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15358            int userId) {
15359        int callingUid = Binder.getCallingUid();
15360        if (callingUid != Process.SYSTEM_UID) {
15361            throw new SecurityException(
15362                    "addPersistentPreferredActivity can only be run by the system");
15363        }
15364        if (filter.countActions() == 0) {
15365            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15366            return;
15367        }
15368        synchronized (mPackages) {
15369            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15370                    ":");
15371            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15372            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15373                    new PersistentPreferredActivity(filter, activity));
15374            scheduleWritePackageRestrictionsLocked(userId);
15375        }
15376    }
15377
15378    @Override
15379    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15380        int callingUid = Binder.getCallingUid();
15381        if (callingUid != Process.SYSTEM_UID) {
15382            throw new SecurityException(
15383                    "clearPackagePersistentPreferredActivities can only be run by the system");
15384        }
15385        ArrayList<PersistentPreferredActivity> removed = null;
15386        boolean changed = false;
15387        synchronized (mPackages) {
15388            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15389                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15390                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15391                        .valueAt(i);
15392                if (userId != thisUserId) {
15393                    continue;
15394                }
15395                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15396                while (it.hasNext()) {
15397                    PersistentPreferredActivity ppa = it.next();
15398                    // Mark entry for removal only if it matches the package name.
15399                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15400                        if (removed == null) {
15401                            removed = new ArrayList<PersistentPreferredActivity>();
15402                        }
15403                        removed.add(ppa);
15404                    }
15405                }
15406                if (removed != null) {
15407                    for (int j=0; j<removed.size(); j++) {
15408                        PersistentPreferredActivity ppa = removed.get(j);
15409                        ppir.removeFilter(ppa);
15410                    }
15411                    changed = true;
15412                }
15413            }
15414
15415            if (changed) {
15416                scheduleWritePackageRestrictionsLocked(userId);
15417            }
15418        }
15419    }
15420
15421    /**
15422     * Common machinery for picking apart a restored XML blob and passing
15423     * it to a caller-supplied functor to be applied to the running system.
15424     */
15425    private void restoreFromXml(XmlPullParser parser, int userId,
15426            String expectedStartTag, BlobXmlRestorer functor)
15427            throws IOException, XmlPullParserException {
15428        int type;
15429        while ((type = parser.next()) != XmlPullParser.START_TAG
15430                && type != XmlPullParser.END_DOCUMENT) {
15431        }
15432        if (type != XmlPullParser.START_TAG) {
15433            // oops didn't find a start tag?!
15434            if (DEBUG_BACKUP) {
15435                Slog.e(TAG, "Didn't find start tag during restore");
15436            }
15437            return;
15438        }
15439Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15440        // this is supposed to be TAG_PREFERRED_BACKUP
15441        if (!expectedStartTag.equals(parser.getName())) {
15442            if (DEBUG_BACKUP) {
15443                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15444            }
15445            return;
15446        }
15447
15448        // skip interfering stuff, then we're aligned with the backing implementation
15449        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15450Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15451        functor.apply(parser, userId);
15452    }
15453
15454    private interface BlobXmlRestorer {
15455        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15456    }
15457
15458    /**
15459     * Non-Binder method, support for the backup/restore mechanism: write the
15460     * full set of preferred activities in its canonical XML format.  Returns the
15461     * XML output as a byte array, or null if there is none.
15462     */
15463    @Override
15464    public byte[] getPreferredActivityBackup(int userId) {
15465        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15466            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15467        }
15468
15469        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15470        try {
15471            final XmlSerializer serializer = new FastXmlSerializer();
15472            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15473            serializer.startDocument(null, true);
15474            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15475
15476            synchronized (mPackages) {
15477                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15478            }
15479
15480            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15481            serializer.endDocument();
15482            serializer.flush();
15483        } catch (Exception e) {
15484            if (DEBUG_BACKUP) {
15485                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15486            }
15487            return null;
15488        }
15489
15490        return dataStream.toByteArray();
15491    }
15492
15493    @Override
15494    public void restorePreferredActivities(byte[] backup, int userId) {
15495        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15496            throw new SecurityException("Only the system may call restorePreferredActivities()");
15497        }
15498
15499        try {
15500            final XmlPullParser parser = Xml.newPullParser();
15501            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15502            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15503                    new BlobXmlRestorer() {
15504                        @Override
15505                        public void apply(XmlPullParser parser, int userId)
15506                                throws XmlPullParserException, IOException {
15507                            synchronized (mPackages) {
15508                                mSettings.readPreferredActivitiesLPw(parser, userId);
15509                            }
15510                        }
15511                    } );
15512        } catch (Exception e) {
15513            if (DEBUG_BACKUP) {
15514                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15515            }
15516        }
15517    }
15518
15519    /**
15520     * Non-Binder method, support for the backup/restore mechanism: write the
15521     * default browser (etc) settings in its canonical XML format.  Returns the default
15522     * browser XML representation as a byte array, or null if there is none.
15523     */
15524    @Override
15525    public byte[] getDefaultAppsBackup(int userId) {
15526        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15527            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15528        }
15529
15530        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15531        try {
15532            final XmlSerializer serializer = new FastXmlSerializer();
15533            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15534            serializer.startDocument(null, true);
15535            serializer.startTag(null, TAG_DEFAULT_APPS);
15536
15537            synchronized (mPackages) {
15538                mSettings.writeDefaultAppsLPr(serializer, userId);
15539            }
15540
15541            serializer.endTag(null, TAG_DEFAULT_APPS);
15542            serializer.endDocument();
15543            serializer.flush();
15544        } catch (Exception e) {
15545            if (DEBUG_BACKUP) {
15546                Slog.e(TAG, "Unable to write default apps for backup", e);
15547            }
15548            return null;
15549        }
15550
15551        return dataStream.toByteArray();
15552    }
15553
15554    @Override
15555    public void restoreDefaultApps(byte[] backup, int userId) {
15556        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15557            throw new SecurityException("Only the system may call restoreDefaultApps()");
15558        }
15559
15560        try {
15561            final XmlPullParser parser = Xml.newPullParser();
15562            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15563            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15564                    new BlobXmlRestorer() {
15565                        @Override
15566                        public void apply(XmlPullParser parser, int userId)
15567                                throws XmlPullParserException, IOException {
15568                            synchronized (mPackages) {
15569                                mSettings.readDefaultAppsLPw(parser, userId);
15570                            }
15571                        }
15572                    } );
15573        } catch (Exception e) {
15574            if (DEBUG_BACKUP) {
15575                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15576            }
15577        }
15578    }
15579
15580    @Override
15581    public byte[] getIntentFilterVerificationBackup(int userId) {
15582        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15583            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15584        }
15585
15586        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15587        try {
15588            final XmlSerializer serializer = new FastXmlSerializer();
15589            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15590            serializer.startDocument(null, true);
15591            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15592
15593            synchronized (mPackages) {
15594                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15595            }
15596
15597            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15598            serializer.endDocument();
15599            serializer.flush();
15600        } catch (Exception e) {
15601            if (DEBUG_BACKUP) {
15602                Slog.e(TAG, "Unable to write default apps for backup", e);
15603            }
15604            return null;
15605        }
15606
15607        return dataStream.toByteArray();
15608    }
15609
15610    @Override
15611    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15612        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15613            throw new SecurityException("Only the system may call restorePreferredActivities()");
15614        }
15615
15616        try {
15617            final XmlPullParser parser = Xml.newPullParser();
15618            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15619            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15620                    new BlobXmlRestorer() {
15621                        @Override
15622                        public void apply(XmlPullParser parser, int userId)
15623                                throws XmlPullParserException, IOException {
15624                            synchronized (mPackages) {
15625                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15626                                mSettings.writeLPr();
15627                            }
15628                        }
15629                    } );
15630        } catch (Exception e) {
15631            if (DEBUG_BACKUP) {
15632                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15633            }
15634        }
15635    }
15636
15637    @Override
15638    public byte[] getPermissionGrantBackup(int userId) {
15639        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15640            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15641        }
15642
15643        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15644        try {
15645            final XmlSerializer serializer = new FastXmlSerializer();
15646            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15647            serializer.startDocument(null, true);
15648            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15649
15650            synchronized (mPackages) {
15651                serializeRuntimePermissionGrantsLPr(serializer, userId);
15652            }
15653
15654            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15655            serializer.endDocument();
15656            serializer.flush();
15657        } catch (Exception e) {
15658            if (DEBUG_BACKUP) {
15659                Slog.e(TAG, "Unable to write default apps for backup", e);
15660            }
15661            return null;
15662        }
15663
15664        return dataStream.toByteArray();
15665    }
15666
15667    @Override
15668    public void restorePermissionGrants(byte[] backup, int userId) {
15669        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15670            throw new SecurityException("Only the system may call restorePermissionGrants()");
15671        }
15672
15673        try {
15674            final XmlPullParser parser = Xml.newPullParser();
15675            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15676            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15677                    new BlobXmlRestorer() {
15678                        @Override
15679                        public void apply(XmlPullParser parser, int userId)
15680                                throws XmlPullParserException, IOException {
15681                            synchronized (mPackages) {
15682                                processRestoredPermissionGrantsLPr(parser, userId);
15683                            }
15684                        }
15685                    } );
15686        } catch (Exception e) {
15687            if (DEBUG_BACKUP) {
15688                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15689            }
15690        }
15691    }
15692
15693    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15694            throws IOException {
15695        serializer.startTag(null, TAG_ALL_GRANTS);
15696
15697        final int N = mSettings.mPackages.size();
15698        for (int i = 0; i < N; i++) {
15699            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15700            boolean pkgGrantsKnown = false;
15701
15702            PermissionsState packagePerms = ps.getPermissionsState();
15703
15704            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15705                final int grantFlags = state.getFlags();
15706                // only look at grants that are not system/policy fixed
15707                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15708                    final boolean isGranted = state.isGranted();
15709                    // And only back up the user-twiddled state bits
15710                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15711                        final String packageName = mSettings.mPackages.keyAt(i);
15712                        if (!pkgGrantsKnown) {
15713                            serializer.startTag(null, TAG_GRANT);
15714                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15715                            pkgGrantsKnown = true;
15716                        }
15717
15718                        final boolean userSet =
15719                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15720                        final boolean userFixed =
15721                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15722                        final boolean revoke =
15723                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15724
15725                        serializer.startTag(null, TAG_PERMISSION);
15726                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15727                        if (isGranted) {
15728                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15729                        }
15730                        if (userSet) {
15731                            serializer.attribute(null, ATTR_USER_SET, "true");
15732                        }
15733                        if (userFixed) {
15734                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15735                        }
15736                        if (revoke) {
15737                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15738                        }
15739                        serializer.endTag(null, TAG_PERMISSION);
15740                    }
15741                }
15742            }
15743
15744            if (pkgGrantsKnown) {
15745                serializer.endTag(null, TAG_GRANT);
15746            }
15747        }
15748
15749        serializer.endTag(null, TAG_ALL_GRANTS);
15750    }
15751
15752    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15753            throws XmlPullParserException, IOException {
15754        String pkgName = null;
15755        int outerDepth = parser.getDepth();
15756        int type;
15757        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15758                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15759            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15760                continue;
15761            }
15762
15763            final String tagName = parser.getName();
15764            if (tagName.equals(TAG_GRANT)) {
15765                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15766                if (DEBUG_BACKUP) {
15767                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15768                }
15769            } else if (tagName.equals(TAG_PERMISSION)) {
15770
15771                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15772                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15773
15774                int newFlagSet = 0;
15775                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15776                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15777                }
15778                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15779                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15780                }
15781                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15782                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15783                }
15784                if (DEBUG_BACKUP) {
15785                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15786                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15787                }
15788                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15789                if (ps != null) {
15790                    // Already installed so we apply the grant immediately
15791                    if (DEBUG_BACKUP) {
15792                        Slog.v(TAG, "        + already installed; applying");
15793                    }
15794                    PermissionsState perms = ps.getPermissionsState();
15795                    BasePermission bp = mSettings.mPermissions.get(permName);
15796                    if (bp != null) {
15797                        if (isGranted) {
15798                            perms.grantRuntimePermission(bp, userId);
15799                        }
15800                        if (newFlagSet != 0) {
15801                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15802                        }
15803                    }
15804                } else {
15805                    // Need to wait for post-restore install to apply the grant
15806                    if (DEBUG_BACKUP) {
15807                        Slog.v(TAG, "        - not yet installed; saving for later");
15808                    }
15809                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15810                            isGranted, newFlagSet, userId);
15811                }
15812            } else {
15813                PackageManagerService.reportSettingsProblem(Log.WARN,
15814                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15815                XmlUtils.skipCurrentTag(parser);
15816            }
15817        }
15818
15819        scheduleWriteSettingsLocked();
15820        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15821    }
15822
15823    @Override
15824    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15825            int sourceUserId, int targetUserId, int flags) {
15826        mContext.enforceCallingOrSelfPermission(
15827                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15828        int callingUid = Binder.getCallingUid();
15829        enforceOwnerRights(ownerPackage, callingUid);
15830        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15831        if (intentFilter.countActions() == 0) {
15832            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15833            return;
15834        }
15835        synchronized (mPackages) {
15836            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15837                    ownerPackage, targetUserId, flags);
15838            CrossProfileIntentResolver resolver =
15839                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15840            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15841            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15842            if (existing != null) {
15843                int size = existing.size();
15844                for (int i = 0; i < size; i++) {
15845                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15846                        return;
15847                    }
15848                }
15849            }
15850            resolver.addFilter(newFilter);
15851            scheduleWritePackageRestrictionsLocked(sourceUserId);
15852        }
15853    }
15854
15855    @Override
15856    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15857        mContext.enforceCallingOrSelfPermission(
15858                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15859        int callingUid = Binder.getCallingUid();
15860        enforceOwnerRights(ownerPackage, callingUid);
15861        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15862        synchronized (mPackages) {
15863            CrossProfileIntentResolver resolver =
15864                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15865            ArraySet<CrossProfileIntentFilter> set =
15866                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15867            for (CrossProfileIntentFilter filter : set) {
15868                if (filter.getOwnerPackage().equals(ownerPackage)) {
15869                    resolver.removeFilter(filter);
15870                }
15871            }
15872            scheduleWritePackageRestrictionsLocked(sourceUserId);
15873        }
15874    }
15875
15876    // Enforcing that callingUid is owning pkg on userId
15877    private void enforceOwnerRights(String pkg, int callingUid) {
15878        // The system owns everything.
15879        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15880            return;
15881        }
15882        int callingUserId = UserHandle.getUserId(callingUid);
15883        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15884        if (pi == null) {
15885            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15886                    + callingUserId);
15887        }
15888        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15889            throw new SecurityException("Calling uid " + callingUid
15890                    + " does not own package " + pkg);
15891        }
15892    }
15893
15894    @Override
15895    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15896        Intent intent = new Intent(Intent.ACTION_MAIN);
15897        intent.addCategory(Intent.CATEGORY_HOME);
15898
15899        final int callingUserId = UserHandle.getCallingUserId();
15900        List<ResolveInfo> list = queryIntentActivities(intent, null,
15901                PackageManager.GET_META_DATA, callingUserId);
15902        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15903                true, false, false, callingUserId);
15904
15905        allHomeCandidates.clear();
15906        if (list != null) {
15907            for (ResolveInfo ri : list) {
15908                allHomeCandidates.add(ri);
15909            }
15910        }
15911        return (preferred == null || preferred.activityInfo == null)
15912                ? null
15913                : new ComponentName(preferred.activityInfo.packageName,
15914                        preferred.activityInfo.name);
15915    }
15916
15917    @Override
15918    public void setApplicationEnabledSetting(String appPackageName,
15919            int newState, int flags, int userId, String callingPackage) {
15920        if (!sUserManager.exists(userId)) return;
15921        if (callingPackage == null) {
15922            callingPackage = Integer.toString(Binder.getCallingUid());
15923        }
15924        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15925    }
15926
15927    @Override
15928    public void setComponentEnabledSetting(ComponentName componentName,
15929            int newState, int flags, int userId) {
15930        if (!sUserManager.exists(userId)) return;
15931        setEnabledSetting(componentName.getPackageName(),
15932                componentName.getClassName(), newState, flags, userId, null);
15933    }
15934
15935    private void setEnabledSetting(final String packageName, String className, int newState,
15936            final int flags, int userId, String callingPackage) {
15937        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15938              || newState == COMPONENT_ENABLED_STATE_ENABLED
15939              || newState == COMPONENT_ENABLED_STATE_DISABLED
15940              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15941              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15942            throw new IllegalArgumentException("Invalid new component state: "
15943                    + newState);
15944        }
15945        PackageSetting pkgSetting;
15946        final int uid = Binder.getCallingUid();
15947        final int permission = mContext.checkCallingOrSelfPermission(
15948                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15949        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15950        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15951        boolean sendNow = false;
15952        boolean isApp = (className == null);
15953        String componentName = isApp ? packageName : className;
15954        int packageUid = -1;
15955        ArrayList<String> components;
15956
15957        // writer
15958        synchronized (mPackages) {
15959            pkgSetting = mSettings.mPackages.get(packageName);
15960            if (pkgSetting == null) {
15961                if (className == null) {
15962                    throw new IllegalArgumentException("Unknown package: " + packageName);
15963                }
15964                throw new IllegalArgumentException(
15965                        "Unknown component: " + packageName + "/" + className);
15966            }
15967            // Allow root and verify that userId is not being specified by a different user
15968            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15969                throw new SecurityException(
15970                        "Permission Denial: attempt to change component state from pid="
15971                        + Binder.getCallingPid()
15972                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15973            }
15974            if (className == null) {
15975                // We're dealing with an application/package level state change
15976                if (pkgSetting.getEnabled(userId) == newState) {
15977                    // Nothing to do
15978                    return;
15979                }
15980                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15981                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15982                    // Don't care about who enables an app.
15983                    callingPackage = null;
15984                }
15985                pkgSetting.setEnabled(newState, userId, callingPackage);
15986                // pkgSetting.pkg.mSetEnabled = newState;
15987            } else {
15988                // We're dealing with a component level state change
15989                // First, verify that this is a valid class name.
15990                PackageParser.Package pkg = pkgSetting.pkg;
15991                if (pkg == null || !pkg.hasComponentClassName(className)) {
15992                    if (pkg != null &&
15993                            pkg.applicationInfo.targetSdkVersion >=
15994                                    Build.VERSION_CODES.JELLY_BEAN) {
15995                        throw new IllegalArgumentException("Component class " + className
15996                                + " does not exist in " + packageName);
15997                    } else {
15998                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15999                                + className + " does not exist in " + packageName);
16000                    }
16001                }
16002                switch (newState) {
16003                case COMPONENT_ENABLED_STATE_ENABLED:
16004                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16005                        return;
16006                    }
16007                    break;
16008                case COMPONENT_ENABLED_STATE_DISABLED:
16009                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16010                        return;
16011                    }
16012                    break;
16013                case COMPONENT_ENABLED_STATE_DEFAULT:
16014                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16015                        return;
16016                    }
16017                    break;
16018                default:
16019                    Slog.e(TAG, "Invalid new component state: " + newState);
16020                    return;
16021                }
16022            }
16023            scheduleWritePackageRestrictionsLocked(userId);
16024            components = mPendingBroadcasts.get(userId, packageName);
16025            final boolean newPackage = components == null;
16026            if (newPackage) {
16027                components = new ArrayList<String>();
16028            }
16029            if (!components.contains(componentName)) {
16030                components.add(componentName);
16031            }
16032            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16033                sendNow = true;
16034                // Purge entry from pending broadcast list if another one exists already
16035                // since we are sending one right away.
16036                mPendingBroadcasts.remove(userId, packageName);
16037            } else {
16038                if (newPackage) {
16039                    mPendingBroadcasts.put(userId, packageName, components);
16040                }
16041                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16042                    // Schedule a message
16043                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16044                }
16045            }
16046        }
16047
16048        long callingId = Binder.clearCallingIdentity();
16049        try {
16050            if (sendNow) {
16051                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16052                sendPackageChangedBroadcast(packageName,
16053                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16054            }
16055        } finally {
16056            Binder.restoreCallingIdentity(callingId);
16057        }
16058    }
16059
16060    private void sendPackageChangedBroadcast(String packageName,
16061            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16062        if (DEBUG_INSTALL)
16063            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16064                    + componentNames);
16065        Bundle extras = new Bundle(4);
16066        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16067        String nameList[] = new String[componentNames.size()];
16068        componentNames.toArray(nameList);
16069        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16070        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16071        extras.putInt(Intent.EXTRA_UID, packageUid);
16072        // If this is not reporting a change of the overall package, then only send it
16073        // to registered receivers.  We don't want to launch a swath of apps for every
16074        // little component state change.
16075        final int flags = !componentNames.contains(packageName)
16076                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16077        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16078                new int[] {UserHandle.getUserId(packageUid)});
16079    }
16080
16081    @Override
16082    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16083        if (!sUserManager.exists(userId)) return;
16084        final int uid = Binder.getCallingUid();
16085        final int permission = mContext.checkCallingOrSelfPermission(
16086                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16087        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16088        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16089        // writer
16090        synchronized (mPackages) {
16091            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16092                    allowedByPermission, uid, userId)) {
16093                scheduleWritePackageRestrictionsLocked(userId);
16094            }
16095        }
16096    }
16097
16098    @Override
16099    public String getInstallerPackageName(String packageName) {
16100        // reader
16101        synchronized (mPackages) {
16102            return mSettings.getInstallerPackageNameLPr(packageName);
16103        }
16104    }
16105
16106    @Override
16107    public int getApplicationEnabledSetting(String packageName, int userId) {
16108        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16109        int uid = Binder.getCallingUid();
16110        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16111        // reader
16112        synchronized (mPackages) {
16113            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16114        }
16115    }
16116
16117    @Override
16118    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16119        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16120        int uid = Binder.getCallingUid();
16121        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16122        // reader
16123        synchronized (mPackages) {
16124            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16125        }
16126    }
16127
16128    @Override
16129    public void enterSafeMode() {
16130        enforceSystemOrRoot("Only the system can request entering safe mode");
16131
16132        if (!mSystemReady) {
16133            mSafeMode = true;
16134        }
16135    }
16136
16137    @Override
16138    public void systemReady() {
16139        mSystemReady = true;
16140
16141        // Read the compatibilty setting when the system is ready.
16142        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16143                mContext.getContentResolver(),
16144                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16145        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16146        if (DEBUG_SETTINGS) {
16147            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16148        }
16149
16150        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16151
16152        synchronized (mPackages) {
16153            // Verify that all of the preferred activity components actually
16154            // exist.  It is possible for applications to be updated and at
16155            // that point remove a previously declared activity component that
16156            // had been set as a preferred activity.  We try to clean this up
16157            // the next time we encounter that preferred activity, but it is
16158            // possible for the user flow to never be able to return to that
16159            // situation so here we do a sanity check to make sure we haven't
16160            // left any junk around.
16161            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16162            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16163                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16164                removed.clear();
16165                for (PreferredActivity pa : pir.filterSet()) {
16166                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16167                        removed.add(pa);
16168                    }
16169                }
16170                if (removed.size() > 0) {
16171                    for (int r=0; r<removed.size(); r++) {
16172                        PreferredActivity pa = removed.get(r);
16173                        Slog.w(TAG, "Removing dangling preferred activity: "
16174                                + pa.mPref.mComponent);
16175                        pir.removeFilter(pa);
16176                    }
16177                    mSettings.writePackageRestrictionsLPr(
16178                            mSettings.mPreferredActivities.keyAt(i));
16179                }
16180            }
16181
16182            for (int userId : UserManagerService.getInstance().getUserIds()) {
16183                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16184                    grantPermissionsUserIds = ArrayUtils.appendInt(
16185                            grantPermissionsUserIds, userId);
16186                }
16187            }
16188        }
16189        sUserManager.systemReady();
16190
16191        // If we upgraded grant all default permissions before kicking off.
16192        for (int userId : grantPermissionsUserIds) {
16193            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16194        }
16195
16196        // Kick off any messages waiting for system ready
16197        if (mPostSystemReadyMessages != null) {
16198            for (Message msg : mPostSystemReadyMessages) {
16199                msg.sendToTarget();
16200            }
16201            mPostSystemReadyMessages = null;
16202        }
16203
16204        // Watch for external volumes that come and go over time
16205        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16206        storage.registerListener(mStorageListener);
16207
16208        mInstallerService.systemReady();
16209        mPackageDexOptimizer.systemReady();
16210
16211        MountServiceInternal mountServiceInternal = LocalServices.getService(
16212                MountServiceInternal.class);
16213        mountServiceInternal.addExternalStoragePolicy(
16214                new MountServiceInternal.ExternalStorageMountPolicy() {
16215            @Override
16216            public int getMountMode(int uid, String packageName) {
16217                if (Process.isIsolated(uid)) {
16218                    return Zygote.MOUNT_EXTERNAL_NONE;
16219                }
16220                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16221                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16222                }
16223                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16224                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16225                }
16226                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16227                    return Zygote.MOUNT_EXTERNAL_READ;
16228                }
16229                return Zygote.MOUNT_EXTERNAL_WRITE;
16230            }
16231
16232            @Override
16233            public boolean hasExternalStorage(int uid, String packageName) {
16234                return true;
16235            }
16236        });
16237    }
16238
16239    @Override
16240    public boolean isSafeMode() {
16241        return mSafeMode;
16242    }
16243
16244    @Override
16245    public boolean hasSystemUidErrors() {
16246        return mHasSystemUidErrors;
16247    }
16248
16249    static String arrayToString(int[] array) {
16250        StringBuffer buf = new StringBuffer(128);
16251        buf.append('[');
16252        if (array != null) {
16253            for (int i=0; i<array.length; i++) {
16254                if (i > 0) buf.append(", ");
16255                buf.append(array[i]);
16256            }
16257        }
16258        buf.append(']');
16259        return buf.toString();
16260    }
16261
16262    static class DumpState {
16263        public static final int DUMP_LIBS = 1 << 0;
16264        public static final int DUMP_FEATURES = 1 << 1;
16265        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16266        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16267        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16268        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16269        public static final int DUMP_PERMISSIONS = 1 << 6;
16270        public static final int DUMP_PACKAGES = 1 << 7;
16271        public static final int DUMP_SHARED_USERS = 1 << 8;
16272        public static final int DUMP_MESSAGES = 1 << 9;
16273        public static final int DUMP_PROVIDERS = 1 << 10;
16274        public static final int DUMP_VERIFIERS = 1 << 11;
16275        public static final int DUMP_PREFERRED = 1 << 12;
16276        public static final int DUMP_PREFERRED_XML = 1 << 13;
16277        public static final int DUMP_KEYSETS = 1 << 14;
16278        public static final int DUMP_VERSION = 1 << 15;
16279        public static final int DUMP_INSTALLS = 1 << 16;
16280        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16281        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16282
16283        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16284
16285        private int mTypes;
16286
16287        private int mOptions;
16288
16289        private boolean mTitlePrinted;
16290
16291        private SharedUserSetting mSharedUser;
16292
16293        public boolean isDumping(int type) {
16294            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16295                return true;
16296            }
16297
16298            return (mTypes & type) != 0;
16299        }
16300
16301        public void setDump(int type) {
16302            mTypes |= type;
16303        }
16304
16305        public boolean isOptionEnabled(int option) {
16306            return (mOptions & option) != 0;
16307        }
16308
16309        public void setOptionEnabled(int option) {
16310            mOptions |= option;
16311        }
16312
16313        public boolean onTitlePrinted() {
16314            final boolean printed = mTitlePrinted;
16315            mTitlePrinted = true;
16316            return printed;
16317        }
16318
16319        public boolean getTitlePrinted() {
16320            return mTitlePrinted;
16321        }
16322
16323        public void setTitlePrinted(boolean enabled) {
16324            mTitlePrinted = enabled;
16325        }
16326
16327        public SharedUserSetting getSharedUser() {
16328            return mSharedUser;
16329        }
16330
16331        public void setSharedUser(SharedUserSetting user) {
16332            mSharedUser = user;
16333        }
16334    }
16335
16336    @Override
16337    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16338            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16339        (new PackageManagerShellCommand(this)).exec(
16340                this, in, out, err, args, resultReceiver);
16341    }
16342
16343    @Override
16344    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16345        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16346                != PackageManager.PERMISSION_GRANTED) {
16347            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16348                    + Binder.getCallingPid()
16349                    + ", uid=" + Binder.getCallingUid()
16350                    + " without permission "
16351                    + android.Manifest.permission.DUMP);
16352            return;
16353        }
16354
16355        DumpState dumpState = new DumpState();
16356        boolean fullPreferred = false;
16357        boolean checkin = false;
16358
16359        String packageName = null;
16360        ArraySet<String> permissionNames = null;
16361
16362        int opti = 0;
16363        while (opti < args.length) {
16364            String opt = args[opti];
16365            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16366                break;
16367            }
16368            opti++;
16369
16370            if ("-a".equals(opt)) {
16371                // Right now we only know how to print all.
16372            } else if ("-h".equals(opt)) {
16373                pw.println("Package manager dump options:");
16374                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16375                pw.println("    --checkin: dump for a checkin");
16376                pw.println("    -f: print details of intent filters");
16377                pw.println("    -h: print this help");
16378                pw.println("  cmd may be one of:");
16379                pw.println("    l[ibraries]: list known shared libraries");
16380                pw.println("    f[eatures]: list device features");
16381                pw.println("    k[eysets]: print known keysets");
16382                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16383                pw.println("    perm[issions]: dump permissions");
16384                pw.println("    permission [name ...]: dump declaration and use of given permission");
16385                pw.println("    pref[erred]: print preferred package settings");
16386                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16387                pw.println("    prov[iders]: dump content providers");
16388                pw.println("    p[ackages]: dump installed packages");
16389                pw.println("    s[hared-users]: dump shared user IDs");
16390                pw.println("    m[essages]: print collected runtime messages");
16391                pw.println("    v[erifiers]: print package verifier info");
16392                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16393                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16394                pw.println("    version: print database version info");
16395                pw.println("    write: write current settings now");
16396                pw.println("    installs: details about install sessions");
16397                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16398                pw.println("    <package.name>: info about given package");
16399                return;
16400            } else if ("--checkin".equals(opt)) {
16401                checkin = true;
16402            } else if ("-f".equals(opt)) {
16403                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16404            } else {
16405                pw.println("Unknown argument: " + opt + "; use -h for help");
16406            }
16407        }
16408
16409        // Is the caller requesting to dump a particular piece of data?
16410        if (opti < args.length) {
16411            String cmd = args[opti];
16412            opti++;
16413            // Is this a package name?
16414            if ("android".equals(cmd) || cmd.contains(".")) {
16415                packageName = cmd;
16416                // When dumping a single package, we always dump all of its
16417                // filter information since the amount of data will be reasonable.
16418                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16419            } else if ("check-permission".equals(cmd)) {
16420                if (opti >= args.length) {
16421                    pw.println("Error: check-permission missing permission argument");
16422                    return;
16423                }
16424                String perm = args[opti];
16425                opti++;
16426                if (opti >= args.length) {
16427                    pw.println("Error: check-permission missing package argument");
16428                    return;
16429                }
16430                String pkg = args[opti];
16431                opti++;
16432                int user = UserHandle.getUserId(Binder.getCallingUid());
16433                if (opti < args.length) {
16434                    try {
16435                        user = Integer.parseInt(args[opti]);
16436                    } catch (NumberFormatException e) {
16437                        pw.println("Error: check-permission user argument is not a number: "
16438                                + args[opti]);
16439                        return;
16440                    }
16441                }
16442                pw.println(checkPermission(perm, pkg, user));
16443                return;
16444            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16445                dumpState.setDump(DumpState.DUMP_LIBS);
16446            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16447                dumpState.setDump(DumpState.DUMP_FEATURES);
16448            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16449                if (opti >= args.length) {
16450                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16451                            | DumpState.DUMP_SERVICE_RESOLVERS
16452                            | DumpState.DUMP_RECEIVER_RESOLVERS
16453                            | DumpState.DUMP_CONTENT_RESOLVERS);
16454                } else {
16455                    while (opti < args.length) {
16456                        String name = args[opti];
16457                        if ("a".equals(name) || "activity".equals(name)) {
16458                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16459                        } else if ("s".equals(name) || "service".equals(name)) {
16460                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16461                        } else if ("r".equals(name) || "receiver".equals(name)) {
16462                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16463                        } else if ("c".equals(name) || "content".equals(name)) {
16464                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16465                        } else {
16466                            pw.println("Error: unknown resolver table type: " + name);
16467                            return;
16468                        }
16469                        opti++;
16470                    }
16471                }
16472            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16473                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16474            } else if ("permission".equals(cmd)) {
16475                if (opti >= args.length) {
16476                    pw.println("Error: permission requires permission name");
16477                    return;
16478                }
16479                permissionNames = new ArraySet<>();
16480                while (opti < args.length) {
16481                    permissionNames.add(args[opti]);
16482                    opti++;
16483                }
16484                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16485                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16486            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16487                dumpState.setDump(DumpState.DUMP_PREFERRED);
16488            } else if ("preferred-xml".equals(cmd)) {
16489                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16490                if (opti < args.length && "--full".equals(args[opti])) {
16491                    fullPreferred = true;
16492                    opti++;
16493                }
16494            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16495                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16496            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16497                dumpState.setDump(DumpState.DUMP_PACKAGES);
16498            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16499                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16500            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16501                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16502            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16503                dumpState.setDump(DumpState.DUMP_MESSAGES);
16504            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16505                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16506            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16507                    || "intent-filter-verifiers".equals(cmd)) {
16508                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16509            } else if ("version".equals(cmd)) {
16510                dumpState.setDump(DumpState.DUMP_VERSION);
16511            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16512                dumpState.setDump(DumpState.DUMP_KEYSETS);
16513            } else if ("installs".equals(cmd)) {
16514                dumpState.setDump(DumpState.DUMP_INSTALLS);
16515            } else if ("write".equals(cmd)) {
16516                synchronized (mPackages) {
16517                    mSettings.writeLPr();
16518                    pw.println("Settings written.");
16519                    return;
16520                }
16521            }
16522        }
16523
16524        if (checkin) {
16525            pw.println("vers,1");
16526        }
16527
16528        // reader
16529        synchronized (mPackages) {
16530            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16531                if (!checkin) {
16532                    if (dumpState.onTitlePrinted())
16533                        pw.println();
16534                    pw.println("Database versions:");
16535                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16536                }
16537            }
16538
16539            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16540                if (!checkin) {
16541                    if (dumpState.onTitlePrinted())
16542                        pw.println();
16543                    pw.println("Verifiers:");
16544                    pw.print("  Required: ");
16545                    pw.print(mRequiredVerifierPackage);
16546                    pw.print(" (uid=");
16547                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16548                            UserHandle.USER_SYSTEM));
16549                    pw.println(")");
16550                } else if (mRequiredVerifierPackage != null) {
16551                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16552                    pw.print(",");
16553                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16554                            UserHandle.USER_SYSTEM));
16555                }
16556            }
16557
16558            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16559                    packageName == null) {
16560                if (mIntentFilterVerifierComponent != null) {
16561                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16562                    if (!checkin) {
16563                        if (dumpState.onTitlePrinted())
16564                            pw.println();
16565                        pw.println("Intent Filter Verifier:");
16566                        pw.print("  Using: ");
16567                        pw.print(verifierPackageName);
16568                        pw.print(" (uid=");
16569                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16570                                UserHandle.USER_SYSTEM));
16571                        pw.println(")");
16572                    } else if (verifierPackageName != null) {
16573                        pw.print("ifv,"); pw.print(verifierPackageName);
16574                        pw.print(",");
16575                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16576                                UserHandle.USER_SYSTEM));
16577                    }
16578                } else {
16579                    pw.println();
16580                    pw.println("No Intent Filter Verifier available!");
16581                }
16582            }
16583
16584            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16585                boolean printedHeader = false;
16586                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16587                while (it.hasNext()) {
16588                    String name = it.next();
16589                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16590                    if (!checkin) {
16591                        if (!printedHeader) {
16592                            if (dumpState.onTitlePrinted())
16593                                pw.println();
16594                            pw.println("Libraries:");
16595                            printedHeader = true;
16596                        }
16597                        pw.print("  ");
16598                    } else {
16599                        pw.print("lib,");
16600                    }
16601                    pw.print(name);
16602                    if (!checkin) {
16603                        pw.print(" -> ");
16604                    }
16605                    if (ent.path != null) {
16606                        if (!checkin) {
16607                            pw.print("(jar) ");
16608                            pw.print(ent.path);
16609                        } else {
16610                            pw.print(",jar,");
16611                            pw.print(ent.path);
16612                        }
16613                    } else {
16614                        if (!checkin) {
16615                            pw.print("(apk) ");
16616                            pw.print(ent.apk);
16617                        } else {
16618                            pw.print(",apk,");
16619                            pw.print(ent.apk);
16620                        }
16621                    }
16622                    pw.println();
16623                }
16624            }
16625
16626            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16627                if (dumpState.onTitlePrinted())
16628                    pw.println();
16629                if (!checkin) {
16630                    pw.println("Features:");
16631                }
16632                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16633                while (it.hasNext()) {
16634                    String name = it.next();
16635                    if (!checkin) {
16636                        pw.print("  ");
16637                    } else {
16638                        pw.print("feat,");
16639                    }
16640                    pw.println(name);
16641                }
16642            }
16643
16644            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16645                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16646                        : "Activity Resolver Table:", "  ", packageName,
16647                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16648                    dumpState.setTitlePrinted(true);
16649                }
16650            }
16651            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16652                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16653                        : "Receiver Resolver Table:", "  ", packageName,
16654                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16655                    dumpState.setTitlePrinted(true);
16656                }
16657            }
16658            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16659                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16660                        : "Service Resolver Table:", "  ", packageName,
16661                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16662                    dumpState.setTitlePrinted(true);
16663                }
16664            }
16665            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16666                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16667                        : "Provider Resolver Table:", "  ", packageName,
16668                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16669                    dumpState.setTitlePrinted(true);
16670                }
16671            }
16672
16673            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16674                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16675                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16676                    int user = mSettings.mPreferredActivities.keyAt(i);
16677                    if (pir.dump(pw,
16678                            dumpState.getTitlePrinted()
16679                                ? "\nPreferred Activities User " + user + ":"
16680                                : "Preferred Activities User " + user + ":", "  ",
16681                            packageName, true, false)) {
16682                        dumpState.setTitlePrinted(true);
16683                    }
16684                }
16685            }
16686
16687            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16688                pw.flush();
16689                FileOutputStream fout = new FileOutputStream(fd);
16690                BufferedOutputStream str = new BufferedOutputStream(fout);
16691                XmlSerializer serializer = new FastXmlSerializer();
16692                try {
16693                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16694                    serializer.startDocument(null, true);
16695                    serializer.setFeature(
16696                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16697                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16698                    serializer.endDocument();
16699                    serializer.flush();
16700                } catch (IllegalArgumentException e) {
16701                    pw.println("Failed writing: " + e);
16702                } catch (IllegalStateException e) {
16703                    pw.println("Failed writing: " + e);
16704                } catch (IOException e) {
16705                    pw.println("Failed writing: " + e);
16706                }
16707            }
16708
16709            if (!checkin
16710                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16711                    && packageName == null) {
16712                pw.println();
16713                int count = mSettings.mPackages.size();
16714                if (count == 0) {
16715                    pw.println("No applications!");
16716                    pw.println();
16717                } else {
16718                    final String prefix = "  ";
16719                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16720                    if (allPackageSettings.size() == 0) {
16721                        pw.println("No domain preferred apps!");
16722                        pw.println();
16723                    } else {
16724                        pw.println("App verification status:");
16725                        pw.println();
16726                        count = 0;
16727                        for (PackageSetting ps : allPackageSettings) {
16728                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16729                            if (ivi == null || ivi.getPackageName() == null) continue;
16730                            pw.println(prefix + "Package: " + ivi.getPackageName());
16731                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16732                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16733                            pw.println();
16734                            count++;
16735                        }
16736                        if (count == 0) {
16737                            pw.println(prefix + "No app verification established.");
16738                            pw.println();
16739                        }
16740                        for (int userId : sUserManager.getUserIds()) {
16741                            pw.println("App linkages for user " + userId + ":");
16742                            pw.println();
16743                            count = 0;
16744                            for (PackageSetting ps : allPackageSettings) {
16745                                final long status = ps.getDomainVerificationStatusForUser(userId);
16746                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16747                                    continue;
16748                                }
16749                                pw.println(prefix + "Package: " + ps.name);
16750                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16751                                String statusStr = IntentFilterVerificationInfo.
16752                                        getStatusStringFromValue(status);
16753                                pw.println(prefix + "Status:  " + statusStr);
16754                                pw.println();
16755                                count++;
16756                            }
16757                            if (count == 0) {
16758                                pw.println(prefix + "No configured app linkages.");
16759                                pw.println();
16760                            }
16761                        }
16762                    }
16763                }
16764            }
16765
16766            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16767                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16768                if (packageName == null && permissionNames == null) {
16769                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16770                        if (iperm == 0) {
16771                            if (dumpState.onTitlePrinted())
16772                                pw.println();
16773                            pw.println("AppOp Permissions:");
16774                        }
16775                        pw.print("  AppOp Permission ");
16776                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16777                        pw.println(":");
16778                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16779                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16780                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16781                        }
16782                    }
16783                }
16784            }
16785
16786            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16787                boolean printedSomething = false;
16788                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16789                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16790                        continue;
16791                    }
16792                    if (!printedSomething) {
16793                        if (dumpState.onTitlePrinted())
16794                            pw.println();
16795                        pw.println("Registered ContentProviders:");
16796                        printedSomething = true;
16797                    }
16798                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16799                    pw.print("    "); pw.println(p.toString());
16800                }
16801                printedSomething = false;
16802                for (Map.Entry<String, PackageParser.Provider> entry :
16803                        mProvidersByAuthority.entrySet()) {
16804                    PackageParser.Provider p = entry.getValue();
16805                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16806                        continue;
16807                    }
16808                    if (!printedSomething) {
16809                        if (dumpState.onTitlePrinted())
16810                            pw.println();
16811                        pw.println("ContentProvider Authorities:");
16812                        printedSomething = true;
16813                    }
16814                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16815                    pw.print("    "); pw.println(p.toString());
16816                    if (p.info != null && p.info.applicationInfo != null) {
16817                        final String appInfo = p.info.applicationInfo.toString();
16818                        pw.print("      applicationInfo="); pw.println(appInfo);
16819                    }
16820                }
16821            }
16822
16823            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16824                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16825            }
16826
16827            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16828                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16829            }
16830
16831            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16832                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16833            }
16834
16835            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16836                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16837            }
16838
16839            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16840                // XXX should handle packageName != null by dumping only install data that
16841                // the given package is involved with.
16842                if (dumpState.onTitlePrinted()) pw.println();
16843                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16844            }
16845
16846            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16847                if (dumpState.onTitlePrinted()) pw.println();
16848                mSettings.dumpReadMessagesLPr(pw, dumpState);
16849
16850                pw.println();
16851                pw.println("Package warning messages:");
16852                BufferedReader in = null;
16853                String line = null;
16854                try {
16855                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16856                    while ((line = in.readLine()) != null) {
16857                        if (line.contains("ignored: updated version")) continue;
16858                        pw.println(line);
16859                    }
16860                } catch (IOException ignored) {
16861                } finally {
16862                    IoUtils.closeQuietly(in);
16863                }
16864            }
16865
16866            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16867                BufferedReader in = null;
16868                String line = null;
16869                try {
16870                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16871                    while ((line = in.readLine()) != null) {
16872                        if (line.contains("ignored: updated version")) continue;
16873                        pw.print("msg,");
16874                        pw.println(line);
16875                    }
16876                } catch (IOException ignored) {
16877                } finally {
16878                    IoUtils.closeQuietly(in);
16879                }
16880            }
16881        }
16882    }
16883
16884    private String dumpDomainString(String packageName) {
16885        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16886        List<IntentFilter> filters = getAllIntentFilters(packageName);
16887
16888        ArraySet<String> result = new ArraySet<>();
16889        if (iviList.size() > 0) {
16890            for (IntentFilterVerificationInfo ivi : iviList) {
16891                for (String host : ivi.getDomains()) {
16892                    result.add(host);
16893                }
16894            }
16895        }
16896        if (filters != null && filters.size() > 0) {
16897            for (IntentFilter filter : filters) {
16898                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16899                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16900                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16901                    result.addAll(filter.getHostsList());
16902                }
16903            }
16904        }
16905
16906        StringBuilder sb = new StringBuilder(result.size() * 16);
16907        for (String domain : result) {
16908            if (sb.length() > 0) sb.append(" ");
16909            sb.append(domain);
16910        }
16911        return sb.toString();
16912    }
16913
16914    // ------- apps on sdcard specific code -------
16915    static final boolean DEBUG_SD_INSTALL = false;
16916
16917    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16918
16919    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16920
16921    private boolean mMediaMounted = false;
16922
16923    static String getEncryptKey() {
16924        try {
16925            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16926                    SD_ENCRYPTION_KEYSTORE_NAME);
16927            if (sdEncKey == null) {
16928                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16929                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16930                if (sdEncKey == null) {
16931                    Slog.e(TAG, "Failed to create encryption keys");
16932                    return null;
16933                }
16934            }
16935            return sdEncKey;
16936        } catch (NoSuchAlgorithmException nsae) {
16937            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16938            return null;
16939        } catch (IOException ioe) {
16940            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16941            return null;
16942        }
16943    }
16944
16945    /*
16946     * Update media status on PackageManager.
16947     */
16948    @Override
16949    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16950        int callingUid = Binder.getCallingUid();
16951        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16952            throw new SecurityException("Media status can only be updated by the system");
16953        }
16954        // reader; this apparently protects mMediaMounted, but should probably
16955        // be a different lock in that case.
16956        synchronized (mPackages) {
16957            Log.i(TAG, "Updating external media status from "
16958                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16959                    + (mediaStatus ? "mounted" : "unmounted"));
16960            if (DEBUG_SD_INSTALL)
16961                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16962                        + ", mMediaMounted=" + mMediaMounted);
16963            if (mediaStatus == mMediaMounted) {
16964                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16965                        : 0, -1);
16966                mHandler.sendMessage(msg);
16967                return;
16968            }
16969            mMediaMounted = mediaStatus;
16970        }
16971        // Queue up an async operation since the package installation may take a
16972        // little while.
16973        mHandler.post(new Runnable() {
16974            public void run() {
16975                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16976            }
16977        });
16978    }
16979
16980    /**
16981     * Called by MountService when the initial ASECs to scan are available.
16982     * Should block until all the ASEC containers are finished being scanned.
16983     */
16984    public void scanAvailableAsecs() {
16985        updateExternalMediaStatusInner(true, false, false);
16986    }
16987
16988    /*
16989     * Collect information of applications on external media, map them against
16990     * existing containers and update information based on current mount status.
16991     * Please note that we always have to report status if reportStatus has been
16992     * set to true especially when unloading packages.
16993     */
16994    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16995            boolean externalStorage) {
16996        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16997        int[] uidArr = EmptyArray.INT;
16998
16999        final String[] list = PackageHelper.getSecureContainerList();
17000        if (ArrayUtils.isEmpty(list)) {
17001            Log.i(TAG, "No secure containers found");
17002        } else {
17003            // Process list of secure containers and categorize them
17004            // as active or stale based on their package internal state.
17005
17006            // reader
17007            synchronized (mPackages) {
17008                for (String cid : list) {
17009                    // Leave stages untouched for now; installer service owns them
17010                    if (PackageInstallerService.isStageName(cid)) continue;
17011
17012                    if (DEBUG_SD_INSTALL)
17013                        Log.i(TAG, "Processing container " + cid);
17014                    String pkgName = getAsecPackageName(cid);
17015                    if (pkgName == null) {
17016                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17017                        continue;
17018                    }
17019                    if (DEBUG_SD_INSTALL)
17020                        Log.i(TAG, "Looking for pkg : " + pkgName);
17021
17022                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17023                    if (ps == null) {
17024                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17025                        continue;
17026                    }
17027
17028                    /*
17029                     * Skip packages that are not external if we're unmounting
17030                     * external storage.
17031                     */
17032                    if (externalStorage && !isMounted && !isExternal(ps)) {
17033                        continue;
17034                    }
17035
17036                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17037                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17038                    // The package status is changed only if the code path
17039                    // matches between settings and the container id.
17040                    if (ps.codePathString != null
17041                            && ps.codePathString.startsWith(args.getCodePath())) {
17042                        if (DEBUG_SD_INSTALL) {
17043                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17044                                    + " at code path: " + ps.codePathString);
17045                        }
17046
17047                        // We do have a valid package installed on sdcard
17048                        processCids.put(args, ps.codePathString);
17049                        final int uid = ps.appId;
17050                        if (uid != -1) {
17051                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17052                        }
17053                    } else {
17054                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17055                                + ps.codePathString);
17056                    }
17057                }
17058            }
17059
17060            Arrays.sort(uidArr);
17061        }
17062
17063        // Process packages with valid entries.
17064        if (isMounted) {
17065            if (DEBUG_SD_INSTALL)
17066                Log.i(TAG, "Loading packages");
17067            loadMediaPackages(processCids, uidArr, externalStorage);
17068            startCleaningPackages();
17069            mInstallerService.onSecureContainersAvailable();
17070        } else {
17071            if (DEBUG_SD_INSTALL)
17072                Log.i(TAG, "Unloading packages");
17073            unloadMediaPackages(processCids, uidArr, reportStatus);
17074        }
17075    }
17076
17077    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17078            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17079        final int size = infos.size();
17080        final String[] packageNames = new String[size];
17081        final int[] packageUids = new int[size];
17082        for (int i = 0; i < size; i++) {
17083            final ApplicationInfo info = infos.get(i);
17084            packageNames[i] = info.packageName;
17085            packageUids[i] = info.uid;
17086        }
17087        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17088                finishedReceiver);
17089    }
17090
17091    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17092            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17093        sendResourcesChangedBroadcast(mediaStatus, replacing,
17094                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17095    }
17096
17097    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17098            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17099        int size = pkgList.length;
17100        if (size > 0) {
17101            // Send broadcasts here
17102            Bundle extras = new Bundle();
17103            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17104            if (uidArr != null) {
17105                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17106            }
17107            if (replacing) {
17108                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17109            }
17110            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17111                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17112            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17113        }
17114    }
17115
17116   /*
17117     * Look at potentially valid container ids from processCids If package
17118     * information doesn't match the one on record or package scanning fails,
17119     * the cid is added to list of removeCids. We currently don't delete stale
17120     * containers.
17121     */
17122    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17123            boolean externalStorage) {
17124        ArrayList<String> pkgList = new ArrayList<String>();
17125        Set<AsecInstallArgs> keys = processCids.keySet();
17126
17127        for (AsecInstallArgs args : keys) {
17128            String codePath = processCids.get(args);
17129            if (DEBUG_SD_INSTALL)
17130                Log.i(TAG, "Loading container : " + args.cid);
17131            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17132            try {
17133                // Make sure there are no container errors first.
17134                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17135                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17136                            + " when installing from sdcard");
17137                    continue;
17138                }
17139                // Check code path here.
17140                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17141                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17142                            + " does not match one in settings " + codePath);
17143                    continue;
17144                }
17145                // Parse package
17146                int parseFlags = mDefParseFlags;
17147                if (args.isExternalAsec()) {
17148                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17149                }
17150                if (args.isFwdLocked()) {
17151                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17152                }
17153
17154                synchronized (mInstallLock) {
17155                    PackageParser.Package pkg = null;
17156                    try {
17157                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17158                    } catch (PackageManagerException e) {
17159                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17160                    }
17161                    // Scan the package
17162                    if (pkg != null) {
17163                        /*
17164                         * TODO why is the lock being held? doPostInstall is
17165                         * called in other places without the lock. This needs
17166                         * to be straightened out.
17167                         */
17168                        // writer
17169                        synchronized (mPackages) {
17170                            retCode = PackageManager.INSTALL_SUCCEEDED;
17171                            pkgList.add(pkg.packageName);
17172                            // Post process args
17173                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17174                                    pkg.applicationInfo.uid);
17175                        }
17176                    } else {
17177                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17178                    }
17179                }
17180
17181            } finally {
17182                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17183                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17184                }
17185            }
17186        }
17187        // writer
17188        synchronized (mPackages) {
17189            // If the platform SDK has changed since the last time we booted,
17190            // we need to re-grant app permission to catch any new ones that
17191            // appear. This is really a hack, and means that apps can in some
17192            // cases get permissions that the user didn't initially explicitly
17193            // allow... it would be nice to have some better way to handle
17194            // this situation.
17195            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17196                    : mSettings.getInternalVersion();
17197            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17198                    : StorageManager.UUID_PRIVATE_INTERNAL;
17199
17200            int updateFlags = UPDATE_PERMISSIONS_ALL;
17201            if (ver.sdkVersion != mSdkVersion) {
17202                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17203                        + mSdkVersion + "; regranting permissions for external");
17204                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17205            }
17206            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17207
17208            // Yay, everything is now upgraded
17209            ver.forceCurrent();
17210
17211            // can downgrade to reader
17212            // Persist settings
17213            mSettings.writeLPr();
17214        }
17215        // Send a broadcast to let everyone know we are done processing
17216        if (pkgList.size() > 0) {
17217            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17218        }
17219    }
17220
17221   /*
17222     * Utility method to unload a list of specified containers
17223     */
17224    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17225        // Just unmount all valid containers.
17226        for (AsecInstallArgs arg : cidArgs) {
17227            synchronized (mInstallLock) {
17228                arg.doPostDeleteLI(false);
17229           }
17230       }
17231   }
17232
17233    /*
17234     * Unload packages mounted on external media. This involves deleting package
17235     * data from internal structures, sending broadcasts about disabled packages,
17236     * gc'ing to free up references, unmounting all secure containers
17237     * corresponding to packages on external media, and posting a
17238     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17239     * that we always have to post this message if status has been requested no
17240     * matter what.
17241     */
17242    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17243            final boolean reportStatus) {
17244        if (DEBUG_SD_INSTALL)
17245            Log.i(TAG, "unloading media packages");
17246        ArrayList<String> pkgList = new ArrayList<String>();
17247        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17248        final Set<AsecInstallArgs> keys = processCids.keySet();
17249        for (AsecInstallArgs args : keys) {
17250            String pkgName = args.getPackageName();
17251            if (DEBUG_SD_INSTALL)
17252                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17253            // Delete package internally
17254            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17255            synchronized (mInstallLock) {
17256                boolean res = deletePackageLI(pkgName, null, false, null, null,
17257                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17258                if (res) {
17259                    pkgList.add(pkgName);
17260                } else {
17261                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17262                    failedList.add(args);
17263                }
17264            }
17265        }
17266
17267        // reader
17268        synchronized (mPackages) {
17269            // We didn't update the settings after removing each package;
17270            // write them now for all packages.
17271            mSettings.writeLPr();
17272        }
17273
17274        // We have to absolutely send UPDATED_MEDIA_STATUS only
17275        // after confirming that all the receivers processed the ordered
17276        // broadcast when packages get disabled, force a gc to clean things up.
17277        // and unload all the containers.
17278        if (pkgList.size() > 0) {
17279            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17280                    new IIntentReceiver.Stub() {
17281                public void performReceive(Intent intent, int resultCode, String data,
17282                        Bundle extras, boolean ordered, boolean sticky,
17283                        int sendingUser) throws RemoteException {
17284                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17285                            reportStatus ? 1 : 0, 1, keys);
17286                    mHandler.sendMessage(msg);
17287                }
17288            });
17289        } else {
17290            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17291                    keys);
17292            mHandler.sendMessage(msg);
17293        }
17294    }
17295
17296    private void loadPrivatePackages(final VolumeInfo vol) {
17297        mHandler.post(new Runnable() {
17298            @Override
17299            public void run() {
17300                loadPrivatePackagesInner(vol);
17301            }
17302        });
17303    }
17304
17305    private void loadPrivatePackagesInner(VolumeInfo vol) {
17306        final String volumeUuid = vol.fsUuid;
17307        if (TextUtils.isEmpty(volumeUuid)) {
17308            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17309            return;
17310        }
17311
17312        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17313        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17314
17315        final VersionInfo ver;
17316        final List<PackageSetting> packages;
17317        synchronized (mPackages) {
17318            ver = mSettings.findOrCreateVersion(volumeUuid);
17319            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17320        }
17321
17322        // TODO: introduce a new concept similar to "frozen" to prevent these
17323        // apps from being launched until after data has been fully reconciled
17324        for (PackageSetting ps : packages) {
17325            synchronized (mInstallLock) {
17326                final PackageParser.Package pkg;
17327                try {
17328                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17329                    loaded.add(pkg.applicationInfo);
17330
17331                } catch (PackageManagerException e) {
17332                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17333                }
17334
17335                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17336                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17337                }
17338            }
17339        }
17340
17341        // Reconcile app data for all started/unlocked users
17342        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17343        final UserManager um = mContext.getSystemService(UserManager.class);
17344        for (UserInfo user : um.getUsers()) {
17345            final int flags;
17346            if (um.isUserUnlocked(user.id)) {
17347                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17348            } else if (um.isUserRunning(user.id)) {
17349                flags = StorageManager.FLAG_STORAGE_DE;
17350            } else {
17351                continue;
17352            }
17353
17354            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17355            reconcileAppsData(volumeUuid, user.id, flags);
17356        }
17357
17358        synchronized (mPackages) {
17359            int updateFlags = UPDATE_PERMISSIONS_ALL;
17360            if (ver.sdkVersion != mSdkVersion) {
17361                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17362                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17363                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17364            }
17365            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17366
17367            // Yay, everything is now upgraded
17368            ver.forceCurrent();
17369
17370            mSettings.writeLPr();
17371        }
17372
17373        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17374        sendResourcesChangedBroadcast(true, false, loaded, null);
17375    }
17376
17377    private void unloadPrivatePackages(final VolumeInfo vol) {
17378        mHandler.post(new Runnable() {
17379            @Override
17380            public void run() {
17381                unloadPrivatePackagesInner(vol);
17382            }
17383        });
17384    }
17385
17386    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17387        final String volumeUuid = vol.fsUuid;
17388        if (TextUtils.isEmpty(volumeUuid)) {
17389            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17390            return;
17391        }
17392
17393        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17394        synchronized (mInstallLock) {
17395        synchronized (mPackages) {
17396            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17397            for (PackageSetting ps : packages) {
17398                if (ps.pkg == null) continue;
17399
17400                final ApplicationInfo info = ps.pkg.applicationInfo;
17401                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17402                if (deletePackageLI(ps.name, null, false, null, null,
17403                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17404                    unloaded.add(info);
17405                } else {
17406                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17407                }
17408            }
17409
17410            mSettings.writeLPr();
17411        }
17412        }
17413
17414        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17415        sendResourcesChangedBroadcast(false, false, unloaded, null);
17416    }
17417
17418    /**
17419     * Examine all users present on given mounted volume, and destroy data
17420     * belonging to users that are no longer valid, or whose user ID has been
17421     * recycled.
17422     */
17423    private void reconcileUsers(String volumeUuid) {
17424        final File[] files = FileUtils
17425                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
17426        for (File file : files) {
17427            if (!file.isDirectory()) continue;
17428
17429            final int userId;
17430            final UserInfo info;
17431            try {
17432                userId = Integer.parseInt(file.getName());
17433                info = sUserManager.getUserInfo(userId);
17434            } catch (NumberFormatException e) {
17435                Slog.w(TAG, "Invalid user directory " + file);
17436                continue;
17437            }
17438
17439            boolean destroyUser = false;
17440            if (info == null) {
17441                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17442                        + " because no matching user was found");
17443                destroyUser = true;
17444            } else {
17445                try {
17446                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17447                } catch (IOException e) {
17448                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17449                            + " because we failed to enforce serial number: " + e);
17450                    destroyUser = true;
17451                }
17452            }
17453
17454            if (destroyUser) {
17455                synchronized (mInstallLock) {
17456                    try {
17457                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17458                    } catch (InstallerException e) {
17459                        Slog.w(TAG, "Failed to clean up user dirs", e);
17460                    }
17461                }
17462            }
17463        }
17464    }
17465
17466    private void assertPackageKnown(String volumeUuid, String packageName)
17467            throws PackageManagerException {
17468        synchronized (mPackages) {
17469            final PackageSetting ps = mSettings.mPackages.get(packageName);
17470            if (ps == null) {
17471                throw new PackageManagerException("Package " + packageName + " is unknown");
17472            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17473                throw new PackageManagerException(
17474                        "Package " + packageName + " found on unknown volume " + volumeUuid
17475                                + "; expected volume " + ps.volumeUuid);
17476            }
17477        }
17478    }
17479
17480    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17481            throws PackageManagerException {
17482        synchronized (mPackages) {
17483            final PackageSetting ps = mSettings.mPackages.get(packageName);
17484            if (ps == null) {
17485                throw new PackageManagerException("Package " + packageName + " is unknown");
17486            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17487                throw new PackageManagerException(
17488                        "Package " + packageName + " found on unknown volume " + volumeUuid
17489                                + "; expected volume " + ps.volumeUuid);
17490            } else if (!ps.getInstalled(userId)) {
17491                throw new PackageManagerException(
17492                        "Package " + packageName + " not installed for user " + userId);
17493            }
17494        }
17495    }
17496
17497    /**
17498     * Examine all apps present on given mounted volume, and destroy apps that
17499     * aren't expected, either due to uninstallation or reinstallation on
17500     * another volume.
17501     */
17502    private void reconcileApps(String volumeUuid) {
17503        final File[] files = FileUtils
17504                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17505        for (File file : files) {
17506            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17507                    && !PackageInstallerService.isStageName(file.getName());
17508            if (!isPackage) {
17509                // Ignore entries which are not packages
17510                continue;
17511            }
17512
17513            try {
17514                final PackageLite pkg = PackageParser.parsePackageLite(file,
17515                        PackageParser.PARSE_MUST_BE_APK);
17516                assertPackageKnown(volumeUuid, pkg.packageName);
17517
17518            } catch (PackageParserException | PackageManagerException e) {
17519                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17520                synchronized (mInstallLock) {
17521                    removeCodePathLI(file);
17522                }
17523            }
17524        }
17525    }
17526
17527    /**
17528     * Reconcile all app data for the given user.
17529     * <p>
17530     * Verifies that directories exist and that ownership and labeling is
17531     * correct for all installed apps on all mounted volumes.
17532     */
17533    void reconcileAppsData(int userId, int flags) {
17534        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17535        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17536            final String volumeUuid = vol.getFsUuid();
17537            reconcileAppsData(volumeUuid, userId, flags);
17538        }
17539    }
17540
17541    /**
17542     * Reconcile all app data on given mounted volume.
17543     * <p>
17544     * Destroys app data that isn't expected, either due to uninstallation or
17545     * reinstallation on another volume.
17546     * <p>
17547     * Verifies that directories exist and that ownership and labeling is
17548     * correct for all installed apps.
17549     */
17550    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17551        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17552                + Integer.toHexString(flags));
17553
17554        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17555        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17556
17557        boolean restoreconNeeded = false;
17558
17559        // First look for stale data that doesn't belong, and check if things
17560        // have changed since we did our last restorecon
17561        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17562            if (!isUserKeyUnlocked(userId)) {
17563                throw new RuntimeException(
17564                        "Yikes, someone asked us to reconcile CE storage while " + userId
17565                                + " was still locked; this would have caused massive data loss!");
17566            }
17567
17568            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17569
17570            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17571            for (File file : files) {
17572                final String packageName = file.getName();
17573                try {
17574                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17575                } catch (PackageManagerException e) {
17576                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17577                    synchronized (mInstallLock) {
17578                        destroyAppDataLI(volumeUuid, packageName, userId,
17579                                StorageManager.FLAG_STORAGE_CE);
17580                    }
17581                }
17582            }
17583        }
17584        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17585            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17586
17587            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17588            for (File file : files) {
17589                final String packageName = file.getName();
17590                try {
17591                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17592                } catch (PackageManagerException e) {
17593                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17594                    synchronized (mInstallLock) {
17595                        destroyAppDataLI(volumeUuid, packageName, userId,
17596                                StorageManager.FLAG_STORAGE_DE);
17597                    }
17598                }
17599            }
17600        }
17601
17602        // Ensure that data directories are ready to roll for all packages
17603        // installed for this volume and user
17604        final List<PackageSetting> packages;
17605        synchronized (mPackages) {
17606            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17607        }
17608        int preparedCount = 0;
17609        for (PackageSetting ps : packages) {
17610            final String packageName = ps.name;
17611            if (ps.pkg == null) {
17612                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17613                // TODO: might be due to legacy ASEC apps; we should circle back
17614                // and reconcile again once they're scanned
17615                continue;
17616            }
17617
17618            if (ps.getInstalled(userId)) {
17619                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17620                preparedCount++;
17621            }
17622        }
17623
17624        if (restoreconNeeded) {
17625            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17626                SELinuxMMAC.setRestoreconDone(ceDir);
17627            }
17628            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17629                SELinuxMMAC.setRestoreconDone(deDir);
17630            }
17631        }
17632
17633        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17634                + " packages; restoreconNeeded was " + restoreconNeeded);
17635    }
17636
17637    /**
17638     * Prepare app data for the given app just after it was installed or
17639     * upgraded. This method carefully only touches users that it's installed
17640     * for, and it forces a restorecon to handle any seinfo changes.
17641     * <p>
17642     * Verifies that directories exist and that ownership and labeling is
17643     * correct for all installed apps. If there is an ownership mismatch, it
17644     * will try recovering system apps by wiping data; third-party app data is
17645     * left intact.
17646     */
17647    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17648        prepareAppDataAfterInstallInternal(pkg);
17649        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17650        for (int i = 0; i < childCount; i++) {
17651            PackageParser.Package childPackage = pkg.childPackages.get(i);
17652            prepareAppDataAfterInstallInternal(childPackage);
17653        }
17654    }
17655
17656    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17657        final PackageSetting ps;
17658        synchronized (mPackages) {
17659            ps = mSettings.mPackages.get(pkg.packageName);
17660        }
17661
17662        final UserManager um = mContext.getSystemService(UserManager.class);
17663        for (UserInfo user : um.getUsers()) {
17664            final int flags;
17665            if (um.isUserUnlocked(user.id)) {
17666                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17667            } else if (um.isUserRunning(user.id)) {
17668                flags = StorageManager.FLAG_STORAGE_DE;
17669            } else {
17670                continue;
17671            }
17672
17673            if (ps.getInstalled(user.id)) {
17674                // Whenever an app changes, force a restorecon of its data
17675                // TODO: when user data is locked, mark that we're still dirty
17676                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17677            }
17678        }
17679    }
17680
17681    /**
17682     * Prepare app data for the given app.
17683     * <p>
17684     * Verifies that directories exist and that ownership and labeling is
17685     * correct for all installed apps. If there is an ownership mismatch, this
17686     * will try recovering system apps by wiping data; third-party app data is
17687     * left intact.
17688     */
17689    private void prepareAppData(String volumeUuid, int userId, int flags,
17690            PackageParser.Package pkg, boolean restoreconNeeded) {
17691        if (DEBUG_APP_DATA) {
17692            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17693                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17694        }
17695
17696        final String packageName = pkg.packageName;
17697        final ApplicationInfo app = pkg.applicationInfo;
17698        final int appId = UserHandle.getAppId(app.uid);
17699
17700        Preconditions.checkNotNull(app.seinfo);
17701
17702        synchronized (mInstallLock) {
17703            try {
17704                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17705                        appId, app.seinfo, app.targetSdkVersion);
17706            } catch (InstallerException e) {
17707                if (app.isSystemApp()) {
17708                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17709                            + ", but trying to recover: " + e);
17710                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17711                    try {
17712                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17713                                appId, app.seinfo, app.targetSdkVersion);
17714                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17715                    } catch (InstallerException e2) {
17716                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17717                    }
17718                } else {
17719                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17720                }
17721            }
17722
17723            if (restoreconNeeded) {
17724                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17725            }
17726
17727            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17728                // Create a native library symlink only if we have native libraries
17729                // and if the native libraries are 32 bit libraries. We do not provide
17730                // this symlink for 64 bit libraries.
17731                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17732                    final String nativeLibPath = app.nativeLibraryDir;
17733                    try {
17734                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17735                                nativeLibPath, userId);
17736                    } catch (InstallerException e) {
17737                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17738                    }
17739                }
17740            }
17741        }
17742    }
17743
17744    private void unfreezePackage(String packageName) {
17745        synchronized (mPackages) {
17746            final PackageSetting ps = mSettings.mPackages.get(packageName);
17747            if (ps != null) {
17748                ps.frozen = false;
17749            }
17750        }
17751    }
17752
17753    @Override
17754    public int movePackage(final String packageName, final String volumeUuid) {
17755        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17756
17757        final int moveId = mNextMoveId.getAndIncrement();
17758        mHandler.post(new Runnable() {
17759            @Override
17760            public void run() {
17761                try {
17762                    movePackageInternal(packageName, volumeUuid, moveId);
17763                } catch (PackageManagerException e) {
17764                    Slog.w(TAG, "Failed to move " + packageName, e);
17765                    mMoveCallbacks.notifyStatusChanged(moveId,
17766                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17767                }
17768            }
17769        });
17770        return moveId;
17771    }
17772
17773    private void movePackageInternal(final String packageName, final String volumeUuid,
17774            final int moveId) throws PackageManagerException {
17775        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17776        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17777        final PackageManager pm = mContext.getPackageManager();
17778
17779        final boolean currentAsec;
17780        final String currentVolumeUuid;
17781        final File codeFile;
17782        final String installerPackageName;
17783        final String packageAbiOverride;
17784        final int appId;
17785        final String seinfo;
17786        final String label;
17787        final int targetSdkVersion;
17788
17789        // reader
17790        synchronized (mPackages) {
17791            final PackageParser.Package pkg = mPackages.get(packageName);
17792            final PackageSetting ps = mSettings.mPackages.get(packageName);
17793            if (pkg == null || ps == null) {
17794                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17795            }
17796
17797            if (pkg.applicationInfo.isSystemApp()) {
17798                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17799                        "Cannot move system application");
17800            }
17801
17802            if (pkg.applicationInfo.isExternalAsec()) {
17803                currentAsec = true;
17804                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17805            } else if (pkg.applicationInfo.isForwardLocked()) {
17806                currentAsec = true;
17807                currentVolumeUuid = "forward_locked";
17808            } else {
17809                currentAsec = false;
17810                currentVolumeUuid = ps.volumeUuid;
17811
17812                final File probe = new File(pkg.codePath);
17813                final File probeOat = new File(probe, "oat");
17814                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17815                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17816                            "Move only supported for modern cluster style installs");
17817                }
17818            }
17819
17820            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17821                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17822                        "Package already moved to " + volumeUuid);
17823            }
17824
17825            if (ps.frozen) {
17826                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17827                        "Failed to move already frozen package");
17828            }
17829            ps.frozen = true;
17830
17831            codeFile = new File(pkg.codePath);
17832            installerPackageName = ps.installerPackageName;
17833            packageAbiOverride = ps.cpuAbiOverrideString;
17834            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17835            seinfo = pkg.applicationInfo.seinfo;
17836            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17837            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17838        }
17839
17840        // Now that we're guarded by frozen state, kill app during move
17841        final long token = Binder.clearCallingIdentity();
17842        try {
17843            killApplication(packageName, appId, "move pkg");
17844        } finally {
17845            Binder.restoreCallingIdentity(token);
17846        }
17847
17848        final Bundle extras = new Bundle();
17849        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17850        extras.putString(Intent.EXTRA_TITLE, label);
17851        mMoveCallbacks.notifyCreated(moveId, extras);
17852
17853        int installFlags;
17854        final boolean moveCompleteApp;
17855        final File measurePath;
17856
17857        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17858            installFlags = INSTALL_INTERNAL;
17859            moveCompleteApp = !currentAsec;
17860            measurePath = Environment.getDataAppDirectory(volumeUuid);
17861        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17862            installFlags = INSTALL_EXTERNAL;
17863            moveCompleteApp = false;
17864            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17865        } else {
17866            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17867            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17868                    || !volume.isMountedWritable()) {
17869                unfreezePackage(packageName);
17870                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17871                        "Move location not mounted private volume");
17872            }
17873
17874            Preconditions.checkState(!currentAsec);
17875
17876            installFlags = INSTALL_INTERNAL;
17877            moveCompleteApp = true;
17878            measurePath = Environment.getDataAppDirectory(volumeUuid);
17879        }
17880
17881        final PackageStats stats = new PackageStats(null, -1);
17882        synchronized (mInstaller) {
17883            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17884                unfreezePackage(packageName);
17885                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17886                        "Failed to measure package size");
17887            }
17888        }
17889
17890        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17891                + stats.dataSize);
17892
17893        final long startFreeBytes = measurePath.getFreeSpace();
17894        final long sizeBytes;
17895        if (moveCompleteApp) {
17896            sizeBytes = stats.codeSize + stats.dataSize;
17897        } else {
17898            sizeBytes = stats.codeSize;
17899        }
17900
17901        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17902            unfreezePackage(packageName);
17903            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17904                    "Not enough free space to move");
17905        }
17906
17907        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17908
17909        final CountDownLatch installedLatch = new CountDownLatch(1);
17910        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17911            @Override
17912            public void onUserActionRequired(Intent intent) throws RemoteException {
17913                throw new IllegalStateException();
17914            }
17915
17916            @Override
17917            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17918                    Bundle extras) throws RemoteException {
17919                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17920                        + PackageManager.installStatusToString(returnCode, msg));
17921
17922                installedLatch.countDown();
17923
17924                // Regardless of success or failure of the move operation,
17925                // always unfreeze the package
17926                unfreezePackage(packageName);
17927
17928                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17929                switch (status) {
17930                    case PackageInstaller.STATUS_SUCCESS:
17931                        mMoveCallbacks.notifyStatusChanged(moveId,
17932                                PackageManager.MOVE_SUCCEEDED);
17933                        break;
17934                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17935                        mMoveCallbacks.notifyStatusChanged(moveId,
17936                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17937                        break;
17938                    default:
17939                        mMoveCallbacks.notifyStatusChanged(moveId,
17940                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17941                        break;
17942                }
17943            }
17944        };
17945
17946        final MoveInfo move;
17947        if (moveCompleteApp) {
17948            // Kick off a thread to report progress estimates
17949            new Thread() {
17950                @Override
17951                public void run() {
17952                    while (true) {
17953                        try {
17954                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17955                                break;
17956                            }
17957                        } catch (InterruptedException ignored) {
17958                        }
17959
17960                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17961                        final int progress = 10 + (int) MathUtils.constrain(
17962                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17963                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17964                    }
17965                }
17966            }.start();
17967
17968            final String dataAppName = codeFile.getName();
17969            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17970                    dataAppName, appId, seinfo, targetSdkVersion);
17971        } else {
17972            move = null;
17973        }
17974
17975        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17976
17977        final Message msg = mHandler.obtainMessage(INIT_COPY);
17978        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17979        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17980                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17981        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17982        msg.obj = params;
17983
17984        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17985                System.identityHashCode(msg.obj));
17986        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17987                System.identityHashCode(msg.obj));
17988
17989        mHandler.sendMessage(msg);
17990    }
17991
17992    @Override
17993    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17994        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17995
17996        final int realMoveId = mNextMoveId.getAndIncrement();
17997        final Bundle extras = new Bundle();
17998        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17999        mMoveCallbacks.notifyCreated(realMoveId, extras);
18000
18001        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18002            @Override
18003            public void onCreated(int moveId, Bundle extras) {
18004                // Ignored
18005            }
18006
18007            @Override
18008            public void onStatusChanged(int moveId, int status, long estMillis) {
18009                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18010            }
18011        };
18012
18013        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18014        storage.setPrimaryStorageUuid(volumeUuid, callback);
18015        return realMoveId;
18016    }
18017
18018    @Override
18019    public int getMoveStatus(int moveId) {
18020        mContext.enforceCallingOrSelfPermission(
18021                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18022        return mMoveCallbacks.mLastStatus.get(moveId);
18023    }
18024
18025    @Override
18026    public void registerMoveCallback(IPackageMoveObserver callback) {
18027        mContext.enforceCallingOrSelfPermission(
18028                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18029        mMoveCallbacks.register(callback);
18030    }
18031
18032    @Override
18033    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18034        mContext.enforceCallingOrSelfPermission(
18035                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18036        mMoveCallbacks.unregister(callback);
18037    }
18038
18039    @Override
18040    public boolean setInstallLocation(int loc) {
18041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18042                null);
18043        if (getInstallLocation() == loc) {
18044            return true;
18045        }
18046        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18047                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18048            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18049                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18050            return true;
18051        }
18052        return false;
18053   }
18054
18055    @Override
18056    public int getInstallLocation() {
18057        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18058                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18059                PackageHelper.APP_INSTALL_AUTO);
18060    }
18061
18062    /** Called by UserManagerService */
18063    void cleanUpUser(UserManagerService userManager, int userHandle) {
18064        synchronized (mPackages) {
18065            mDirtyUsers.remove(userHandle);
18066            mUserNeedsBadging.delete(userHandle);
18067            mSettings.removeUserLPw(userHandle);
18068            mPendingBroadcasts.remove(userHandle);
18069            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18070        }
18071        synchronized (mInstallLock) {
18072            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18073            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18074                final String volumeUuid = vol.getFsUuid();
18075                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18076                try {
18077                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18078                } catch (InstallerException e) {
18079                    Slog.w(TAG, "Failed to remove user data", e);
18080                }
18081            }
18082            synchronized (mPackages) {
18083                removeUnusedPackagesLILPw(userManager, userHandle);
18084            }
18085        }
18086    }
18087
18088    /**
18089     * We're removing userHandle and would like to remove any downloaded packages
18090     * that are no longer in use by any other user.
18091     * @param userHandle the user being removed
18092     */
18093    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18094        final boolean DEBUG_CLEAN_APKS = false;
18095        int [] users = userManager.getUserIds();
18096        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18097        while (psit.hasNext()) {
18098            PackageSetting ps = psit.next();
18099            if (ps.pkg == null) {
18100                continue;
18101            }
18102            final String packageName = ps.pkg.packageName;
18103            // Skip over if system app
18104            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18105                continue;
18106            }
18107            if (DEBUG_CLEAN_APKS) {
18108                Slog.i(TAG, "Checking package " + packageName);
18109            }
18110            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18111            if (keep) {
18112                if (DEBUG_CLEAN_APKS) {
18113                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18114                }
18115            } else {
18116                for (int i = 0; i < users.length; i++) {
18117                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18118                        keep = true;
18119                        if (DEBUG_CLEAN_APKS) {
18120                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18121                                    + users[i]);
18122                        }
18123                        break;
18124                    }
18125                }
18126            }
18127            if (!keep) {
18128                if (DEBUG_CLEAN_APKS) {
18129                    Slog.i(TAG, "  Removing package " + packageName);
18130                }
18131                mHandler.post(new Runnable() {
18132                    public void run() {
18133                        deletePackageX(packageName, userHandle, 0);
18134                    } //end run
18135                });
18136            }
18137        }
18138    }
18139
18140    /** Called by UserManagerService */
18141    void createNewUser(int userHandle) {
18142        synchronized (mInstallLock) {
18143            try {
18144                mInstaller.createUserConfig(userHandle);
18145            } catch (InstallerException e) {
18146                Slog.w(TAG, "Failed to create user config", e);
18147            }
18148            mSettings.createNewUserLI(this, mInstaller, userHandle);
18149        }
18150        synchronized (mPackages) {
18151            applyFactoryDefaultBrowserLPw(userHandle);
18152            primeDomainVerificationsLPw(userHandle);
18153        }
18154    }
18155
18156    void newUserCreated(final int userHandle) {
18157        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18158        // If permission review for legacy apps is required, we represent
18159        // dagerous permissions for such apps as always granted runtime
18160        // permissions to keep per user flag state whether review is needed.
18161        // Hence, if a new user is added we have to propagate dangerous
18162        // permission grants for these legacy apps.
18163        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18164            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18165                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18166        }
18167    }
18168
18169    @Override
18170    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18171        mContext.enforceCallingOrSelfPermission(
18172                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18173                "Only package verification agents can read the verifier device identity");
18174
18175        synchronized (mPackages) {
18176            return mSettings.getVerifierDeviceIdentityLPw();
18177        }
18178    }
18179
18180    @Override
18181    public void setPermissionEnforced(String permission, boolean enforced) {
18182        // TODO: Now that we no longer change GID for storage, this should to away.
18183        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18184                "setPermissionEnforced");
18185        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18186            synchronized (mPackages) {
18187                if (mSettings.mReadExternalStorageEnforced == null
18188                        || mSettings.mReadExternalStorageEnforced != enforced) {
18189                    mSettings.mReadExternalStorageEnforced = enforced;
18190                    mSettings.writeLPr();
18191                }
18192            }
18193            // kill any non-foreground processes so we restart them and
18194            // grant/revoke the GID.
18195            final IActivityManager am = ActivityManagerNative.getDefault();
18196            if (am != null) {
18197                final long token = Binder.clearCallingIdentity();
18198                try {
18199                    am.killProcessesBelowForeground("setPermissionEnforcement");
18200                } catch (RemoteException e) {
18201                } finally {
18202                    Binder.restoreCallingIdentity(token);
18203                }
18204            }
18205        } else {
18206            throw new IllegalArgumentException("No selective enforcement for " + permission);
18207        }
18208    }
18209
18210    @Override
18211    @Deprecated
18212    public boolean isPermissionEnforced(String permission) {
18213        return true;
18214    }
18215
18216    @Override
18217    public boolean isStorageLow() {
18218        final long token = Binder.clearCallingIdentity();
18219        try {
18220            final DeviceStorageMonitorInternal
18221                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18222            if (dsm != null) {
18223                return dsm.isMemoryLow();
18224            } else {
18225                return false;
18226            }
18227        } finally {
18228            Binder.restoreCallingIdentity(token);
18229        }
18230    }
18231
18232    @Override
18233    public IPackageInstaller getPackageInstaller() {
18234        return mInstallerService;
18235    }
18236
18237    private boolean userNeedsBadging(int userId) {
18238        int index = mUserNeedsBadging.indexOfKey(userId);
18239        if (index < 0) {
18240            final UserInfo userInfo;
18241            final long token = Binder.clearCallingIdentity();
18242            try {
18243                userInfo = sUserManager.getUserInfo(userId);
18244            } finally {
18245                Binder.restoreCallingIdentity(token);
18246            }
18247            final boolean b;
18248            if (userInfo != null && userInfo.isManagedProfile()) {
18249                b = true;
18250            } else {
18251                b = false;
18252            }
18253            mUserNeedsBadging.put(userId, b);
18254            return b;
18255        }
18256        return mUserNeedsBadging.valueAt(index);
18257    }
18258
18259    @Override
18260    public KeySet getKeySetByAlias(String packageName, String alias) {
18261        if (packageName == null || alias == null) {
18262            return null;
18263        }
18264        synchronized(mPackages) {
18265            final PackageParser.Package pkg = mPackages.get(packageName);
18266            if (pkg == null) {
18267                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18268                throw new IllegalArgumentException("Unknown package: " + packageName);
18269            }
18270            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18271            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18272        }
18273    }
18274
18275    @Override
18276    public KeySet getSigningKeySet(String packageName) {
18277        if (packageName == null) {
18278            return null;
18279        }
18280        synchronized(mPackages) {
18281            final PackageParser.Package pkg = mPackages.get(packageName);
18282            if (pkg == null) {
18283                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18284                throw new IllegalArgumentException("Unknown package: " + packageName);
18285            }
18286            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18287                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18288                throw new SecurityException("May not access signing KeySet of other apps.");
18289            }
18290            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18291            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18292        }
18293    }
18294
18295    @Override
18296    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18297        if (packageName == null || ks == null) {
18298            return false;
18299        }
18300        synchronized(mPackages) {
18301            final PackageParser.Package pkg = mPackages.get(packageName);
18302            if (pkg == null) {
18303                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18304                throw new IllegalArgumentException("Unknown package: " + packageName);
18305            }
18306            IBinder ksh = ks.getToken();
18307            if (ksh instanceof KeySetHandle) {
18308                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18309                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18310            }
18311            return false;
18312        }
18313    }
18314
18315    @Override
18316    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18317        if (packageName == null || ks == null) {
18318            return false;
18319        }
18320        synchronized(mPackages) {
18321            final PackageParser.Package pkg = mPackages.get(packageName);
18322            if (pkg == null) {
18323                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18324                throw new IllegalArgumentException("Unknown package: " + packageName);
18325            }
18326            IBinder ksh = ks.getToken();
18327            if (ksh instanceof KeySetHandle) {
18328                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18329                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18330            }
18331            return false;
18332        }
18333    }
18334
18335    private void deletePackageIfUnusedLPr(final String packageName) {
18336        PackageSetting ps = mSettings.mPackages.get(packageName);
18337        if (ps == null) {
18338            return;
18339        }
18340        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18341            // TODO Implement atomic delete if package is unused
18342            // It is currently possible that the package will be deleted even if it is installed
18343            // after this method returns.
18344            mHandler.post(new Runnable() {
18345                public void run() {
18346                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18347                }
18348            });
18349        }
18350    }
18351
18352    /**
18353     * Check and throw if the given before/after packages would be considered a
18354     * downgrade.
18355     */
18356    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18357            throws PackageManagerException {
18358        if (after.versionCode < before.mVersionCode) {
18359            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18360                    "Update version code " + after.versionCode + " is older than current "
18361                    + before.mVersionCode);
18362        } else if (after.versionCode == before.mVersionCode) {
18363            if (after.baseRevisionCode < before.baseRevisionCode) {
18364                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18365                        "Update base revision code " + after.baseRevisionCode
18366                        + " is older than current " + before.baseRevisionCode);
18367            }
18368
18369            if (!ArrayUtils.isEmpty(after.splitNames)) {
18370                for (int i = 0; i < after.splitNames.length; i++) {
18371                    final String splitName = after.splitNames[i];
18372                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18373                    if (j != -1) {
18374                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18375                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18376                                    "Update split " + splitName + " revision code "
18377                                    + after.splitRevisionCodes[i] + " is older than current "
18378                                    + before.splitRevisionCodes[j]);
18379                        }
18380                    }
18381                }
18382            }
18383        }
18384    }
18385
18386    private static class MoveCallbacks extends Handler {
18387        private static final int MSG_CREATED = 1;
18388        private static final int MSG_STATUS_CHANGED = 2;
18389
18390        private final RemoteCallbackList<IPackageMoveObserver>
18391                mCallbacks = new RemoteCallbackList<>();
18392
18393        private final SparseIntArray mLastStatus = new SparseIntArray();
18394
18395        public MoveCallbacks(Looper looper) {
18396            super(looper);
18397        }
18398
18399        public void register(IPackageMoveObserver callback) {
18400            mCallbacks.register(callback);
18401        }
18402
18403        public void unregister(IPackageMoveObserver callback) {
18404            mCallbacks.unregister(callback);
18405        }
18406
18407        @Override
18408        public void handleMessage(Message msg) {
18409            final SomeArgs args = (SomeArgs) msg.obj;
18410            final int n = mCallbacks.beginBroadcast();
18411            for (int i = 0; i < n; i++) {
18412                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18413                try {
18414                    invokeCallback(callback, msg.what, args);
18415                } catch (RemoteException ignored) {
18416                }
18417            }
18418            mCallbacks.finishBroadcast();
18419            args.recycle();
18420        }
18421
18422        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18423                throws RemoteException {
18424            switch (what) {
18425                case MSG_CREATED: {
18426                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18427                    break;
18428                }
18429                case MSG_STATUS_CHANGED: {
18430                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18431                    break;
18432                }
18433            }
18434        }
18435
18436        private void notifyCreated(int moveId, Bundle extras) {
18437            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18438
18439            final SomeArgs args = SomeArgs.obtain();
18440            args.argi1 = moveId;
18441            args.arg2 = extras;
18442            obtainMessage(MSG_CREATED, args).sendToTarget();
18443        }
18444
18445        private void notifyStatusChanged(int moveId, int status) {
18446            notifyStatusChanged(moveId, status, -1);
18447        }
18448
18449        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18450            Slog.v(TAG, "Move " + moveId + " status " + status);
18451
18452            final SomeArgs args = SomeArgs.obtain();
18453            args.argi1 = moveId;
18454            args.argi2 = status;
18455            args.arg3 = estMillis;
18456            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18457
18458            synchronized (mLastStatus) {
18459                mLastStatus.put(moveId, status);
18460            }
18461        }
18462    }
18463
18464    private final static class OnPermissionChangeListeners extends Handler {
18465        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18466
18467        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18468                new RemoteCallbackList<>();
18469
18470        public OnPermissionChangeListeners(Looper looper) {
18471            super(looper);
18472        }
18473
18474        @Override
18475        public void handleMessage(Message msg) {
18476            switch (msg.what) {
18477                case MSG_ON_PERMISSIONS_CHANGED: {
18478                    final int uid = msg.arg1;
18479                    handleOnPermissionsChanged(uid);
18480                } break;
18481            }
18482        }
18483
18484        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18485            mPermissionListeners.register(listener);
18486
18487        }
18488
18489        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18490            mPermissionListeners.unregister(listener);
18491        }
18492
18493        public void onPermissionsChanged(int uid) {
18494            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18495                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18496            }
18497        }
18498
18499        private void handleOnPermissionsChanged(int uid) {
18500            final int count = mPermissionListeners.beginBroadcast();
18501            try {
18502                for (int i = 0; i < count; i++) {
18503                    IOnPermissionsChangeListener callback = mPermissionListeners
18504                            .getBroadcastItem(i);
18505                    try {
18506                        callback.onPermissionsChanged(uid);
18507                    } catch (RemoteException e) {
18508                        Log.e(TAG, "Permission listener is dead", e);
18509                    }
18510                }
18511            } finally {
18512                mPermissionListeners.finishBroadcast();
18513            }
18514        }
18515    }
18516
18517    private class PackageManagerInternalImpl extends PackageManagerInternal {
18518        @Override
18519        public void setLocationPackagesProvider(PackagesProvider provider) {
18520            synchronized (mPackages) {
18521                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18522            }
18523        }
18524
18525        @Override
18526        public void setImePackagesProvider(PackagesProvider provider) {
18527            synchronized (mPackages) {
18528                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18529            }
18530        }
18531
18532        @Override
18533        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18534            synchronized (mPackages) {
18535                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18536            }
18537        }
18538
18539        @Override
18540        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18541            synchronized (mPackages) {
18542                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18543            }
18544        }
18545
18546        @Override
18547        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18548            synchronized (mPackages) {
18549                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18550            }
18551        }
18552
18553        @Override
18554        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18555            synchronized (mPackages) {
18556                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18557            }
18558        }
18559
18560        @Override
18561        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18562            synchronized (mPackages) {
18563                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18564            }
18565        }
18566
18567        @Override
18568        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18569            synchronized (mPackages) {
18570                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18571                        packageName, userId);
18572            }
18573        }
18574
18575        @Override
18576        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18577            synchronized (mPackages) {
18578                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18579                        packageName, userId);
18580            }
18581        }
18582
18583        @Override
18584        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18585            synchronized (mPackages) {
18586                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18587                        packageName, userId);
18588            }
18589        }
18590
18591        @Override
18592        public void setKeepUninstalledPackages(final List<String> packageList) {
18593            Preconditions.checkNotNull(packageList);
18594            List<String> removedFromList = null;
18595            synchronized (mPackages) {
18596                if (mKeepUninstalledPackages != null) {
18597                    final int packagesCount = mKeepUninstalledPackages.size();
18598                    for (int i = 0; i < packagesCount; i++) {
18599                        String oldPackage = mKeepUninstalledPackages.get(i);
18600                        if (packageList != null && packageList.contains(oldPackage)) {
18601                            continue;
18602                        }
18603                        if (removedFromList == null) {
18604                            removedFromList = new ArrayList<>();
18605                        }
18606                        removedFromList.add(oldPackage);
18607                    }
18608                }
18609                mKeepUninstalledPackages = new ArrayList<>(packageList);
18610                if (removedFromList != null) {
18611                    final int removedCount = removedFromList.size();
18612                    for (int i = 0; i < removedCount; i++) {
18613                        deletePackageIfUnusedLPr(removedFromList.get(i));
18614                    }
18615                }
18616            }
18617        }
18618
18619        @Override
18620        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18621            synchronized (mPackages) {
18622                // If we do not support permission review, done.
18623                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18624                    return false;
18625                }
18626
18627                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18628                if (packageSetting == null) {
18629                    return false;
18630                }
18631
18632                // Permission review applies only to apps not supporting the new permission model.
18633                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18634                    return false;
18635                }
18636
18637                // Legacy apps have the permission and get user consent on launch.
18638                PermissionsState permissionsState = packageSetting.getPermissionsState();
18639                return permissionsState.isPermissionReviewRequired(userId);
18640            }
18641        }
18642    }
18643
18644    @Override
18645    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18646        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18647        synchronized (mPackages) {
18648            final long identity = Binder.clearCallingIdentity();
18649            try {
18650                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18651                        packageNames, userId);
18652            } finally {
18653                Binder.restoreCallingIdentity(identity);
18654            }
18655        }
18656    }
18657
18658    private static void enforceSystemOrPhoneCaller(String tag) {
18659        int callingUid = Binder.getCallingUid();
18660        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18661            throw new SecurityException(
18662                    "Cannot call " + tag + " from UID " + callingUid);
18663        }
18664    }
18665
18666    boolean isHistoricalPackageUsageAvailable() {
18667        return mPackageUsage.isHistoricalPackageUsageAvailable();
18668    }
18669}
18670