PackageManagerService.java revision 354cd3ce2213a1032d9138ea6fa1420f055ab08c
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 FeatureInfo[] getSystemAvailableFeatures() {
3431        Collection<FeatureInfo> featSet;
3432        synchronized (mPackages) {
3433            featSet = mAvailableFeatures.values();
3434            int size = featSet.size();
3435            if (size > 0) {
3436                FeatureInfo[] features = new FeatureInfo[size+1];
3437                featSet.toArray(features);
3438                FeatureInfo fi = new FeatureInfo();
3439                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3440                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3441                features[size] = fi;
3442                return features;
3443            }
3444        }
3445        return null;
3446    }
3447
3448    @Override
3449    public boolean hasSystemFeature(String name) {
3450        synchronized (mPackages) {
3451            return mAvailableFeatures.containsKey(name);
3452        }
3453    }
3454
3455    @Override
3456    public int checkPermission(String permName, String pkgName, int userId) {
3457        if (!sUserManager.exists(userId)) {
3458            return PackageManager.PERMISSION_DENIED;
3459        }
3460
3461        synchronized (mPackages) {
3462            final PackageParser.Package p = mPackages.get(pkgName);
3463            if (p != null && p.mExtras != null) {
3464                final PackageSetting ps = (PackageSetting) p.mExtras;
3465                final PermissionsState permissionsState = ps.getPermissionsState();
3466                if (permissionsState.hasPermission(permName, userId)) {
3467                    return PackageManager.PERMISSION_GRANTED;
3468                }
3469                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3470                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3471                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3472                    return PackageManager.PERMISSION_GRANTED;
3473                }
3474            }
3475        }
3476
3477        return PackageManager.PERMISSION_DENIED;
3478    }
3479
3480    @Override
3481    public int checkUidPermission(String permName, int uid) {
3482        final int userId = UserHandle.getUserId(uid);
3483
3484        if (!sUserManager.exists(userId)) {
3485            return PackageManager.PERMISSION_DENIED;
3486        }
3487
3488        synchronized (mPackages) {
3489            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3490            if (obj != null) {
3491                final SettingBase ps = (SettingBase) obj;
3492                final PermissionsState permissionsState = ps.getPermissionsState();
3493                if (permissionsState.hasPermission(permName, userId)) {
3494                    return PackageManager.PERMISSION_GRANTED;
3495                }
3496                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3497                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3498                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3499                    return PackageManager.PERMISSION_GRANTED;
3500                }
3501            } else {
3502                ArraySet<String> perms = mSystemPermissions.get(uid);
3503                if (perms != null) {
3504                    if (perms.contains(permName)) {
3505                        return PackageManager.PERMISSION_GRANTED;
3506                    }
3507                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3508                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3509                        return PackageManager.PERMISSION_GRANTED;
3510                    }
3511                }
3512            }
3513        }
3514
3515        return PackageManager.PERMISSION_DENIED;
3516    }
3517
3518    @Override
3519    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3520        if (UserHandle.getCallingUserId() != userId) {
3521            mContext.enforceCallingPermission(
3522                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3523                    "isPermissionRevokedByPolicy for user " + userId);
3524        }
3525
3526        if (checkPermission(permission, packageName, userId)
3527                == PackageManager.PERMISSION_GRANTED) {
3528            return false;
3529        }
3530
3531        final long identity = Binder.clearCallingIdentity();
3532        try {
3533            final int flags = getPermissionFlags(permission, packageName, userId);
3534            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3535        } finally {
3536            Binder.restoreCallingIdentity(identity);
3537        }
3538    }
3539
3540    @Override
3541    public String getPermissionControllerPackageName() {
3542        synchronized (mPackages) {
3543            return mRequiredInstallerPackage;
3544        }
3545    }
3546
3547    /**
3548     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3549     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3550     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3551     * @param message the message to log on security exception
3552     */
3553    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3554            boolean checkShell, String message) {
3555        if (userId < 0) {
3556            throw new IllegalArgumentException("Invalid userId " + userId);
3557        }
3558        if (checkShell) {
3559            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3560        }
3561        if (userId == UserHandle.getUserId(callingUid)) return;
3562        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3563            if (requireFullPermission) {
3564                mContext.enforceCallingOrSelfPermission(
3565                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3566            } else {
3567                try {
3568                    mContext.enforceCallingOrSelfPermission(
3569                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3570                } catch (SecurityException se) {
3571                    mContext.enforceCallingOrSelfPermission(
3572                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3573                }
3574            }
3575        }
3576    }
3577
3578    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3579        if (callingUid == Process.SHELL_UID) {
3580            if (userHandle >= 0
3581                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3582                throw new SecurityException("Shell does not have permission to access user "
3583                        + userHandle);
3584            } else if (userHandle < 0) {
3585                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3586                        + Debug.getCallers(3));
3587            }
3588        }
3589    }
3590
3591    private BasePermission findPermissionTreeLP(String permName) {
3592        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3593            if (permName.startsWith(bp.name) &&
3594                    permName.length() > bp.name.length() &&
3595                    permName.charAt(bp.name.length()) == '.') {
3596                return bp;
3597            }
3598        }
3599        return null;
3600    }
3601
3602    private BasePermission checkPermissionTreeLP(String permName) {
3603        if (permName != null) {
3604            BasePermission bp = findPermissionTreeLP(permName);
3605            if (bp != null) {
3606                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3607                    return bp;
3608                }
3609                throw new SecurityException("Calling uid "
3610                        + Binder.getCallingUid()
3611                        + " is not allowed to add to permission tree "
3612                        + bp.name + " owned by uid " + bp.uid);
3613            }
3614        }
3615        throw new SecurityException("No permission tree found for " + permName);
3616    }
3617
3618    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3619        if (s1 == null) {
3620            return s2 == null;
3621        }
3622        if (s2 == null) {
3623            return false;
3624        }
3625        if (s1.getClass() != s2.getClass()) {
3626            return false;
3627        }
3628        return s1.equals(s2);
3629    }
3630
3631    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3632        if (pi1.icon != pi2.icon) return false;
3633        if (pi1.logo != pi2.logo) return false;
3634        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3635        if (!compareStrings(pi1.name, pi2.name)) return false;
3636        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3637        // We'll take care of setting this one.
3638        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3639        // These are not currently stored in settings.
3640        //if (!compareStrings(pi1.group, pi2.group)) return false;
3641        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3642        //if (pi1.labelRes != pi2.labelRes) return false;
3643        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3644        return true;
3645    }
3646
3647    int permissionInfoFootprint(PermissionInfo info) {
3648        int size = info.name.length();
3649        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3650        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3651        return size;
3652    }
3653
3654    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3655        int size = 0;
3656        for (BasePermission perm : mSettings.mPermissions.values()) {
3657            if (perm.uid == tree.uid) {
3658                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3659            }
3660        }
3661        return size;
3662    }
3663
3664    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3665        // We calculate the max size of permissions defined by this uid and throw
3666        // if that plus the size of 'info' would exceed our stated maximum.
3667        if (tree.uid != Process.SYSTEM_UID) {
3668            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3669            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3670                throw new SecurityException("Permission tree size cap exceeded");
3671            }
3672        }
3673    }
3674
3675    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3676        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3677            throw new SecurityException("Label must be specified in permission");
3678        }
3679        BasePermission tree = checkPermissionTreeLP(info.name);
3680        BasePermission bp = mSettings.mPermissions.get(info.name);
3681        boolean added = bp == null;
3682        boolean changed = true;
3683        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3684        if (added) {
3685            enforcePermissionCapLocked(info, tree);
3686            bp = new BasePermission(info.name, tree.sourcePackage,
3687                    BasePermission.TYPE_DYNAMIC);
3688        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3689            throw new SecurityException(
3690                    "Not allowed to modify non-dynamic permission "
3691                    + info.name);
3692        } else {
3693            if (bp.protectionLevel == fixedLevel
3694                    && bp.perm.owner.equals(tree.perm.owner)
3695                    && bp.uid == tree.uid
3696                    && comparePermissionInfos(bp.perm.info, info)) {
3697                changed = false;
3698            }
3699        }
3700        bp.protectionLevel = fixedLevel;
3701        info = new PermissionInfo(info);
3702        info.protectionLevel = fixedLevel;
3703        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3704        bp.perm.info.packageName = tree.perm.info.packageName;
3705        bp.uid = tree.uid;
3706        if (added) {
3707            mSettings.mPermissions.put(info.name, bp);
3708        }
3709        if (changed) {
3710            if (!async) {
3711                mSettings.writeLPr();
3712            } else {
3713                scheduleWriteSettingsLocked();
3714            }
3715        }
3716        return added;
3717    }
3718
3719    @Override
3720    public boolean addPermission(PermissionInfo info) {
3721        synchronized (mPackages) {
3722            return addPermissionLocked(info, false);
3723        }
3724    }
3725
3726    @Override
3727    public boolean addPermissionAsync(PermissionInfo info) {
3728        synchronized (mPackages) {
3729            return addPermissionLocked(info, true);
3730        }
3731    }
3732
3733    @Override
3734    public void removePermission(String name) {
3735        synchronized (mPackages) {
3736            checkPermissionTreeLP(name);
3737            BasePermission bp = mSettings.mPermissions.get(name);
3738            if (bp != null) {
3739                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3740                    throw new SecurityException(
3741                            "Not allowed to modify non-dynamic permission "
3742                            + name);
3743                }
3744                mSettings.mPermissions.remove(name);
3745                mSettings.writeLPr();
3746            }
3747        }
3748    }
3749
3750    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3751            BasePermission bp) {
3752        int index = pkg.requestedPermissions.indexOf(bp.name);
3753        if (index == -1) {
3754            throw new SecurityException("Package " + pkg.packageName
3755                    + " has not requested permission " + bp.name);
3756        }
3757        if (!bp.isRuntime() && !bp.isDevelopment()) {
3758            throw new SecurityException("Permission " + bp.name
3759                    + " is not a changeable permission type");
3760        }
3761    }
3762
3763    @Override
3764    public void grantRuntimePermission(String packageName, String name, final int userId) {
3765        if (!sUserManager.exists(userId)) {
3766            Log.e(TAG, "No such user:" + userId);
3767            return;
3768        }
3769
3770        mContext.enforceCallingOrSelfPermission(
3771                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3772                "grantRuntimePermission");
3773
3774        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3775                "grantRuntimePermission");
3776
3777        final int uid;
3778        final SettingBase sb;
3779
3780        synchronized (mPackages) {
3781            final PackageParser.Package pkg = mPackages.get(packageName);
3782            if (pkg == null) {
3783                throw new IllegalArgumentException("Unknown package: " + packageName);
3784            }
3785
3786            final BasePermission bp = mSettings.mPermissions.get(name);
3787            if (bp == null) {
3788                throw new IllegalArgumentException("Unknown permission: " + name);
3789            }
3790
3791            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3792
3793            // If a permission review is required for legacy apps we represent
3794            // their permissions as always granted runtime ones since we need
3795            // to keep the review required permission flag per user while an
3796            // install permission's state is shared across all users.
3797            if (Build.PERMISSIONS_REVIEW_REQUIRED
3798                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3799                    && bp.isRuntime()) {
3800                return;
3801            }
3802
3803            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3804            sb = (SettingBase) pkg.mExtras;
3805            if (sb == null) {
3806                throw new IllegalArgumentException("Unknown package: " + packageName);
3807            }
3808
3809            final PermissionsState permissionsState = sb.getPermissionsState();
3810
3811            final int flags = permissionsState.getPermissionFlags(name, userId);
3812            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3813                throw new SecurityException("Cannot grant system fixed permission "
3814                        + name + " for package " + packageName);
3815            }
3816
3817            if (bp.isDevelopment()) {
3818                // Development permissions must be handled specially, since they are not
3819                // normal runtime permissions.  For now they apply to all users.
3820                if (permissionsState.grantInstallPermission(bp) !=
3821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3822                    scheduleWriteSettingsLocked();
3823                }
3824                return;
3825            }
3826
3827            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3828                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3829                return;
3830            }
3831
3832            final int result = permissionsState.grantRuntimePermission(bp, userId);
3833            switch (result) {
3834                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3835                    return;
3836                }
3837
3838                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3839                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3840                    mHandler.post(new Runnable() {
3841                        @Override
3842                        public void run() {
3843                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3844                        }
3845                    });
3846                }
3847                break;
3848            }
3849
3850            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3851
3852            // Not critical if that is lost - app has to request again.
3853            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3854        }
3855
3856        // Only need to do this if user is initialized. Otherwise it's a new user
3857        // and there are no processes running as the user yet and there's no need
3858        // to make an expensive call to remount processes for the changed permissions.
3859        if (READ_EXTERNAL_STORAGE.equals(name)
3860                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3861            final long token = Binder.clearCallingIdentity();
3862            try {
3863                if (sUserManager.isInitialized(userId)) {
3864                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3865                            MountServiceInternal.class);
3866                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3867                }
3868            } finally {
3869                Binder.restoreCallingIdentity(token);
3870            }
3871        }
3872    }
3873
3874    @Override
3875    public void revokeRuntimePermission(String packageName, String name, int userId) {
3876        if (!sUserManager.exists(userId)) {
3877            Log.e(TAG, "No such user:" + userId);
3878            return;
3879        }
3880
3881        mContext.enforceCallingOrSelfPermission(
3882                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3883                "revokeRuntimePermission");
3884
3885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3886                "revokeRuntimePermission");
3887
3888        final int appId;
3889
3890        synchronized (mPackages) {
3891            final PackageParser.Package pkg = mPackages.get(packageName);
3892            if (pkg == null) {
3893                throw new IllegalArgumentException("Unknown package: " + packageName);
3894            }
3895
3896            final BasePermission bp = mSettings.mPermissions.get(name);
3897            if (bp == null) {
3898                throw new IllegalArgumentException("Unknown permission: " + name);
3899            }
3900
3901            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3902
3903            // If a permission review is required for legacy apps we represent
3904            // their permissions as always granted runtime ones since we need
3905            // to keep the review required permission flag per user while an
3906            // install permission's state is shared across all users.
3907            if (Build.PERMISSIONS_REVIEW_REQUIRED
3908                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3909                    && bp.isRuntime()) {
3910                return;
3911            }
3912
3913            SettingBase sb = (SettingBase) pkg.mExtras;
3914            if (sb == null) {
3915                throw new IllegalArgumentException("Unknown package: " + packageName);
3916            }
3917
3918            final PermissionsState permissionsState = sb.getPermissionsState();
3919
3920            final int flags = permissionsState.getPermissionFlags(name, userId);
3921            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3922                throw new SecurityException("Cannot revoke system fixed permission "
3923                        + name + " for package " + packageName);
3924            }
3925
3926            if (bp.isDevelopment()) {
3927                // Development permissions must be handled specially, since they are not
3928                // normal runtime permissions.  For now they apply to all users.
3929                if (permissionsState.revokeInstallPermission(bp) !=
3930                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3931                    scheduleWriteSettingsLocked();
3932                }
3933                return;
3934            }
3935
3936            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3937                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3938                return;
3939            }
3940
3941            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3942
3943            // Critical, after this call app should never have the permission.
3944            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3945
3946            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3947        }
3948
3949        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3950    }
3951
3952    @Override
3953    public void resetRuntimePermissions() {
3954        mContext.enforceCallingOrSelfPermission(
3955                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3956                "revokeRuntimePermission");
3957
3958        int callingUid = Binder.getCallingUid();
3959        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3960            mContext.enforceCallingOrSelfPermission(
3961                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3962                    "resetRuntimePermissions");
3963        }
3964
3965        synchronized (mPackages) {
3966            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3967            for (int userId : UserManagerService.getInstance().getUserIds()) {
3968                final int packageCount = mPackages.size();
3969                for (int i = 0; i < packageCount; i++) {
3970                    PackageParser.Package pkg = mPackages.valueAt(i);
3971                    if (!(pkg.mExtras instanceof PackageSetting)) {
3972                        continue;
3973                    }
3974                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3975                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3976                }
3977            }
3978        }
3979    }
3980
3981    @Override
3982    public int getPermissionFlags(String name, String packageName, int userId) {
3983        if (!sUserManager.exists(userId)) {
3984            return 0;
3985        }
3986
3987        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3988
3989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3990                "getPermissionFlags");
3991
3992        synchronized (mPackages) {
3993            final PackageParser.Package pkg = mPackages.get(packageName);
3994            if (pkg == null) {
3995                throw new IllegalArgumentException("Unknown package: " + packageName);
3996            }
3997
3998            final BasePermission bp = mSettings.mPermissions.get(name);
3999            if (bp == null) {
4000                throw new IllegalArgumentException("Unknown permission: " + name);
4001            }
4002
4003            SettingBase sb = (SettingBase) pkg.mExtras;
4004            if (sb == null) {
4005                throw new IllegalArgumentException("Unknown package: " + packageName);
4006            }
4007
4008            PermissionsState permissionsState = sb.getPermissionsState();
4009            return permissionsState.getPermissionFlags(name, userId);
4010        }
4011    }
4012
4013    @Override
4014    public void updatePermissionFlags(String name, String packageName, int flagMask,
4015            int flagValues, int userId) {
4016        if (!sUserManager.exists(userId)) {
4017            return;
4018        }
4019
4020        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4021
4022        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4023                "updatePermissionFlags");
4024
4025        // Only the system can change these flags and nothing else.
4026        if (getCallingUid() != Process.SYSTEM_UID) {
4027            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4028            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4029            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4030            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4031            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4032        }
4033
4034        synchronized (mPackages) {
4035            final PackageParser.Package pkg = mPackages.get(packageName);
4036            if (pkg == null) {
4037                throw new IllegalArgumentException("Unknown package: " + packageName);
4038            }
4039
4040            final BasePermission bp = mSettings.mPermissions.get(name);
4041            if (bp == null) {
4042                throw new IllegalArgumentException("Unknown permission: " + name);
4043            }
4044
4045            SettingBase sb = (SettingBase) pkg.mExtras;
4046            if (sb == null) {
4047                throw new IllegalArgumentException("Unknown package: " + packageName);
4048            }
4049
4050            PermissionsState permissionsState = sb.getPermissionsState();
4051
4052            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4053
4054            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4055                // Install and runtime permissions are stored in different places,
4056                // so figure out what permission changed and persist the change.
4057                if (permissionsState.getInstallPermissionState(name) != null) {
4058                    scheduleWriteSettingsLocked();
4059                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4060                        || hadState) {
4061                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4062                }
4063            }
4064        }
4065    }
4066
4067    /**
4068     * Update the permission flags for all packages and runtime permissions of a user in order
4069     * to allow device or profile owner to remove POLICY_FIXED.
4070     */
4071    @Override
4072    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4073        if (!sUserManager.exists(userId)) {
4074            return;
4075        }
4076
4077        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4078
4079        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4080                "updatePermissionFlagsForAllApps");
4081
4082        // Only the system can change system fixed flags.
4083        if (getCallingUid() != Process.SYSTEM_UID) {
4084            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4085            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4086        }
4087
4088        synchronized (mPackages) {
4089            boolean changed = false;
4090            final int packageCount = mPackages.size();
4091            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4092                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4093                SettingBase sb = (SettingBase) pkg.mExtras;
4094                if (sb == null) {
4095                    continue;
4096                }
4097                PermissionsState permissionsState = sb.getPermissionsState();
4098                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4099                        userId, flagMask, flagValues);
4100            }
4101            if (changed) {
4102                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4103            }
4104        }
4105    }
4106
4107    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4108        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4109                != PackageManager.PERMISSION_GRANTED
4110            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4111                != PackageManager.PERMISSION_GRANTED) {
4112            throw new SecurityException(message + " requires "
4113                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4114                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4115        }
4116    }
4117
4118    @Override
4119    public boolean shouldShowRequestPermissionRationale(String permissionName,
4120            String packageName, int userId) {
4121        if (UserHandle.getCallingUserId() != userId) {
4122            mContext.enforceCallingPermission(
4123                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4124                    "canShowRequestPermissionRationale for user " + userId);
4125        }
4126
4127        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4128        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4129            return false;
4130        }
4131
4132        if (checkPermission(permissionName, packageName, userId)
4133                == PackageManager.PERMISSION_GRANTED) {
4134            return false;
4135        }
4136
4137        final int flags;
4138
4139        final long identity = Binder.clearCallingIdentity();
4140        try {
4141            flags = getPermissionFlags(permissionName,
4142                    packageName, userId);
4143        } finally {
4144            Binder.restoreCallingIdentity(identity);
4145        }
4146
4147        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4148                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4149                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4150
4151        if ((flags & fixedFlags) != 0) {
4152            return false;
4153        }
4154
4155        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4156    }
4157
4158    @Override
4159    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4160        mContext.enforceCallingOrSelfPermission(
4161                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4162                "addOnPermissionsChangeListener");
4163
4164        synchronized (mPackages) {
4165            mOnPermissionChangeListeners.addListenerLocked(listener);
4166        }
4167    }
4168
4169    @Override
4170    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4171        synchronized (mPackages) {
4172            mOnPermissionChangeListeners.removeListenerLocked(listener);
4173        }
4174    }
4175
4176    @Override
4177    public boolean isProtectedBroadcast(String actionName) {
4178        synchronized (mPackages) {
4179            if (mProtectedBroadcasts.contains(actionName)) {
4180                return true;
4181            } else if (actionName != null) {
4182                // TODO: remove these terrible hacks
4183                if (actionName.startsWith("android.net.netmon.lingerExpired")
4184                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4185                    return true;
4186                }
4187            }
4188        }
4189        return false;
4190    }
4191
4192    @Override
4193    public int checkSignatures(String pkg1, String pkg2) {
4194        synchronized (mPackages) {
4195            final PackageParser.Package p1 = mPackages.get(pkg1);
4196            final PackageParser.Package p2 = mPackages.get(pkg2);
4197            if (p1 == null || p1.mExtras == null
4198                    || p2 == null || p2.mExtras == null) {
4199                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4200            }
4201            return compareSignatures(p1.mSignatures, p2.mSignatures);
4202        }
4203    }
4204
4205    @Override
4206    public int checkUidSignatures(int uid1, int uid2) {
4207        // Map to base uids.
4208        uid1 = UserHandle.getAppId(uid1);
4209        uid2 = UserHandle.getAppId(uid2);
4210        // reader
4211        synchronized (mPackages) {
4212            Signature[] s1;
4213            Signature[] s2;
4214            Object obj = mSettings.getUserIdLPr(uid1);
4215            if (obj != null) {
4216                if (obj instanceof SharedUserSetting) {
4217                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4218                } else if (obj instanceof PackageSetting) {
4219                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4220                } else {
4221                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4222                }
4223            } else {
4224                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4225            }
4226            obj = mSettings.getUserIdLPr(uid2);
4227            if (obj != null) {
4228                if (obj instanceof SharedUserSetting) {
4229                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4230                } else if (obj instanceof PackageSetting) {
4231                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4232                } else {
4233                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4234                }
4235            } else {
4236                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4237            }
4238            return compareSignatures(s1, s2);
4239        }
4240    }
4241
4242    private void killUid(int appId, int userId, String reason) {
4243        final long identity = Binder.clearCallingIdentity();
4244        try {
4245            IActivityManager am = ActivityManagerNative.getDefault();
4246            if (am != null) {
4247                try {
4248                    am.killUid(appId, userId, reason);
4249                } catch (RemoteException e) {
4250                    /* ignore - same process */
4251                }
4252            }
4253        } finally {
4254            Binder.restoreCallingIdentity(identity);
4255        }
4256    }
4257
4258    /**
4259     * Compares two sets of signatures. Returns:
4260     * <br />
4261     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4262     * <br />
4263     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4264     * <br />
4265     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4266     * <br />
4267     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4268     * <br />
4269     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4270     */
4271    static int compareSignatures(Signature[] s1, Signature[] s2) {
4272        if (s1 == null) {
4273            return s2 == null
4274                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4275                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4276        }
4277
4278        if (s2 == null) {
4279            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4280        }
4281
4282        if (s1.length != s2.length) {
4283            return PackageManager.SIGNATURE_NO_MATCH;
4284        }
4285
4286        // Since both signature sets are of size 1, we can compare without HashSets.
4287        if (s1.length == 1) {
4288            return s1[0].equals(s2[0]) ?
4289                    PackageManager.SIGNATURE_MATCH :
4290                    PackageManager.SIGNATURE_NO_MATCH;
4291        }
4292
4293        ArraySet<Signature> set1 = new ArraySet<Signature>();
4294        for (Signature sig : s1) {
4295            set1.add(sig);
4296        }
4297        ArraySet<Signature> set2 = new ArraySet<Signature>();
4298        for (Signature sig : s2) {
4299            set2.add(sig);
4300        }
4301        // Make sure s2 contains all signatures in s1.
4302        if (set1.equals(set2)) {
4303            return PackageManager.SIGNATURE_MATCH;
4304        }
4305        return PackageManager.SIGNATURE_NO_MATCH;
4306    }
4307
4308    /**
4309     * If the database version for this type of package (internal storage or
4310     * external storage) is less than the version where package signatures
4311     * were updated, return true.
4312     */
4313    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4314        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4315        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4316    }
4317
4318    /**
4319     * Used for backward compatibility to make sure any packages with
4320     * certificate chains get upgraded to the new style. {@code existingSigs}
4321     * will be in the old format (since they were stored on disk from before the
4322     * system upgrade) and {@code scannedSigs} will be in the newer format.
4323     */
4324    private int compareSignaturesCompat(PackageSignatures existingSigs,
4325            PackageParser.Package scannedPkg) {
4326        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4327            return PackageManager.SIGNATURE_NO_MATCH;
4328        }
4329
4330        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4331        for (Signature sig : existingSigs.mSignatures) {
4332            existingSet.add(sig);
4333        }
4334        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4335        for (Signature sig : scannedPkg.mSignatures) {
4336            try {
4337                Signature[] chainSignatures = sig.getChainSignatures();
4338                for (Signature chainSig : chainSignatures) {
4339                    scannedCompatSet.add(chainSig);
4340                }
4341            } catch (CertificateEncodingException e) {
4342                scannedCompatSet.add(sig);
4343            }
4344        }
4345        /*
4346         * Make sure the expanded scanned set contains all signatures in the
4347         * existing one.
4348         */
4349        if (scannedCompatSet.equals(existingSet)) {
4350            // Migrate the old signatures to the new scheme.
4351            existingSigs.assignSignatures(scannedPkg.mSignatures);
4352            // The new KeySets will be re-added later in the scanning process.
4353            synchronized (mPackages) {
4354                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4355            }
4356            return PackageManager.SIGNATURE_MATCH;
4357        }
4358        return PackageManager.SIGNATURE_NO_MATCH;
4359    }
4360
4361    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4362        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4363        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4364    }
4365
4366    private int compareSignaturesRecover(PackageSignatures existingSigs,
4367            PackageParser.Package scannedPkg) {
4368        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4369            return PackageManager.SIGNATURE_NO_MATCH;
4370        }
4371
4372        String msg = null;
4373        try {
4374            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4375                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4376                        + scannedPkg.packageName);
4377                return PackageManager.SIGNATURE_MATCH;
4378            }
4379        } catch (CertificateException e) {
4380            msg = e.getMessage();
4381        }
4382
4383        logCriticalInfo(Log.INFO,
4384                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4385        return PackageManager.SIGNATURE_NO_MATCH;
4386    }
4387
4388    @Override
4389    public String[] getPackagesForUid(int uid) {
4390        uid = UserHandle.getAppId(uid);
4391        // reader
4392        synchronized (mPackages) {
4393            Object obj = mSettings.getUserIdLPr(uid);
4394            if (obj instanceof SharedUserSetting) {
4395                final SharedUserSetting sus = (SharedUserSetting) obj;
4396                final int N = sus.packages.size();
4397                final String[] res = new String[N];
4398                final Iterator<PackageSetting> it = sus.packages.iterator();
4399                int i = 0;
4400                while (it.hasNext()) {
4401                    res[i++] = it.next().name;
4402                }
4403                return res;
4404            } else if (obj instanceof PackageSetting) {
4405                final PackageSetting ps = (PackageSetting) obj;
4406                return new String[] { ps.name };
4407            }
4408        }
4409        return null;
4410    }
4411
4412    @Override
4413    public String getNameForUid(int uid) {
4414        // reader
4415        synchronized (mPackages) {
4416            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4417            if (obj instanceof SharedUserSetting) {
4418                final SharedUserSetting sus = (SharedUserSetting) obj;
4419                return sus.name + ":" + sus.userId;
4420            } else if (obj instanceof PackageSetting) {
4421                final PackageSetting ps = (PackageSetting) obj;
4422                return ps.name;
4423            }
4424        }
4425        return null;
4426    }
4427
4428    @Override
4429    public int getUidForSharedUser(String sharedUserName) {
4430        if(sharedUserName == null) {
4431            return -1;
4432        }
4433        // reader
4434        synchronized (mPackages) {
4435            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4436            if (suid == null) {
4437                return -1;
4438            }
4439            return suid.userId;
4440        }
4441    }
4442
4443    @Override
4444    public int getFlagsForUid(int uid) {
4445        synchronized (mPackages) {
4446            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4447            if (obj instanceof SharedUserSetting) {
4448                final SharedUserSetting sus = (SharedUserSetting) obj;
4449                return sus.pkgFlags;
4450            } else if (obj instanceof PackageSetting) {
4451                final PackageSetting ps = (PackageSetting) obj;
4452                return ps.pkgFlags;
4453            }
4454        }
4455        return 0;
4456    }
4457
4458    @Override
4459    public int getPrivateFlagsForUid(int uid) {
4460        synchronized (mPackages) {
4461            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4462            if (obj instanceof SharedUserSetting) {
4463                final SharedUserSetting sus = (SharedUserSetting) obj;
4464                return sus.pkgPrivateFlags;
4465            } else if (obj instanceof PackageSetting) {
4466                final PackageSetting ps = (PackageSetting) obj;
4467                return ps.pkgPrivateFlags;
4468            }
4469        }
4470        return 0;
4471    }
4472
4473    @Override
4474    public boolean isUidPrivileged(int uid) {
4475        uid = UserHandle.getAppId(uid);
4476        // reader
4477        synchronized (mPackages) {
4478            Object obj = mSettings.getUserIdLPr(uid);
4479            if (obj instanceof SharedUserSetting) {
4480                final SharedUserSetting sus = (SharedUserSetting) obj;
4481                final Iterator<PackageSetting> it = sus.packages.iterator();
4482                while (it.hasNext()) {
4483                    if (it.next().isPrivileged()) {
4484                        return true;
4485                    }
4486                }
4487            } else if (obj instanceof PackageSetting) {
4488                final PackageSetting ps = (PackageSetting) obj;
4489                return ps.isPrivileged();
4490            }
4491        }
4492        return false;
4493    }
4494
4495    @Override
4496    public String[] getAppOpPermissionPackages(String permissionName) {
4497        synchronized (mPackages) {
4498            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4499            if (pkgs == null) {
4500                return null;
4501            }
4502            return pkgs.toArray(new String[pkgs.size()]);
4503        }
4504    }
4505
4506    @Override
4507    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4508            int flags, int userId) {
4509        if (!sUserManager.exists(userId)) return null;
4510        flags = updateFlagsForResolve(flags, userId, intent);
4511        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4512        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4513        final ResolveInfo bestChoice =
4514                chooseBestActivity(intent, resolvedType, flags, query, userId);
4515
4516        if (isEphemeralAllowed(intent, query, userId)) {
4517            final EphemeralResolveInfo ai =
4518                    getEphemeralResolveInfo(intent, resolvedType, userId);
4519            if (ai != null) {
4520                if (DEBUG_EPHEMERAL) {
4521                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4522                }
4523                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4524                bestChoice.ephemeralResolveInfo = ai;
4525            }
4526        }
4527        return bestChoice;
4528    }
4529
4530    @Override
4531    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4532            IntentFilter filter, int match, ComponentName activity) {
4533        final int userId = UserHandle.getCallingUserId();
4534        if (DEBUG_PREFERRED) {
4535            Log.v(TAG, "setLastChosenActivity intent=" + intent
4536                + " resolvedType=" + resolvedType
4537                + " flags=" + flags
4538                + " filter=" + filter
4539                + " match=" + match
4540                + " activity=" + activity);
4541            filter.dump(new PrintStreamPrinter(System.out), "    ");
4542        }
4543        intent.setComponent(null);
4544        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4545        // Find any earlier preferred or last chosen entries and nuke them
4546        findPreferredActivity(intent, resolvedType,
4547                flags, query, 0, false, true, false, userId);
4548        // Add the new activity as the last chosen for this filter
4549        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4550                "Setting last chosen");
4551    }
4552
4553    @Override
4554    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4555        final int userId = UserHandle.getCallingUserId();
4556        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4557        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4558        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4559                false, false, false, userId);
4560    }
4561
4562
4563    private boolean isEphemeralAllowed(
4564            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4565        // Short circuit and return early if possible.
4566        if (DISABLE_EPHEMERAL_APPS) {
4567            return false;
4568        }
4569        final int callingUser = UserHandle.getCallingUserId();
4570        if (callingUser != UserHandle.USER_SYSTEM) {
4571            return false;
4572        }
4573        if (mEphemeralResolverConnection == null) {
4574            return false;
4575        }
4576        if (intent.getComponent() != null) {
4577            return false;
4578        }
4579        if (intent.getPackage() != null) {
4580            return false;
4581        }
4582        final boolean isWebUri = hasWebURI(intent);
4583        if (!isWebUri) {
4584            return false;
4585        }
4586        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4587        synchronized (mPackages) {
4588            final int count = resolvedActivites.size();
4589            for (int n = 0; n < count; n++) {
4590                ResolveInfo info = resolvedActivites.get(n);
4591                String packageName = info.activityInfo.packageName;
4592                PackageSetting ps = mSettings.mPackages.get(packageName);
4593                if (ps != null) {
4594                    // Try to get the status from User settings first
4595                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4596                    int status = (int) (packedStatus >> 32);
4597                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4598                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4599                        if (DEBUG_EPHEMERAL) {
4600                            Slog.v(TAG, "DENY ephemeral apps;"
4601                                + " pkg: " + packageName + ", status: " + status);
4602                        }
4603                        return false;
4604                    }
4605                }
4606            }
4607        }
4608        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4609        return true;
4610    }
4611
4612    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4613            int userId) {
4614        MessageDigest digest = null;
4615        try {
4616            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4617        } catch (NoSuchAlgorithmException e) {
4618            // If we can't create a digest, ignore ephemeral apps.
4619            return null;
4620        }
4621
4622        final byte[] hostBytes = intent.getData().getHost().getBytes();
4623        final byte[] digestBytes = digest.digest(hostBytes);
4624        int shaPrefix =
4625                digestBytes[0] << 24
4626                | digestBytes[1] << 16
4627                | digestBytes[2] << 8
4628                | digestBytes[3] << 0;
4629        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4630                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4631        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4632            // No hash prefix match; there are no ephemeral apps for this domain.
4633            return null;
4634        }
4635        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4636            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4637            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4638                continue;
4639            }
4640            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4641            // No filters; this should never happen.
4642            if (filters.isEmpty()) {
4643                continue;
4644            }
4645            // We have a domain match; resolve the filters to see if anything matches.
4646            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4647            for (int j = filters.size() - 1; j >= 0; --j) {
4648                final EphemeralResolveIntentInfo intentInfo =
4649                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4650                ephemeralResolver.addFilter(intentInfo);
4651            }
4652            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4653                    intent, resolvedType, false /*defaultOnly*/, userId);
4654            if (!matchedResolveInfoList.isEmpty()) {
4655                return matchedResolveInfoList.get(0);
4656            }
4657        }
4658        // Hash or filter mis-match; no ephemeral apps for this domain.
4659        return null;
4660    }
4661
4662    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4663            int flags, List<ResolveInfo> query, int userId) {
4664        if (query != null) {
4665            final int N = query.size();
4666            if (N == 1) {
4667                return query.get(0);
4668            } else if (N > 1) {
4669                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4670                // If there is more than one activity with the same priority,
4671                // then let the user decide between them.
4672                ResolveInfo r0 = query.get(0);
4673                ResolveInfo r1 = query.get(1);
4674                if (DEBUG_INTENT_MATCHING || debug) {
4675                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4676                            + r1.activityInfo.name + "=" + r1.priority);
4677                }
4678                // If the first activity has a higher priority, or a different
4679                // default, then it is always desirable to pick it.
4680                if (r0.priority != r1.priority
4681                        || r0.preferredOrder != r1.preferredOrder
4682                        || r0.isDefault != r1.isDefault) {
4683                    return query.get(0);
4684                }
4685                // If we have saved a preference for a preferred activity for
4686                // this Intent, use that.
4687                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4688                        flags, query, r0.priority, true, false, debug, userId);
4689                if (ri != null) {
4690                    return ri;
4691                }
4692                ri = new ResolveInfo(mResolveInfo);
4693                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4694                ri.activityInfo.applicationInfo = new ApplicationInfo(
4695                        ri.activityInfo.applicationInfo);
4696                if (userId != 0) {
4697                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4698                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4699                }
4700                // Make sure that the resolver is displayable in car mode
4701                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4702                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4703                return ri;
4704            }
4705        }
4706        return null;
4707    }
4708
4709    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4710            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4711        final int N = query.size();
4712        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4713                .get(userId);
4714        // Get the list of persistent preferred activities that handle the intent
4715        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4716        List<PersistentPreferredActivity> pprefs = ppir != null
4717                ? ppir.queryIntent(intent, resolvedType,
4718                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4719                : null;
4720        if (pprefs != null && pprefs.size() > 0) {
4721            final int M = pprefs.size();
4722            for (int i=0; i<M; i++) {
4723                final PersistentPreferredActivity ppa = pprefs.get(i);
4724                if (DEBUG_PREFERRED || debug) {
4725                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4726                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4727                            + "\n  component=" + ppa.mComponent);
4728                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4729                }
4730                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4731                        flags | MATCH_DISABLED_COMPONENTS, userId);
4732                if (DEBUG_PREFERRED || debug) {
4733                    Slog.v(TAG, "Found persistent preferred activity:");
4734                    if (ai != null) {
4735                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4736                    } else {
4737                        Slog.v(TAG, "  null");
4738                    }
4739                }
4740                if (ai == null) {
4741                    // This previously registered persistent preferred activity
4742                    // component is no longer known. Ignore it and do NOT remove it.
4743                    continue;
4744                }
4745                for (int j=0; j<N; j++) {
4746                    final ResolveInfo ri = query.get(j);
4747                    if (!ri.activityInfo.applicationInfo.packageName
4748                            .equals(ai.applicationInfo.packageName)) {
4749                        continue;
4750                    }
4751                    if (!ri.activityInfo.name.equals(ai.name)) {
4752                        continue;
4753                    }
4754                    //  Found a persistent preference that can handle the intent.
4755                    if (DEBUG_PREFERRED || debug) {
4756                        Slog.v(TAG, "Returning persistent preferred activity: " +
4757                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4758                    }
4759                    return ri;
4760                }
4761            }
4762        }
4763        return null;
4764    }
4765
4766    // TODO: handle preferred activities missing while user has amnesia
4767    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4768            List<ResolveInfo> query, int priority, boolean always,
4769            boolean removeMatches, boolean debug, int userId) {
4770        if (!sUserManager.exists(userId)) return null;
4771        flags = updateFlagsForResolve(flags, userId, intent);
4772        // writer
4773        synchronized (mPackages) {
4774            if (intent.getSelector() != null) {
4775                intent = intent.getSelector();
4776            }
4777            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4778
4779            // Try to find a matching persistent preferred activity.
4780            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4781                    debug, userId);
4782
4783            // If a persistent preferred activity matched, use it.
4784            if (pri != null) {
4785                return pri;
4786            }
4787
4788            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4789            // Get the list of preferred activities that handle the intent
4790            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4791            List<PreferredActivity> prefs = pir != null
4792                    ? pir.queryIntent(intent, resolvedType,
4793                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4794                    : null;
4795            if (prefs != null && prefs.size() > 0) {
4796                boolean changed = false;
4797                try {
4798                    // First figure out how good the original match set is.
4799                    // We will only allow preferred activities that came
4800                    // from the same match quality.
4801                    int match = 0;
4802
4803                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4804
4805                    final int N = query.size();
4806                    for (int j=0; j<N; j++) {
4807                        final ResolveInfo ri = query.get(j);
4808                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4809                                + ": 0x" + Integer.toHexString(match));
4810                        if (ri.match > match) {
4811                            match = ri.match;
4812                        }
4813                    }
4814
4815                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4816                            + Integer.toHexString(match));
4817
4818                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4819                    final int M = prefs.size();
4820                    for (int i=0; i<M; i++) {
4821                        final PreferredActivity pa = prefs.get(i);
4822                        if (DEBUG_PREFERRED || debug) {
4823                            Slog.v(TAG, "Checking PreferredActivity ds="
4824                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4825                                    + "\n  component=" + pa.mPref.mComponent);
4826                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4827                        }
4828                        if (pa.mPref.mMatch != match) {
4829                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4830                                    + Integer.toHexString(pa.mPref.mMatch));
4831                            continue;
4832                        }
4833                        // If it's not an "always" type preferred activity and that's what we're
4834                        // looking for, skip it.
4835                        if (always && !pa.mPref.mAlways) {
4836                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4837                            continue;
4838                        }
4839                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4840                                flags | MATCH_DISABLED_COMPONENTS, userId);
4841                        if (DEBUG_PREFERRED || debug) {
4842                            Slog.v(TAG, "Found preferred activity:");
4843                            if (ai != null) {
4844                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4845                            } else {
4846                                Slog.v(TAG, "  null");
4847                            }
4848                        }
4849                        if (ai == null) {
4850                            // This previously registered preferred activity
4851                            // component is no longer known.  Most likely an update
4852                            // to the app was installed and in the new version this
4853                            // component no longer exists.  Clean it up by removing
4854                            // it from the preferred activities list, and skip it.
4855                            Slog.w(TAG, "Removing dangling preferred activity: "
4856                                    + pa.mPref.mComponent);
4857                            pir.removeFilter(pa);
4858                            changed = true;
4859                            continue;
4860                        }
4861                        for (int j=0; j<N; j++) {
4862                            final ResolveInfo ri = query.get(j);
4863                            if (!ri.activityInfo.applicationInfo.packageName
4864                                    .equals(ai.applicationInfo.packageName)) {
4865                                continue;
4866                            }
4867                            if (!ri.activityInfo.name.equals(ai.name)) {
4868                                continue;
4869                            }
4870
4871                            if (removeMatches) {
4872                                pir.removeFilter(pa);
4873                                changed = true;
4874                                if (DEBUG_PREFERRED) {
4875                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4876                                }
4877                                break;
4878                            }
4879
4880                            // Okay we found a previously set preferred or last chosen app.
4881                            // If the result set is different from when this
4882                            // was created, we need to clear it and re-ask the
4883                            // user their preference, if we're looking for an "always" type entry.
4884                            if (always && !pa.mPref.sameSet(query)) {
4885                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4886                                        + intent + " type " + resolvedType);
4887                                if (DEBUG_PREFERRED) {
4888                                    Slog.v(TAG, "Removing preferred activity since set changed "
4889                                            + pa.mPref.mComponent);
4890                                }
4891                                pir.removeFilter(pa);
4892                                // Re-add the filter as a "last chosen" entry (!always)
4893                                PreferredActivity lastChosen = new PreferredActivity(
4894                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4895                                pir.addFilter(lastChosen);
4896                                changed = true;
4897                                return null;
4898                            }
4899
4900                            // Yay! Either the set matched or we're looking for the last chosen
4901                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4902                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4903                            return ri;
4904                        }
4905                    }
4906                } finally {
4907                    if (changed) {
4908                        if (DEBUG_PREFERRED) {
4909                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4910                        }
4911                        scheduleWritePackageRestrictionsLocked(userId);
4912                    }
4913                }
4914            }
4915        }
4916        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4917        return null;
4918    }
4919
4920    /*
4921     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4922     */
4923    @Override
4924    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4925            int targetUserId) {
4926        mContext.enforceCallingOrSelfPermission(
4927                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4928        List<CrossProfileIntentFilter> matches =
4929                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4930        if (matches != null) {
4931            int size = matches.size();
4932            for (int i = 0; i < size; i++) {
4933                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4934            }
4935        }
4936        if (hasWebURI(intent)) {
4937            // cross-profile app linking works only towards the parent.
4938            final UserInfo parent = getProfileParent(sourceUserId);
4939            synchronized(mPackages) {
4940                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4941                        intent, resolvedType, 0, sourceUserId, parent.id);
4942                return xpDomainInfo != null;
4943            }
4944        }
4945        return false;
4946    }
4947
4948    private UserInfo getProfileParent(int userId) {
4949        final long identity = Binder.clearCallingIdentity();
4950        try {
4951            return sUserManager.getProfileParent(userId);
4952        } finally {
4953            Binder.restoreCallingIdentity(identity);
4954        }
4955    }
4956
4957    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4958            String resolvedType, int userId) {
4959        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4960        if (resolver != null) {
4961            return resolver.queryIntent(intent, resolvedType, false, userId);
4962        }
4963        return null;
4964    }
4965
4966    @Override
4967    public List<ResolveInfo> queryIntentActivities(Intent intent,
4968            String resolvedType, int flags, int userId) {
4969        if (!sUserManager.exists(userId)) return Collections.emptyList();
4970        flags = updateFlagsForResolve(flags, userId, intent);
4971        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4972        ComponentName comp = intent.getComponent();
4973        if (comp == null) {
4974            if (intent.getSelector() != null) {
4975                intent = intent.getSelector();
4976                comp = intent.getComponent();
4977            }
4978        }
4979
4980        if (comp != null) {
4981            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4982            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4983            if (ai != null) {
4984                final ResolveInfo ri = new ResolveInfo();
4985                ri.activityInfo = ai;
4986                list.add(ri);
4987            }
4988            return list;
4989        }
4990
4991        // reader
4992        synchronized (mPackages) {
4993            final String pkgName = intent.getPackage();
4994            if (pkgName == null) {
4995                List<CrossProfileIntentFilter> matchingFilters =
4996                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4997                // Check for results that need to skip the current profile.
4998                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4999                        resolvedType, flags, userId);
5000                if (xpResolveInfo != null) {
5001                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5002                    result.add(xpResolveInfo);
5003                    return filterIfNotSystemUser(result, userId);
5004                }
5005
5006                // Check for results in the current profile.
5007                List<ResolveInfo> result = mActivities.queryIntent(
5008                        intent, resolvedType, flags, userId);
5009                result = filterIfNotSystemUser(result, userId);
5010
5011                // Check for cross profile results.
5012                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5013                xpResolveInfo = queryCrossProfileIntents(
5014                        matchingFilters, intent, resolvedType, flags, userId,
5015                        hasNonNegativePriorityResult);
5016                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5017                    boolean isVisibleToUser = filterIfNotSystemUser(
5018                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5019                    if (isVisibleToUser) {
5020                        result.add(xpResolveInfo);
5021                        Collections.sort(result, mResolvePrioritySorter);
5022                    }
5023                }
5024                if (hasWebURI(intent)) {
5025                    CrossProfileDomainInfo xpDomainInfo = null;
5026                    final UserInfo parent = getProfileParent(userId);
5027                    if (parent != null) {
5028                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5029                                flags, userId, parent.id);
5030                    }
5031                    if (xpDomainInfo != null) {
5032                        if (xpResolveInfo != null) {
5033                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5034                            // in the result.
5035                            result.remove(xpResolveInfo);
5036                        }
5037                        if (result.size() == 0) {
5038                            result.add(xpDomainInfo.resolveInfo);
5039                            return result;
5040                        }
5041                    } else if (result.size() <= 1) {
5042                        return result;
5043                    }
5044                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5045                            xpDomainInfo, userId);
5046                    Collections.sort(result, mResolvePrioritySorter);
5047                }
5048                return result;
5049            }
5050            final PackageParser.Package pkg = mPackages.get(pkgName);
5051            if (pkg != null) {
5052                return filterIfNotSystemUser(
5053                        mActivities.queryIntentForPackage(
5054                                intent, resolvedType, flags, pkg.activities, userId),
5055                        userId);
5056            }
5057            return new ArrayList<ResolveInfo>();
5058        }
5059    }
5060
5061    private static class CrossProfileDomainInfo {
5062        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5063        ResolveInfo resolveInfo;
5064        /* Best domain verification status of the activities found in the other profile */
5065        int bestDomainVerificationStatus;
5066    }
5067
5068    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5069            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5070        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5071                sourceUserId)) {
5072            return null;
5073        }
5074        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5075                resolvedType, flags, parentUserId);
5076
5077        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5078            return null;
5079        }
5080        CrossProfileDomainInfo result = null;
5081        int size = resultTargetUser.size();
5082        for (int i = 0; i < size; i++) {
5083            ResolveInfo riTargetUser = resultTargetUser.get(i);
5084            // Intent filter verification is only for filters that specify a host. So don't return
5085            // those that handle all web uris.
5086            if (riTargetUser.handleAllWebDataURI) {
5087                continue;
5088            }
5089            String packageName = riTargetUser.activityInfo.packageName;
5090            PackageSetting ps = mSettings.mPackages.get(packageName);
5091            if (ps == null) {
5092                continue;
5093            }
5094            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5095            int status = (int)(verificationState >> 32);
5096            if (result == null) {
5097                result = new CrossProfileDomainInfo();
5098                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5099                        sourceUserId, parentUserId);
5100                result.bestDomainVerificationStatus = status;
5101            } else {
5102                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5103                        result.bestDomainVerificationStatus);
5104            }
5105        }
5106        // Don't consider matches with status NEVER across profiles.
5107        if (result != null && result.bestDomainVerificationStatus
5108                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5109            return null;
5110        }
5111        return result;
5112    }
5113
5114    /**
5115     * Verification statuses are ordered from the worse to the best, except for
5116     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5117     */
5118    private int bestDomainVerificationStatus(int status1, int status2) {
5119        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5120            return status2;
5121        }
5122        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5123            return status1;
5124        }
5125        return (int) MathUtils.max(status1, status2);
5126    }
5127
5128    private boolean isUserEnabled(int userId) {
5129        long callingId = Binder.clearCallingIdentity();
5130        try {
5131            UserInfo userInfo = sUserManager.getUserInfo(userId);
5132            return userInfo != null && userInfo.isEnabled();
5133        } finally {
5134            Binder.restoreCallingIdentity(callingId);
5135        }
5136    }
5137
5138    /**
5139     * Filter out activities with systemUserOnly flag set, when current user is not System.
5140     *
5141     * @return filtered list
5142     */
5143    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5144        if (userId == UserHandle.USER_SYSTEM) {
5145            return resolveInfos;
5146        }
5147        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5148            ResolveInfo info = resolveInfos.get(i);
5149            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5150                resolveInfos.remove(i);
5151            }
5152        }
5153        return resolveInfos;
5154    }
5155
5156    /**
5157     * @param resolveInfos list of resolve infos in descending priority order
5158     * @return if the list contains a resolve info with non-negative priority
5159     */
5160    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5161        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5162    }
5163
5164    private static boolean hasWebURI(Intent intent) {
5165        if (intent.getData() == null) {
5166            return false;
5167        }
5168        final String scheme = intent.getScheme();
5169        if (TextUtils.isEmpty(scheme)) {
5170            return false;
5171        }
5172        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5173    }
5174
5175    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5176            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5177            int userId) {
5178        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5179
5180        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5181            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5182                    candidates.size());
5183        }
5184
5185        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5186        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5187        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5188        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5189        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5190        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5191
5192        synchronized (mPackages) {
5193            final int count = candidates.size();
5194            // First, try to use linked apps. Partition the candidates into four lists:
5195            // one for the final results, one for the "do not use ever", one for "undefined status"
5196            // and finally one for "browser app type".
5197            for (int n=0; n<count; n++) {
5198                ResolveInfo info = candidates.get(n);
5199                String packageName = info.activityInfo.packageName;
5200                PackageSetting ps = mSettings.mPackages.get(packageName);
5201                if (ps != null) {
5202                    // Add to the special match all list (Browser use case)
5203                    if (info.handleAllWebDataURI) {
5204                        matchAllList.add(info);
5205                        continue;
5206                    }
5207                    // Try to get the status from User settings first
5208                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5209                    int status = (int)(packedStatus >> 32);
5210                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5211                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5212                        if (DEBUG_DOMAIN_VERIFICATION) {
5213                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5214                                    + " : linkgen=" + linkGeneration);
5215                        }
5216                        // Use link-enabled generation as preferredOrder, i.e.
5217                        // prefer newly-enabled over earlier-enabled.
5218                        info.preferredOrder = linkGeneration;
5219                        alwaysList.add(info);
5220                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5221                        if (DEBUG_DOMAIN_VERIFICATION) {
5222                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5223                        }
5224                        neverList.add(info);
5225                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5226                        if (DEBUG_DOMAIN_VERIFICATION) {
5227                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5228                        }
5229                        alwaysAskList.add(info);
5230                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5231                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5232                        if (DEBUG_DOMAIN_VERIFICATION) {
5233                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5234                        }
5235                        undefinedList.add(info);
5236                    }
5237                }
5238            }
5239
5240            // We'll want to include browser possibilities in a few cases
5241            boolean includeBrowser = false;
5242
5243            // First try to add the "always" resolution(s) for the current user, if any
5244            if (alwaysList.size() > 0) {
5245                result.addAll(alwaysList);
5246            } else {
5247                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5248                result.addAll(undefinedList);
5249                // Maybe add one for the other profile.
5250                if (xpDomainInfo != null && (
5251                        xpDomainInfo.bestDomainVerificationStatus
5252                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5253                    result.add(xpDomainInfo.resolveInfo);
5254                }
5255                includeBrowser = true;
5256            }
5257
5258            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5259            // If there were 'always' entries their preferred order has been set, so we also
5260            // back that off to make the alternatives equivalent
5261            if (alwaysAskList.size() > 0) {
5262                for (ResolveInfo i : result) {
5263                    i.preferredOrder = 0;
5264                }
5265                result.addAll(alwaysAskList);
5266                includeBrowser = true;
5267            }
5268
5269            if (includeBrowser) {
5270                // Also add browsers (all of them or only the default one)
5271                if (DEBUG_DOMAIN_VERIFICATION) {
5272                    Slog.v(TAG, "   ...including browsers in candidate set");
5273                }
5274                if ((matchFlags & MATCH_ALL) != 0) {
5275                    result.addAll(matchAllList);
5276                } else {
5277                    // Browser/generic handling case.  If there's a default browser, go straight
5278                    // to that (but only if there is no other higher-priority match).
5279                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5280                    int maxMatchPrio = 0;
5281                    ResolveInfo defaultBrowserMatch = null;
5282                    final int numCandidates = matchAllList.size();
5283                    for (int n = 0; n < numCandidates; n++) {
5284                        ResolveInfo info = matchAllList.get(n);
5285                        // track the highest overall match priority...
5286                        if (info.priority > maxMatchPrio) {
5287                            maxMatchPrio = info.priority;
5288                        }
5289                        // ...and the highest-priority default browser match
5290                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5291                            if (defaultBrowserMatch == null
5292                                    || (defaultBrowserMatch.priority < info.priority)) {
5293                                if (debug) {
5294                                    Slog.v(TAG, "Considering default browser match " + info);
5295                                }
5296                                defaultBrowserMatch = info;
5297                            }
5298                        }
5299                    }
5300                    if (defaultBrowserMatch != null
5301                            && defaultBrowserMatch.priority >= maxMatchPrio
5302                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5303                    {
5304                        if (debug) {
5305                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5306                        }
5307                        result.add(defaultBrowserMatch);
5308                    } else {
5309                        result.addAll(matchAllList);
5310                    }
5311                }
5312
5313                // If there is nothing selected, add all candidates and remove the ones that the user
5314                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5315                if (result.size() == 0) {
5316                    result.addAll(candidates);
5317                    result.removeAll(neverList);
5318                }
5319            }
5320        }
5321        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5322            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5323                    result.size());
5324            for (ResolveInfo info : result) {
5325                Slog.v(TAG, "  + " + info.activityInfo);
5326            }
5327        }
5328        return result;
5329    }
5330
5331    // Returns a packed value as a long:
5332    //
5333    // high 'int'-sized word: link status: undefined/ask/never/always.
5334    // low 'int'-sized word: relative priority among 'always' results.
5335    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5336        long result = ps.getDomainVerificationStatusForUser(userId);
5337        // if none available, get the master status
5338        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5339            if (ps.getIntentFilterVerificationInfo() != null) {
5340                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5341            }
5342        }
5343        return result;
5344    }
5345
5346    private ResolveInfo querySkipCurrentProfileIntents(
5347            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5348            int flags, int sourceUserId) {
5349        if (matchingFilters != null) {
5350            int size = matchingFilters.size();
5351            for (int i = 0; i < size; i ++) {
5352                CrossProfileIntentFilter filter = matchingFilters.get(i);
5353                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5354                    // Checking if there are activities in the target user that can handle the
5355                    // intent.
5356                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5357                            resolvedType, flags, sourceUserId);
5358                    if (resolveInfo != null) {
5359                        return resolveInfo;
5360                    }
5361                }
5362            }
5363        }
5364        return null;
5365    }
5366
5367    // Return matching ResolveInfo in target user if any.
5368    private ResolveInfo queryCrossProfileIntents(
5369            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5370            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5371        if (matchingFilters != null) {
5372            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5373            // match the same intent. For performance reasons, it is better not to
5374            // run queryIntent twice for the same userId
5375            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5376            int size = matchingFilters.size();
5377            for (int i = 0; i < size; i++) {
5378                CrossProfileIntentFilter filter = matchingFilters.get(i);
5379                int targetUserId = filter.getTargetUserId();
5380                boolean skipCurrentProfile =
5381                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5382                boolean skipCurrentProfileIfNoMatchFound =
5383                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5384                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5385                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5386                    // Checking if there are activities in the target user that can handle the
5387                    // intent.
5388                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5389                            resolvedType, flags, sourceUserId);
5390                    if (resolveInfo != null) return resolveInfo;
5391                    alreadyTriedUserIds.put(targetUserId, true);
5392                }
5393            }
5394        }
5395        return null;
5396    }
5397
5398    /**
5399     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5400     * will forward the intent to the filter's target user.
5401     * Otherwise, returns null.
5402     */
5403    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5404            String resolvedType, int flags, int sourceUserId) {
5405        int targetUserId = filter.getTargetUserId();
5406        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5407                resolvedType, flags, targetUserId);
5408        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5409            // If all the matches in the target profile are suspended, return null.
5410            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5411                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5412                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5413                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5414                            targetUserId);
5415                }
5416            }
5417        }
5418        return null;
5419    }
5420
5421    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5422            int sourceUserId, int targetUserId) {
5423        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5424        long ident = Binder.clearCallingIdentity();
5425        boolean targetIsProfile;
5426        try {
5427            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5428        } finally {
5429            Binder.restoreCallingIdentity(ident);
5430        }
5431        String className;
5432        if (targetIsProfile) {
5433            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5434        } else {
5435            className = FORWARD_INTENT_TO_PARENT;
5436        }
5437        ComponentName forwardingActivityComponentName = new ComponentName(
5438                mAndroidApplication.packageName, className);
5439        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5440                sourceUserId);
5441        if (!targetIsProfile) {
5442            forwardingActivityInfo.showUserIcon = targetUserId;
5443            forwardingResolveInfo.noResourceId = true;
5444        }
5445        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5446        forwardingResolveInfo.priority = 0;
5447        forwardingResolveInfo.preferredOrder = 0;
5448        forwardingResolveInfo.match = 0;
5449        forwardingResolveInfo.isDefault = true;
5450        forwardingResolveInfo.filter = filter;
5451        forwardingResolveInfo.targetUserId = targetUserId;
5452        return forwardingResolveInfo;
5453    }
5454
5455    @Override
5456    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5457            Intent[] specifics, String[] specificTypes, Intent intent,
5458            String resolvedType, int flags, int userId) {
5459        if (!sUserManager.exists(userId)) return Collections.emptyList();
5460        flags = updateFlagsForResolve(flags, userId, intent);
5461        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5462                false, "query intent activity options");
5463        final String resultsAction = intent.getAction();
5464
5465        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5466                | PackageManager.GET_RESOLVED_FILTER, userId);
5467
5468        if (DEBUG_INTENT_MATCHING) {
5469            Log.v(TAG, "Query " + intent + ": " + results);
5470        }
5471
5472        int specificsPos = 0;
5473        int N;
5474
5475        // todo: note that the algorithm used here is O(N^2).  This
5476        // isn't a problem in our current environment, but if we start running
5477        // into situations where we have more than 5 or 10 matches then this
5478        // should probably be changed to something smarter...
5479
5480        // First we go through and resolve each of the specific items
5481        // that were supplied, taking care of removing any corresponding
5482        // duplicate items in the generic resolve list.
5483        if (specifics != null) {
5484            for (int i=0; i<specifics.length; i++) {
5485                final Intent sintent = specifics[i];
5486                if (sintent == null) {
5487                    continue;
5488                }
5489
5490                if (DEBUG_INTENT_MATCHING) {
5491                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5492                }
5493
5494                String action = sintent.getAction();
5495                if (resultsAction != null && resultsAction.equals(action)) {
5496                    // If this action was explicitly requested, then don't
5497                    // remove things that have it.
5498                    action = null;
5499                }
5500
5501                ResolveInfo ri = null;
5502                ActivityInfo ai = null;
5503
5504                ComponentName comp = sintent.getComponent();
5505                if (comp == null) {
5506                    ri = resolveIntent(
5507                        sintent,
5508                        specificTypes != null ? specificTypes[i] : null,
5509                            flags, userId);
5510                    if (ri == null) {
5511                        continue;
5512                    }
5513                    if (ri == mResolveInfo) {
5514                        // ACK!  Must do something better with this.
5515                    }
5516                    ai = ri.activityInfo;
5517                    comp = new ComponentName(ai.applicationInfo.packageName,
5518                            ai.name);
5519                } else {
5520                    ai = getActivityInfo(comp, flags, userId);
5521                    if (ai == null) {
5522                        continue;
5523                    }
5524                }
5525
5526                // Look for any generic query activities that are duplicates
5527                // of this specific one, and remove them from the results.
5528                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5529                N = results.size();
5530                int j;
5531                for (j=specificsPos; j<N; j++) {
5532                    ResolveInfo sri = results.get(j);
5533                    if ((sri.activityInfo.name.equals(comp.getClassName())
5534                            && sri.activityInfo.applicationInfo.packageName.equals(
5535                                    comp.getPackageName()))
5536                        || (action != null && sri.filter.matchAction(action))) {
5537                        results.remove(j);
5538                        if (DEBUG_INTENT_MATCHING) Log.v(
5539                            TAG, "Removing duplicate item from " + j
5540                            + " due to specific " + specificsPos);
5541                        if (ri == null) {
5542                            ri = sri;
5543                        }
5544                        j--;
5545                        N--;
5546                    }
5547                }
5548
5549                // Add this specific item to its proper place.
5550                if (ri == null) {
5551                    ri = new ResolveInfo();
5552                    ri.activityInfo = ai;
5553                }
5554                results.add(specificsPos, ri);
5555                ri.specificIndex = i;
5556                specificsPos++;
5557            }
5558        }
5559
5560        // Now we go through the remaining generic results and remove any
5561        // duplicate actions that are found here.
5562        N = results.size();
5563        for (int i=specificsPos; i<N-1; i++) {
5564            final ResolveInfo rii = results.get(i);
5565            if (rii.filter == null) {
5566                continue;
5567            }
5568
5569            // Iterate over all of the actions of this result's intent
5570            // filter...  typically this should be just one.
5571            final Iterator<String> it = rii.filter.actionsIterator();
5572            if (it == null) {
5573                continue;
5574            }
5575            while (it.hasNext()) {
5576                final String action = it.next();
5577                if (resultsAction != null && resultsAction.equals(action)) {
5578                    // If this action was explicitly requested, then don't
5579                    // remove things that have it.
5580                    continue;
5581                }
5582                for (int j=i+1; j<N; j++) {
5583                    final ResolveInfo rij = results.get(j);
5584                    if (rij.filter != null && rij.filter.hasAction(action)) {
5585                        results.remove(j);
5586                        if (DEBUG_INTENT_MATCHING) Log.v(
5587                            TAG, "Removing duplicate item from " + j
5588                            + " due to action " + action + " at " + i);
5589                        j--;
5590                        N--;
5591                    }
5592                }
5593            }
5594
5595            // If the caller didn't request filter information, drop it now
5596            // so we don't have to marshall/unmarshall it.
5597            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5598                rii.filter = null;
5599            }
5600        }
5601
5602        // Filter out the caller activity if so requested.
5603        if (caller != null) {
5604            N = results.size();
5605            for (int i=0; i<N; i++) {
5606                ActivityInfo ainfo = results.get(i).activityInfo;
5607                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5608                        && caller.getClassName().equals(ainfo.name)) {
5609                    results.remove(i);
5610                    break;
5611                }
5612            }
5613        }
5614
5615        // If the caller didn't request filter information,
5616        // drop them now so we don't have to
5617        // marshall/unmarshall it.
5618        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5619            N = results.size();
5620            for (int i=0; i<N; i++) {
5621                results.get(i).filter = null;
5622            }
5623        }
5624
5625        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5626        return results;
5627    }
5628
5629    @Override
5630    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5631            int userId) {
5632        if (!sUserManager.exists(userId)) return Collections.emptyList();
5633        flags = updateFlagsForResolve(flags, userId, intent);
5634        ComponentName comp = intent.getComponent();
5635        if (comp == null) {
5636            if (intent.getSelector() != null) {
5637                intent = intent.getSelector();
5638                comp = intent.getComponent();
5639            }
5640        }
5641        if (comp != null) {
5642            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5643            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5644            if (ai != null) {
5645                ResolveInfo ri = new ResolveInfo();
5646                ri.activityInfo = ai;
5647                list.add(ri);
5648            }
5649            return list;
5650        }
5651
5652        // reader
5653        synchronized (mPackages) {
5654            String pkgName = intent.getPackage();
5655            if (pkgName == null) {
5656                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5657            }
5658            final PackageParser.Package pkg = mPackages.get(pkgName);
5659            if (pkg != null) {
5660                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5661                        userId);
5662            }
5663            return null;
5664        }
5665    }
5666
5667    @Override
5668    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5669        if (!sUserManager.exists(userId)) return null;
5670        flags = updateFlagsForResolve(flags, userId, intent);
5671        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5672        if (query != null) {
5673            if (query.size() >= 1) {
5674                // If there is more than one service with the same priority,
5675                // just arbitrarily pick the first one.
5676                return query.get(0);
5677            }
5678        }
5679        return null;
5680    }
5681
5682    @Override
5683    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5684            int userId) {
5685        if (!sUserManager.exists(userId)) return Collections.emptyList();
5686        flags = updateFlagsForResolve(flags, userId, intent);
5687        ComponentName comp = intent.getComponent();
5688        if (comp == null) {
5689            if (intent.getSelector() != null) {
5690                intent = intent.getSelector();
5691                comp = intent.getComponent();
5692            }
5693        }
5694        if (comp != null) {
5695            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5696            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5697            if (si != null) {
5698                final ResolveInfo ri = new ResolveInfo();
5699                ri.serviceInfo = si;
5700                list.add(ri);
5701            }
5702            return list;
5703        }
5704
5705        // reader
5706        synchronized (mPackages) {
5707            String pkgName = intent.getPackage();
5708            if (pkgName == null) {
5709                return mServices.queryIntent(intent, resolvedType, flags, userId);
5710            }
5711            final PackageParser.Package pkg = mPackages.get(pkgName);
5712            if (pkg != null) {
5713                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5714                        userId);
5715            }
5716            return null;
5717        }
5718    }
5719
5720    @Override
5721    public List<ResolveInfo> queryIntentContentProviders(
5722            Intent intent, String resolvedType, int flags, int userId) {
5723        if (!sUserManager.exists(userId)) return Collections.emptyList();
5724        flags = updateFlagsForResolve(flags, userId, intent);
5725        ComponentName comp = intent.getComponent();
5726        if (comp == null) {
5727            if (intent.getSelector() != null) {
5728                intent = intent.getSelector();
5729                comp = intent.getComponent();
5730            }
5731        }
5732        if (comp != null) {
5733            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5734            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5735            if (pi != null) {
5736                final ResolveInfo ri = new ResolveInfo();
5737                ri.providerInfo = pi;
5738                list.add(ri);
5739            }
5740            return list;
5741        }
5742
5743        // reader
5744        synchronized (mPackages) {
5745            String pkgName = intent.getPackage();
5746            if (pkgName == null) {
5747                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5748            }
5749            final PackageParser.Package pkg = mPackages.get(pkgName);
5750            if (pkg != null) {
5751                return mProviders.queryIntentForPackage(
5752                        intent, resolvedType, flags, pkg.providers, userId);
5753            }
5754            return null;
5755        }
5756    }
5757
5758    @Override
5759    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5760        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5761        flags = updateFlagsForPackage(flags, userId, null);
5762        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5763        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5764
5765        // writer
5766        synchronized (mPackages) {
5767            ArrayList<PackageInfo> list;
5768            if (listUninstalled) {
5769                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5770                for (PackageSetting ps : mSettings.mPackages.values()) {
5771                    PackageInfo pi;
5772                    if (ps.pkg != null) {
5773                        pi = generatePackageInfo(ps.pkg, flags, userId);
5774                    } else {
5775                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5776                    }
5777                    if (pi != null) {
5778                        list.add(pi);
5779                    }
5780                }
5781            } else {
5782                list = new ArrayList<PackageInfo>(mPackages.size());
5783                for (PackageParser.Package p : mPackages.values()) {
5784                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5785                    if (pi != null) {
5786                        list.add(pi);
5787                    }
5788                }
5789            }
5790
5791            return new ParceledListSlice<PackageInfo>(list);
5792        }
5793    }
5794
5795    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5796            String[] permissions, boolean[] tmp, int flags, int userId) {
5797        int numMatch = 0;
5798        final PermissionsState permissionsState = ps.getPermissionsState();
5799        for (int i=0; i<permissions.length; i++) {
5800            final String permission = permissions[i];
5801            if (permissionsState.hasPermission(permission, userId)) {
5802                tmp[i] = true;
5803                numMatch++;
5804            } else {
5805                tmp[i] = false;
5806            }
5807        }
5808        if (numMatch == 0) {
5809            return;
5810        }
5811        PackageInfo pi;
5812        if (ps.pkg != null) {
5813            pi = generatePackageInfo(ps.pkg, flags, userId);
5814        } else {
5815            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5816        }
5817        // The above might return null in cases of uninstalled apps or install-state
5818        // skew across users/profiles.
5819        if (pi != null) {
5820            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5821                if (numMatch == permissions.length) {
5822                    pi.requestedPermissions = permissions;
5823                } else {
5824                    pi.requestedPermissions = new String[numMatch];
5825                    numMatch = 0;
5826                    for (int i=0; i<permissions.length; i++) {
5827                        if (tmp[i]) {
5828                            pi.requestedPermissions[numMatch] = permissions[i];
5829                            numMatch++;
5830                        }
5831                    }
5832                }
5833            }
5834            list.add(pi);
5835        }
5836    }
5837
5838    @Override
5839    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5840            String[] permissions, int flags, int userId) {
5841        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5842        flags = updateFlagsForPackage(flags, userId, permissions);
5843        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5844
5845        // writer
5846        synchronized (mPackages) {
5847            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5848            boolean[] tmpBools = new boolean[permissions.length];
5849            if (listUninstalled) {
5850                for (PackageSetting ps : mSettings.mPackages.values()) {
5851                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5852                }
5853            } else {
5854                for (PackageParser.Package pkg : mPackages.values()) {
5855                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5856                    if (ps != null) {
5857                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5858                                userId);
5859                    }
5860                }
5861            }
5862
5863            return new ParceledListSlice<PackageInfo>(list);
5864        }
5865    }
5866
5867    @Override
5868    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5869        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5870        flags = updateFlagsForApplication(flags, userId, null);
5871        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5872
5873        // writer
5874        synchronized (mPackages) {
5875            ArrayList<ApplicationInfo> list;
5876            if (listUninstalled) {
5877                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5878                for (PackageSetting ps : mSettings.mPackages.values()) {
5879                    ApplicationInfo ai;
5880                    if (ps.pkg != null) {
5881                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5882                                ps.readUserState(userId), userId);
5883                    } else {
5884                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5885                    }
5886                    if (ai != null) {
5887                        list.add(ai);
5888                    }
5889                }
5890            } else {
5891                list = new ArrayList<ApplicationInfo>(mPackages.size());
5892                for (PackageParser.Package p : mPackages.values()) {
5893                    if (p.mExtras != null) {
5894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5895                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5896                        if (ai != null) {
5897                            list.add(ai);
5898                        }
5899                    }
5900                }
5901            }
5902
5903            return new ParceledListSlice<ApplicationInfo>(list);
5904        }
5905    }
5906
5907    @Override
5908    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5909        if (DISABLE_EPHEMERAL_APPS) {
5910            return null;
5911        }
5912
5913        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5914                "getEphemeralApplications");
5915        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5916                "getEphemeralApplications");
5917        synchronized (mPackages) {
5918            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5919                    .getEphemeralApplicationsLPw(userId);
5920            if (ephemeralApps != null) {
5921                return new ParceledListSlice<>(ephemeralApps);
5922            }
5923        }
5924        return null;
5925    }
5926
5927    @Override
5928    public boolean isEphemeralApplication(String packageName, int userId) {
5929        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5930                "isEphemeral");
5931        if (DISABLE_EPHEMERAL_APPS) {
5932            return false;
5933        }
5934
5935        if (!isCallerSameApp(packageName)) {
5936            return false;
5937        }
5938        synchronized (mPackages) {
5939            PackageParser.Package pkg = mPackages.get(packageName);
5940            if (pkg != null) {
5941                return pkg.applicationInfo.isEphemeralApp();
5942            }
5943        }
5944        return false;
5945    }
5946
5947    @Override
5948    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5949        if (DISABLE_EPHEMERAL_APPS) {
5950            return null;
5951        }
5952
5953        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5954                "getCookie");
5955        if (!isCallerSameApp(packageName)) {
5956            return null;
5957        }
5958        synchronized (mPackages) {
5959            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5960                    packageName, userId);
5961        }
5962    }
5963
5964    @Override
5965    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5966        if (DISABLE_EPHEMERAL_APPS) {
5967            return true;
5968        }
5969
5970        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5971                "setCookie");
5972        if (!isCallerSameApp(packageName)) {
5973            return false;
5974        }
5975        synchronized (mPackages) {
5976            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5977                    packageName, cookie, userId);
5978        }
5979    }
5980
5981    @Override
5982    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5983        if (DISABLE_EPHEMERAL_APPS) {
5984            return null;
5985        }
5986
5987        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5988                "getEphemeralApplicationIcon");
5989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5990                "getEphemeralApplicationIcon");
5991        synchronized (mPackages) {
5992            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5993                    packageName, userId);
5994        }
5995    }
5996
5997    private boolean isCallerSameApp(String packageName) {
5998        PackageParser.Package pkg = mPackages.get(packageName);
5999        return pkg != null
6000                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6001    }
6002
6003    public List<ApplicationInfo> getPersistentApplications(int flags) {
6004        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6005
6006        // reader
6007        synchronized (mPackages) {
6008            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6009            final int userId = UserHandle.getCallingUserId();
6010            while (i.hasNext()) {
6011                final PackageParser.Package p = i.next();
6012                if (p.applicationInfo != null
6013                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6014                        && (!mSafeMode || isSystemApp(p))) {
6015                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6016                    if (ps != null) {
6017                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6018                                ps.readUserState(userId), userId);
6019                        if (ai != null) {
6020                            finalList.add(ai);
6021                        }
6022                    }
6023                }
6024            }
6025        }
6026
6027        return finalList;
6028    }
6029
6030    @Override
6031    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6032        if (!sUserManager.exists(userId)) return null;
6033        flags = updateFlagsForComponent(flags, userId, name);
6034        // reader
6035        synchronized (mPackages) {
6036            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6037            PackageSetting ps = provider != null
6038                    ? mSettings.mPackages.get(provider.owner.packageName)
6039                    : null;
6040            return ps != null
6041                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6042                    ? PackageParser.generateProviderInfo(provider, flags,
6043                            ps.readUserState(userId), userId)
6044                    : null;
6045        }
6046    }
6047
6048    /**
6049     * @deprecated
6050     */
6051    @Deprecated
6052    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6053        // reader
6054        synchronized (mPackages) {
6055            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6056                    .entrySet().iterator();
6057            final int userId = UserHandle.getCallingUserId();
6058            while (i.hasNext()) {
6059                Map.Entry<String, PackageParser.Provider> entry = i.next();
6060                PackageParser.Provider p = entry.getValue();
6061                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6062
6063                if (ps != null && p.syncable
6064                        && (!mSafeMode || (p.info.applicationInfo.flags
6065                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6066                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6067                            ps.readUserState(userId), userId);
6068                    if (info != null) {
6069                        outNames.add(entry.getKey());
6070                        outInfo.add(info);
6071                    }
6072                }
6073            }
6074        }
6075    }
6076
6077    @Override
6078    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6079            int uid, int flags) {
6080        final int userId = processName != null ? UserHandle.getUserId(uid)
6081                : UserHandle.getCallingUserId();
6082        if (!sUserManager.exists(userId)) return null;
6083        flags = updateFlagsForComponent(flags, userId, processName);
6084
6085        ArrayList<ProviderInfo> finalList = null;
6086        // reader
6087        synchronized (mPackages) {
6088            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6089            while (i.hasNext()) {
6090                final PackageParser.Provider p = i.next();
6091                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6092                if (ps != null && p.info.authority != null
6093                        && (processName == null
6094                                || (p.info.processName.equals(processName)
6095                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6096                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6097                    if (finalList == null) {
6098                        finalList = new ArrayList<ProviderInfo>(3);
6099                    }
6100                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6101                            ps.readUserState(userId), userId);
6102                    if (info != null) {
6103                        finalList.add(info);
6104                    }
6105                }
6106            }
6107        }
6108
6109        if (finalList != null) {
6110            Collections.sort(finalList, mProviderInitOrderSorter);
6111            return new ParceledListSlice<ProviderInfo>(finalList);
6112        }
6113
6114        return null;
6115    }
6116
6117    @Override
6118    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6119        // reader
6120        synchronized (mPackages) {
6121            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6122            return PackageParser.generateInstrumentationInfo(i, flags);
6123        }
6124    }
6125
6126    @Override
6127    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6128            int flags) {
6129        ArrayList<InstrumentationInfo> finalList =
6130            new ArrayList<InstrumentationInfo>();
6131
6132        // reader
6133        synchronized (mPackages) {
6134            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6135            while (i.hasNext()) {
6136                final PackageParser.Instrumentation p = i.next();
6137                if (targetPackage == null
6138                        || targetPackage.equals(p.info.targetPackage)) {
6139                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6140                            flags);
6141                    if (ii != null) {
6142                        finalList.add(ii);
6143                    }
6144                }
6145            }
6146        }
6147
6148        return finalList;
6149    }
6150
6151    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6152        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6153        if (overlays == null) {
6154            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6155            return;
6156        }
6157        for (PackageParser.Package opkg : overlays.values()) {
6158            // Not much to do if idmap fails: we already logged the error
6159            // and we certainly don't want to abort installation of pkg simply
6160            // because an overlay didn't fit properly. For these reasons,
6161            // ignore the return value of createIdmapForPackagePairLI.
6162            createIdmapForPackagePairLI(pkg, opkg);
6163        }
6164    }
6165
6166    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6167            PackageParser.Package opkg) {
6168        if (!opkg.mTrustedOverlay) {
6169            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6170                    opkg.baseCodePath + ": overlay not trusted");
6171            return false;
6172        }
6173        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6174        if (overlaySet == null) {
6175            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6176                    opkg.baseCodePath + " but target package has no known overlays");
6177            return false;
6178        }
6179        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6180        // TODO: generate idmap for split APKs
6181        try {
6182            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6183        } catch (InstallerException e) {
6184            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6185                    + opkg.baseCodePath);
6186            return false;
6187        }
6188        PackageParser.Package[] overlayArray =
6189            overlaySet.values().toArray(new PackageParser.Package[0]);
6190        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6191            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6192                return p1.mOverlayPriority - p2.mOverlayPriority;
6193            }
6194        };
6195        Arrays.sort(overlayArray, cmp);
6196
6197        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6198        int i = 0;
6199        for (PackageParser.Package p : overlayArray) {
6200            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6201        }
6202        return true;
6203    }
6204
6205    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6206        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6207        try {
6208            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6209        } finally {
6210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6211        }
6212    }
6213
6214    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6215        final File[] files = dir.listFiles();
6216        if (ArrayUtils.isEmpty(files)) {
6217            Log.d(TAG, "No files in app dir " + dir);
6218            return;
6219        }
6220
6221        if (DEBUG_PACKAGE_SCANNING) {
6222            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6223                    + " flags=0x" + Integer.toHexString(parseFlags));
6224        }
6225
6226        for (File file : files) {
6227            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6228                    && !PackageInstallerService.isStageName(file.getName());
6229            if (!isPackage) {
6230                // Ignore entries which are not packages
6231                continue;
6232            }
6233            try {
6234                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6235                        scanFlags, currentTime, null);
6236            } catch (PackageManagerException e) {
6237                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6238
6239                // Delete invalid userdata apps
6240                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6241                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6242                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6243                    removeCodePathLI(file);
6244                }
6245            }
6246        }
6247    }
6248
6249    private static File getSettingsProblemFile() {
6250        File dataDir = Environment.getDataDirectory();
6251        File systemDir = new File(dataDir, "system");
6252        File fname = new File(systemDir, "uiderrors.txt");
6253        return fname;
6254    }
6255
6256    static void reportSettingsProblem(int priority, String msg) {
6257        logCriticalInfo(priority, msg);
6258    }
6259
6260    static void logCriticalInfo(int priority, String msg) {
6261        Slog.println(priority, TAG, msg);
6262        EventLogTags.writePmCriticalInfo(msg);
6263        try {
6264            File fname = getSettingsProblemFile();
6265            FileOutputStream out = new FileOutputStream(fname, true);
6266            PrintWriter pw = new FastPrintWriter(out);
6267            SimpleDateFormat formatter = new SimpleDateFormat();
6268            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6269            pw.println(dateString + ": " + msg);
6270            pw.close();
6271            FileUtils.setPermissions(
6272                    fname.toString(),
6273                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6274                    -1, -1);
6275        } catch (java.io.IOException e) {
6276        }
6277    }
6278
6279    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6280            int parseFlags) throws PackageManagerException {
6281        if (ps != null
6282                && ps.codePath.equals(srcFile)
6283                && ps.timeStamp == srcFile.lastModified()
6284                && !isCompatSignatureUpdateNeeded(pkg)
6285                && !isRecoverSignatureUpdateNeeded(pkg)) {
6286            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6287            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6288            ArraySet<PublicKey> signingKs;
6289            synchronized (mPackages) {
6290                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6291            }
6292            if (ps.signatures.mSignatures != null
6293                    && ps.signatures.mSignatures.length != 0
6294                    && signingKs != null) {
6295                // Optimization: reuse the existing cached certificates
6296                // if the package appears to be unchanged.
6297                pkg.mSignatures = ps.signatures.mSignatures;
6298                pkg.mSigningKeys = signingKs;
6299                return;
6300            }
6301
6302            Slog.w(TAG, "PackageSetting for " + ps.name
6303                    + " is missing signatures.  Collecting certs again to recover them.");
6304        } else {
6305            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6306        }
6307
6308        try {
6309            PackageParser.collectCertificates(pkg, parseFlags);
6310        } catch (PackageParserException e) {
6311            throw PackageManagerException.from(e);
6312        }
6313    }
6314
6315    /**
6316     *  Traces a package scan.
6317     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6318     */
6319    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6320            long currentTime, UserHandle user) throws PackageManagerException {
6321        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6322        try {
6323            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6324        } finally {
6325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6326        }
6327    }
6328
6329    /**
6330     *  Scans a package and returns the newly parsed package.
6331     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6332     */
6333    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6334            long currentTime, UserHandle user) throws PackageManagerException {
6335        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6336        parseFlags |= mDefParseFlags;
6337        PackageParser pp = new PackageParser();
6338        pp.setSeparateProcesses(mSeparateProcesses);
6339        pp.setOnlyCoreApps(mOnlyCore);
6340        pp.setDisplayMetrics(mMetrics);
6341
6342        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6343            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6344        }
6345
6346        final PackageParser.Package pkg;
6347        try {
6348            pkg = pp.parsePackage(scanFile, parseFlags);
6349        } catch (PackageParserException e) {
6350            throw PackageManagerException.from(e);
6351        }
6352
6353        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6354    }
6355
6356    /**
6357     *  Scans a package and returns the newly parsed package.
6358     *  @throws PackageManagerException on a parse error.
6359     */
6360    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6361            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6362            throws PackageManagerException {
6363        // If the package has children and this is the first dive in the function
6364        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6365        // packages (parent and children) would be successfully scanned before the
6366        // actual scan since scanning mutates internal state and we want to atomically
6367        // install the package and its children.
6368        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6369            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6370                scanFlags |= SCAN_CHECK_ONLY;
6371            }
6372        } else {
6373            scanFlags &= ~SCAN_CHECK_ONLY;
6374        }
6375
6376        // Scan the parent
6377        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6378                scanFlags, currentTime, user);
6379
6380        // Scan the children
6381        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6382        for (int i = 0; i < childCount; i++) {
6383            PackageParser.Package childPackage = pkg.childPackages.get(i);
6384            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6385                    currentTime, user);
6386        }
6387
6388
6389        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6390            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6391        }
6392
6393        return scannedPkg;
6394    }
6395
6396    /**
6397     *  Scans a package and returns the newly parsed package.
6398     *  @throws PackageManagerException on a parse error.
6399     */
6400    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6401            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6402            throws PackageManagerException {
6403        PackageSetting ps = null;
6404        PackageSetting updatedPkg;
6405        // reader
6406        synchronized (mPackages) {
6407            // Look to see if we already know about this package.
6408            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6409            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6410                // This package has been renamed to its original name.  Let's
6411                // use that.
6412                ps = mSettings.peekPackageLPr(oldName);
6413            }
6414            // If there was no original package, see one for the real package name.
6415            if (ps == null) {
6416                ps = mSettings.peekPackageLPr(pkg.packageName);
6417            }
6418            // Check to see if this package could be hiding/updating a system
6419            // package.  Must look for it either under the original or real
6420            // package name depending on our state.
6421            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6422            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6423
6424            // If this is a package we don't know about on the system partition, we
6425            // may need to remove disabled child packages on the system partition
6426            // or may need to not add child packages if the parent apk is updated
6427            // on the data partition and no longer defines this child package.
6428            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6429                // If this is a parent package for an updated system app and this system
6430                // app got an OTA update which no longer defines some of the child packages
6431                // we have to prune them from the disabled system packages.
6432                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6433                if (disabledPs != null) {
6434                    final int scannedChildCount = (pkg.childPackages != null)
6435                            ? pkg.childPackages.size() : 0;
6436                    final int disabledChildCount = disabledPs.childPackageNames != null
6437                            ? disabledPs.childPackageNames.size() : 0;
6438                    for (int i = 0; i < disabledChildCount; i++) {
6439                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6440                        boolean disabledPackageAvailable = false;
6441                        for (int j = 0; j < scannedChildCount; j++) {
6442                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6443                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6444                                disabledPackageAvailable = true;
6445                                break;
6446                            }
6447                         }
6448                         if (!disabledPackageAvailable) {
6449                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6450                         }
6451                    }
6452                }
6453            }
6454        }
6455
6456        boolean updatedPkgBetter = false;
6457        // First check if this is a system package that may involve an update
6458        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6459            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6460            // it needs to drop FLAG_PRIVILEGED.
6461            if (locationIsPrivileged(scanFile)) {
6462                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6463            } else {
6464                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6465            }
6466
6467            if (ps != null && !ps.codePath.equals(scanFile)) {
6468                // The path has changed from what was last scanned...  check the
6469                // version of the new path against what we have stored to determine
6470                // what to do.
6471                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6472                if (pkg.mVersionCode <= ps.versionCode) {
6473                    // The system package has been updated and the code path does not match
6474                    // Ignore entry. Skip it.
6475                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6476                            + " ignored: updated version " + ps.versionCode
6477                            + " better than this " + pkg.mVersionCode);
6478                    if (!updatedPkg.codePath.equals(scanFile)) {
6479                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6480                                + ps.name + " changing from " + updatedPkg.codePathString
6481                                + " to " + scanFile);
6482                        updatedPkg.codePath = scanFile;
6483                        updatedPkg.codePathString = scanFile.toString();
6484                        updatedPkg.resourcePath = scanFile;
6485                        updatedPkg.resourcePathString = scanFile.toString();
6486                    }
6487                    updatedPkg.pkg = pkg;
6488                    updatedPkg.versionCode = pkg.mVersionCode;
6489
6490                    // Update the disabled system child packages to point to the package too.
6491                    final int childCount = updatedPkg.childPackageNames != null
6492                            ? updatedPkg.childPackageNames.size() : 0;
6493                    for (int i = 0; i < childCount; i++) {
6494                        String childPackageName = updatedPkg.childPackageNames.get(i);
6495                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6496                                childPackageName);
6497                        if (updatedChildPkg != null) {
6498                            updatedChildPkg.pkg = pkg;
6499                            updatedChildPkg.versionCode = pkg.mVersionCode;
6500                        }
6501                    }
6502
6503                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6504                            + scanFile + " ignored: updated version " + ps.versionCode
6505                            + " better than this " + pkg.mVersionCode);
6506                } else {
6507                    // The current app on the system partition is better than
6508                    // what we have updated to on the data partition; switch
6509                    // back to the system partition version.
6510                    // At this point, its safely assumed that package installation for
6511                    // apps in system partition will go through. If not there won't be a working
6512                    // version of the app
6513                    // writer
6514                    synchronized (mPackages) {
6515                        // Just remove the loaded entries from package lists.
6516                        mPackages.remove(ps.name);
6517                    }
6518
6519                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6520                            + " reverting from " + ps.codePathString
6521                            + ": new version " + pkg.mVersionCode
6522                            + " better than installed " + ps.versionCode);
6523
6524                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6525                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6526                    synchronized (mInstallLock) {
6527                        args.cleanUpResourcesLI();
6528                    }
6529                    synchronized (mPackages) {
6530                        mSettings.enableSystemPackageLPw(ps.name);
6531                    }
6532                    updatedPkgBetter = true;
6533                }
6534            }
6535        }
6536
6537        if (updatedPkg != null) {
6538            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6539            // initially
6540            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6541
6542            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6543            // flag set initially
6544            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6545                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6546            }
6547        }
6548
6549        // Verify certificates against what was last scanned
6550        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6551
6552        /*
6553         * A new system app appeared, but we already had a non-system one of the
6554         * same name installed earlier.
6555         */
6556        boolean shouldHideSystemApp = false;
6557        if (updatedPkg == null && ps != null
6558                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6559            /*
6560             * Check to make sure the signatures match first. If they don't,
6561             * wipe the installed application and its data.
6562             */
6563            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6564                    != PackageManager.SIGNATURE_MATCH) {
6565                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6566                        + " signatures don't match existing userdata copy; removing");
6567                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null);
6568                ps = null;
6569            } else {
6570                /*
6571                 * If the newly-added system app is an older version than the
6572                 * already installed version, hide it. It will be scanned later
6573                 * and re-added like an update.
6574                 */
6575                if (pkg.mVersionCode <= ps.versionCode) {
6576                    shouldHideSystemApp = true;
6577                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6578                            + " but new version " + pkg.mVersionCode + " better than installed "
6579                            + ps.versionCode + "; hiding system");
6580                } else {
6581                    /*
6582                     * The newly found system app is a newer version that the
6583                     * one previously installed. Simply remove the
6584                     * already-installed application and replace it with our own
6585                     * while keeping the application data.
6586                     */
6587                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6588                            + " reverting from " + ps.codePathString + ": new version "
6589                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6590                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6591                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6592                    synchronized (mInstallLock) {
6593                        args.cleanUpResourcesLI();
6594                    }
6595                }
6596            }
6597        }
6598
6599        // The apk is forward locked (not public) if its code and resources
6600        // are kept in different files. (except for app in either system or
6601        // vendor path).
6602        // TODO grab this value from PackageSettings
6603        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6604            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6605                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6606            }
6607        }
6608
6609        // TODO: extend to support forward-locked splits
6610        String resourcePath = null;
6611        String baseResourcePath = null;
6612        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6613            if (ps != null && ps.resourcePathString != null) {
6614                resourcePath = ps.resourcePathString;
6615                baseResourcePath = ps.resourcePathString;
6616            } else {
6617                // Should not happen at all. Just log an error.
6618                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6619            }
6620        } else {
6621            resourcePath = pkg.codePath;
6622            baseResourcePath = pkg.baseCodePath;
6623        }
6624
6625        // Set application objects path explicitly.
6626        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6627        pkg.setApplicationInfoCodePath(pkg.codePath);
6628        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6629        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6630        pkg.setApplicationInfoResourcePath(resourcePath);
6631        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6632        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6633
6634        // Note that we invoke the following method only if we are about to unpack an application
6635        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6636                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6637
6638        /*
6639         * If the system app should be overridden by a previously installed
6640         * data, hide the system app now and let the /data/app scan pick it up
6641         * again.
6642         */
6643        if (shouldHideSystemApp) {
6644            synchronized (mPackages) {
6645                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6646            }
6647        }
6648
6649        return scannedPkg;
6650    }
6651
6652    private static String fixProcessName(String defProcessName,
6653            String processName, int uid) {
6654        if (processName == null) {
6655            return defProcessName;
6656        }
6657        return processName;
6658    }
6659
6660    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6661            throws PackageManagerException {
6662        if (pkgSetting.signatures.mSignatures != null) {
6663            // Already existing package. Make sure signatures match
6664            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6665                    == PackageManager.SIGNATURE_MATCH;
6666            if (!match) {
6667                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6668                        == PackageManager.SIGNATURE_MATCH;
6669            }
6670            if (!match) {
6671                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6672                        == PackageManager.SIGNATURE_MATCH;
6673            }
6674            if (!match) {
6675                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6676                        + pkg.packageName + " signatures do not match the "
6677                        + "previously installed version; ignoring!");
6678            }
6679        }
6680
6681        // Check for shared user signatures
6682        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6683            // Already existing package. Make sure signatures match
6684            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6685                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6686            if (!match) {
6687                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6688                        == PackageManager.SIGNATURE_MATCH;
6689            }
6690            if (!match) {
6691                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6692                        == PackageManager.SIGNATURE_MATCH;
6693            }
6694            if (!match) {
6695                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6696                        "Package " + pkg.packageName
6697                        + " has no signatures that match those in shared user "
6698                        + pkgSetting.sharedUser.name + "; ignoring!");
6699            }
6700        }
6701    }
6702
6703    /**
6704     * Enforces that only the system UID or root's UID can call a method exposed
6705     * via Binder.
6706     *
6707     * @param message used as message if SecurityException is thrown
6708     * @throws SecurityException if the caller is not system or root
6709     */
6710    private static final void enforceSystemOrRoot(String message) {
6711        final int uid = Binder.getCallingUid();
6712        if (uid != Process.SYSTEM_UID && uid != 0) {
6713            throw new SecurityException(message);
6714        }
6715    }
6716
6717    @Override
6718    public void performFstrimIfNeeded() {
6719        enforceSystemOrRoot("Only the system can request fstrim");
6720
6721        // Before everything else, see whether we need to fstrim.
6722        try {
6723            IMountService ms = PackageHelper.getMountService();
6724            if (ms != null) {
6725                final boolean isUpgrade = isUpgrade();
6726                boolean doTrim = isUpgrade;
6727                if (doTrim) {
6728                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6729                } else {
6730                    final long interval = android.provider.Settings.Global.getLong(
6731                            mContext.getContentResolver(),
6732                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6733                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6734                    if (interval > 0) {
6735                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6736                        if (timeSinceLast > interval) {
6737                            doTrim = true;
6738                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6739                                    + "; running immediately");
6740                        }
6741                    }
6742                }
6743                if (doTrim) {
6744                    if (!isFirstBoot()) {
6745                        try {
6746                            ActivityManagerNative.getDefault().showBootMessage(
6747                                    mContext.getResources().getString(
6748                                            R.string.android_upgrading_fstrim), true);
6749                        } catch (RemoteException e) {
6750                        }
6751                    }
6752                    ms.runMaintenance();
6753                }
6754            } else {
6755                Slog.e(TAG, "Mount service unavailable!");
6756            }
6757        } catch (RemoteException e) {
6758            // Can't happen; MountService is local
6759        }
6760    }
6761
6762    @Override
6763    public void extractPackagesIfNeeded() {
6764        enforceSystemOrRoot("Only the system can request package extraction");
6765
6766        // Extract pacakges only if profile-guided compilation is enabled because
6767        // otherwise BackgroundDexOptService will not dexopt them later.
6768        if (mUseJitProfiles) {
6769            ArraySet<String> pkgs = getOptimizablePackages();
6770            if (pkgs != null) {
6771                for (String pkg : pkgs) {
6772                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6773                            true /* extractOnly */, false /* force */);
6774                }
6775            }
6776        }
6777    }
6778
6779    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6780        List<ResolveInfo> ris = null;
6781        try {
6782            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6783                    intent, null, 0, userId);
6784        } catch (RemoteException e) {
6785        }
6786        ArraySet<String> pkgNames = new ArraySet<String>();
6787        if (ris != null) {
6788            for (ResolveInfo ri : ris) {
6789                pkgNames.add(ri.activityInfo.packageName);
6790            }
6791        }
6792        return pkgNames;
6793    }
6794
6795    @Override
6796    public void notifyPackageUse(String packageName) {
6797        synchronized (mPackages) {
6798            PackageParser.Package p = mPackages.get(packageName);
6799            if (p == null) {
6800                return;
6801            }
6802            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6803        }
6804    }
6805
6806    // TODO: this is not used nor needed. Delete it.
6807    @Override
6808    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6809        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6810                false /* extractOnly */, false /* force */);
6811    }
6812
6813    @Override
6814    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6815            boolean extractOnly, boolean force) {
6816        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6817    }
6818
6819    private boolean performDexOptTraced(String packageName, String instructionSet,
6820                boolean useProfiles, boolean extractOnly, boolean force) {
6821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6822        try {
6823            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6824                    force);
6825        } finally {
6826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6827        }
6828    }
6829
6830    private boolean performDexOptInternal(String packageName, String instructionSet,
6831                boolean useProfiles, boolean extractOnly, boolean force) {
6832        PackageParser.Package p;
6833        final String targetInstructionSet;
6834        synchronized (mPackages) {
6835            p = mPackages.get(packageName);
6836            if (p == null) {
6837                return false;
6838            }
6839            mPackageUsage.write(false);
6840
6841            targetInstructionSet = instructionSet != null ? instructionSet :
6842                    getPrimaryInstructionSet(p.applicationInfo);
6843            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6844                // Skip only if we do not use profiles since they might trigger a recompilation.
6845                return false;
6846            }
6847        }
6848        long callingId = Binder.clearCallingIdentity();
6849        try {
6850            synchronized (mInstallLock) {
6851                final String[] instructionSets = new String[] { targetInstructionSet };
6852                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6853                        useProfiles, extractOnly, force);
6854                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6855            }
6856        } finally {
6857            Binder.restoreCallingIdentity(callingId);
6858        }
6859    }
6860
6861    public ArraySet<String> getOptimizablePackages() {
6862        ArraySet<String> pkgs = new ArraySet<String>();
6863        synchronized (mPackages) {
6864            for (PackageParser.Package p : mPackages.values()) {
6865                if (PackageDexOptimizer.canOptimizePackage(p)) {
6866                    pkgs.add(p.packageName);
6867                }
6868            }
6869        }
6870        return pkgs;
6871    }
6872
6873    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6874            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6875        // Select the dex optimizer based on the force parameter.
6876        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6877        //       allocate an object here.
6878        PackageDexOptimizer pdo = force
6879                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6880                : mPackageDexOptimizer;
6881
6882        // Optimize all dependencies first. Note: we ignore the return value and march on
6883        // on errors.
6884        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6885        if (!deps.isEmpty()) {
6886            for (PackageParser.Package depPackage : deps) {
6887                // TODO: Analyze and investigate if we (should) profile libraries.
6888                // Currently this will do a full compilation of the library.
6889                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6890                        false /* extractOnly */);
6891            }
6892        }
6893
6894        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6895    }
6896
6897    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6898        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6899            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6900            Set<String> collectedNames = new HashSet<>();
6901            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6902
6903            retValue.remove(p);
6904
6905            return retValue;
6906        } else {
6907            return Collections.emptyList();
6908        }
6909    }
6910
6911    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6912            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6913        if (!collectedNames.contains(p.packageName)) {
6914            collectedNames.add(p.packageName);
6915            collected.add(p);
6916
6917            if (p.usesLibraries != null) {
6918                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6919            }
6920            if (p.usesOptionalLibraries != null) {
6921                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6922                        collectedNames);
6923            }
6924        }
6925    }
6926
6927    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6928            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6929        for (String libName : libs) {
6930            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6931            if (libPkg != null) {
6932                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6933            }
6934        }
6935    }
6936
6937    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6938        synchronized (mPackages) {
6939            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6940            if (lib != null && lib.apk != null) {
6941                return mPackages.get(lib.apk);
6942            }
6943        }
6944        return null;
6945    }
6946
6947    public void shutdown() {
6948        mPackageUsage.write(true);
6949    }
6950
6951    @Override
6952    public void forceDexOpt(String packageName) {
6953        enforceSystemOrRoot("forceDexOpt");
6954
6955        PackageParser.Package pkg;
6956        synchronized (mPackages) {
6957            pkg = mPackages.get(packageName);
6958            if (pkg == null) {
6959                throw new IllegalArgumentException("Unknown package: " + packageName);
6960            }
6961        }
6962
6963        synchronized (mInstallLock) {
6964            final String[] instructionSets = new String[] {
6965                    getPrimaryInstructionSet(pkg.applicationInfo) };
6966
6967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6968
6969            // Whoever is calling forceDexOpt wants a fully compiled package.
6970            // Don't use profiles since that may cause compilation to be skipped.
6971            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6972                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6973
6974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6975            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6976                throw new IllegalStateException("Failed to dexopt: " + res);
6977            }
6978        }
6979    }
6980
6981    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6982        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6983            Slog.w(TAG, "Unable to update from " + oldPkg.name
6984                    + " to " + newPkg.packageName
6985                    + ": old package not in system partition");
6986            return false;
6987        } else if (mPackages.get(oldPkg.name) != null) {
6988            Slog.w(TAG, "Unable to update from " + oldPkg.name
6989                    + " to " + newPkg.packageName
6990                    + ": old package still exists");
6991            return false;
6992        }
6993        return true;
6994    }
6995
6996    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6997        // TODO: triage flags as part of 26466827
6998        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6999
7000        boolean res = true;
7001        final int[] users = sUserManager.getUserIds();
7002        for (int user : users) {
7003            try {
7004                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7005            } catch (InstallerException e) {
7006                Slog.w(TAG, "Failed to delete data directory", e);
7007                res = false;
7008            }
7009        }
7010        return res;
7011    }
7012
7013    void removeCodePathLI(File codePath) {
7014        if (codePath.isDirectory()) {
7015            try {
7016                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7017            } catch (InstallerException e) {
7018                Slog.w(TAG, "Failed to remove code path", e);
7019            }
7020        } else {
7021            codePath.delete();
7022        }
7023    }
7024
7025    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7026        try {
7027            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7028        } catch (InstallerException e) {
7029            Slog.w(TAG, "Failed to destroy app data", e);
7030        }
7031    }
7032
7033    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7034            int appId, String seinfo) {
7035        try {
7036            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7037        } catch (InstallerException e) {
7038            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7039        }
7040    }
7041
7042    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7043        final PackageParser.Package pkg;
7044        synchronized (mPackages) {
7045            pkg = mPackages.get(packageName);
7046        }
7047        if (pkg == null) {
7048            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7049            return;
7050        }
7051        deleteCodeCacheDirsLI(pkg);
7052    }
7053
7054    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7055        // TODO: triage flags as part of 26466827
7056        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7057
7058        int[] users = sUserManager.getUserIds();
7059        int res = 0;
7060        for (int user : users) {
7061            // Remove the parent code cache
7062            try {
7063                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7064                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7065            } catch (InstallerException e) {
7066                Slog.w(TAG, "Failed to delete code cache directory", e);
7067            }
7068            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7069            for (int i = 0; i < childCount; i++) {
7070                PackageParser.Package childPkg = pkg.childPackages.get(i);
7071                // Remove the child code cache
7072                try {
7073                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7074                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7075                } catch (InstallerException e) {
7076                    Slog.w(TAG, "Failed to delete code cache directory", e);
7077                }
7078            }
7079        }
7080    }
7081
7082    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7083            long lastUpdateTime) {
7084        // Set parent install/update time
7085        PackageSetting ps = (PackageSetting) pkg.mExtras;
7086        if (ps != null) {
7087            ps.firstInstallTime = firstInstallTime;
7088            ps.lastUpdateTime = lastUpdateTime;
7089        }
7090        // Set children install/update time
7091        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7092        for (int i = 0; i < childCount; i++) {
7093            PackageParser.Package childPkg = pkg.childPackages.get(i);
7094            ps = (PackageSetting) childPkg.mExtras;
7095            if (ps != null) {
7096                ps.firstInstallTime = firstInstallTime;
7097                ps.lastUpdateTime = lastUpdateTime;
7098            }
7099        }
7100    }
7101
7102    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7103            PackageParser.Package changingLib) {
7104        if (file.path != null) {
7105            usesLibraryFiles.add(file.path);
7106            return;
7107        }
7108        PackageParser.Package p = mPackages.get(file.apk);
7109        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7110            // If we are doing this while in the middle of updating a library apk,
7111            // then we need to make sure to use that new apk for determining the
7112            // dependencies here.  (We haven't yet finished committing the new apk
7113            // to the package manager state.)
7114            if (p == null || p.packageName.equals(changingLib.packageName)) {
7115                p = changingLib;
7116            }
7117        }
7118        if (p != null) {
7119            usesLibraryFiles.addAll(p.getAllCodePaths());
7120        }
7121    }
7122
7123    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7124            PackageParser.Package changingLib) throws PackageManagerException {
7125        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7126            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7127            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7128            for (int i=0; i<N; i++) {
7129                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7130                if (file == null) {
7131                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7132                            "Package " + pkg.packageName + " requires unavailable shared library "
7133                            + pkg.usesLibraries.get(i) + "; failing!");
7134                }
7135                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7136            }
7137            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7138            for (int i=0; i<N; i++) {
7139                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7140                if (file == null) {
7141                    Slog.w(TAG, "Package " + pkg.packageName
7142                            + " desires unavailable shared library "
7143                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7144                } else {
7145                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7146                }
7147            }
7148            N = usesLibraryFiles.size();
7149            if (N > 0) {
7150                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7151            } else {
7152                pkg.usesLibraryFiles = null;
7153            }
7154        }
7155    }
7156
7157    private static boolean hasString(List<String> list, List<String> which) {
7158        if (list == null) {
7159            return false;
7160        }
7161        for (int i=list.size()-1; i>=0; i--) {
7162            for (int j=which.size()-1; j>=0; j--) {
7163                if (which.get(j).equals(list.get(i))) {
7164                    return true;
7165                }
7166            }
7167        }
7168        return false;
7169    }
7170
7171    private void updateAllSharedLibrariesLPw() {
7172        for (PackageParser.Package pkg : mPackages.values()) {
7173            try {
7174                updateSharedLibrariesLPw(pkg, null);
7175            } catch (PackageManagerException e) {
7176                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7177            }
7178        }
7179    }
7180
7181    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7182            PackageParser.Package changingPkg) {
7183        ArrayList<PackageParser.Package> res = null;
7184        for (PackageParser.Package pkg : mPackages.values()) {
7185            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7186                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7187                if (res == null) {
7188                    res = new ArrayList<PackageParser.Package>();
7189                }
7190                res.add(pkg);
7191                try {
7192                    updateSharedLibrariesLPw(pkg, changingPkg);
7193                } catch (PackageManagerException e) {
7194                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7195                }
7196            }
7197        }
7198        return res;
7199    }
7200
7201    /**
7202     * Derive the value of the {@code cpuAbiOverride} based on the provided
7203     * value and an optional stored value from the package settings.
7204     */
7205    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7206        String cpuAbiOverride = null;
7207
7208        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7209            cpuAbiOverride = null;
7210        } else if (abiOverride != null) {
7211            cpuAbiOverride = abiOverride;
7212        } else if (settings != null) {
7213            cpuAbiOverride = settings.cpuAbiOverrideString;
7214        }
7215
7216        return cpuAbiOverride;
7217    }
7218
7219    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7220            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7221        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7222        // If the package has children and this is the first dive in the function
7223        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7224        // whether all packages (parent and children) would be successfully scanned
7225        // before the actual scan since scanning mutates internal state and we want
7226        // to atomically install the package and its children.
7227        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7228            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7229                scanFlags |= SCAN_CHECK_ONLY;
7230            }
7231        } else {
7232            scanFlags &= ~SCAN_CHECK_ONLY;
7233        }
7234
7235        final PackageParser.Package scannedPkg;
7236        try {
7237            // Scan the parent
7238            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7239            // Scan the children
7240            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7241            for (int i = 0; i < childCount; i++) {
7242                PackageParser.Package childPkg = pkg.childPackages.get(i);
7243                scanPackageLI(childPkg, parseFlags,
7244                        scanFlags, currentTime, user);
7245            }
7246        } finally {
7247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7248        }
7249
7250        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7251            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7252        }
7253
7254        return scannedPkg;
7255    }
7256
7257    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7258            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7259        boolean success = false;
7260        try {
7261            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7262                    currentTime, user);
7263            success = true;
7264            return res;
7265        } finally {
7266            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7267                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7268            }
7269        }
7270    }
7271
7272    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7273            int scanFlags, long currentTime, UserHandle user)
7274            throws PackageManagerException {
7275        final File scanFile = new File(pkg.codePath);
7276        if (pkg.applicationInfo.getCodePath() == null ||
7277                pkg.applicationInfo.getResourcePath() == null) {
7278            // Bail out. The resource and code paths haven't been set.
7279            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7280                    "Code and resource paths haven't been set correctly");
7281        }
7282
7283        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7284            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7285        } else {
7286            // Only allow system apps to be flagged as core apps.
7287            pkg.coreApp = false;
7288        }
7289
7290        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7291            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7292        }
7293
7294        if (mCustomResolverComponentName != null &&
7295                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7296            setUpCustomResolverActivity(pkg);
7297        }
7298
7299        if (pkg.packageName.equals("android")) {
7300            synchronized (mPackages) {
7301                if (mAndroidApplication != null) {
7302                    Slog.w(TAG, "*************************************************");
7303                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7304                    Slog.w(TAG, " file=" + scanFile);
7305                    Slog.w(TAG, "*************************************************");
7306                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7307                            "Core android package being redefined.  Skipping.");
7308                }
7309
7310                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7311                    // Set up information for our fall-back user intent resolution activity.
7312                    mPlatformPackage = pkg;
7313                    pkg.mVersionCode = mSdkVersion;
7314                    mAndroidApplication = pkg.applicationInfo;
7315
7316                    if (!mResolverReplaced) {
7317                        mResolveActivity.applicationInfo = mAndroidApplication;
7318                        mResolveActivity.name = ResolverActivity.class.getName();
7319                        mResolveActivity.packageName = mAndroidApplication.packageName;
7320                        mResolveActivity.processName = "system:ui";
7321                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7322                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7323                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7324                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7325                        mResolveActivity.exported = true;
7326                        mResolveActivity.enabled = true;
7327                        mResolveInfo.activityInfo = mResolveActivity;
7328                        mResolveInfo.priority = 0;
7329                        mResolveInfo.preferredOrder = 0;
7330                        mResolveInfo.match = 0;
7331                        mResolveComponentName = new ComponentName(
7332                                mAndroidApplication.packageName, mResolveActivity.name);
7333                    }
7334                }
7335            }
7336        }
7337
7338        if (DEBUG_PACKAGE_SCANNING) {
7339            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7340                Log.d(TAG, "Scanning package " + pkg.packageName);
7341        }
7342
7343        synchronized (mPackages) {
7344            if (mPackages.containsKey(pkg.packageName)
7345                    || mSharedLibraries.containsKey(pkg.packageName)) {
7346                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7347                        "Application package " + pkg.packageName
7348                                + " already installed.  Skipping duplicate.");
7349            }
7350
7351            // If we're only installing presumed-existing packages, require that the
7352            // scanned APK is both already known and at the path previously established
7353            // for it.  Previously unknown packages we pick up normally, but if we have an
7354            // a priori expectation about this package's install presence, enforce it.
7355            // With a singular exception for new system packages. When an OTA contains
7356            // a new system package, we allow the codepath to change from a system location
7357            // to the user-installed location. If we don't allow this change, any newer,
7358            // user-installed version of the application will be ignored.
7359            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7360                if (mExpectingBetter.containsKey(pkg.packageName)) {
7361                    logCriticalInfo(Log.WARN,
7362                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7363                } else {
7364                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7365                    if (known != null) {
7366                        if (DEBUG_PACKAGE_SCANNING) {
7367                            Log.d(TAG, "Examining " + pkg.codePath
7368                                    + " and requiring known paths " + known.codePathString
7369                                    + " & " + known.resourcePathString);
7370                        }
7371                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7372                                || !pkg.applicationInfo.getResourcePath().equals(
7373                                known.resourcePathString)) {
7374                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7375                                    "Application package " + pkg.packageName
7376                                            + " found at " + pkg.applicationInfo.getCodePath()
7377                                            + " but expected at " + known.codePathString
7378                                            + "; ignoring.");
7379                        }
7380                    }
7381                }
7382            }
7383        }
7384
7385        // Initialize package source and resource directories
7386        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7387        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7388
7389        SharedUserSetting suid = null;
7390        PackageSetting pkgSetting = null;
7391
7392        if (!isSystemApp(pkg)) {
7393            // Only system apps can use these features.
7394            pkg.mOriginalPackages = null;
7395            pkg.mRealPackage = null;
7396            pkg.mAdoptPermissions = null;
7397        }
7398
7399        // Getting the package setting may have a side-effect, so if we
7400        // are only checking if scan would succeed, stash a copy of the
7401        // old setting to restore at the end.
7402        PackageSetting nonMutatedPs = null;
7403
7404        // writer
7405        synchronized (mPackages) {
7406            if (pkg.mSharedUserId != null) {
7407                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7408                if (suid == null) {
7409                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7410                            "Creating application package " + pkg.packageName
7411                            + " for shared user failed");
7412                }
7413                if (DEBUG_PACKAGE_SCANNING) {
7414                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7415                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7416                                + "): packages=" + suid.packages);
7417                }
7418            }
7419
7420            // Check if we are renaming from an original package name.
7421            PackageSetting origPackage = null;
7422            String realName = null;
7423            if (pkg.mOriginalPackages != null) {
7424                // This package may need to be renamed to a previously
7425                // installed name.  Let's check on that...
7426                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7427                if (pkg.mOriginalPackages.contains(renamed)) {
7428                    // This package had originally been installed as the
7429                    // original name, and we have already taken care of
7430                    // transitioning to the new one.  Just update the new
7431                    // one to continue using the old name.
7432                    realName = pkg.mRealPackage;
7433                    if (!pkg.packageName.equals(renamed)) {
7434                        // Callers into this function may have already taken
7435                        // care of renaming the package; only do it here if
7436                        // it is not already done.
7437                        pkg.setPackageName(renamed);
7438                    }
7439
7440                } else {
7441                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7442                        if ((origPackage = mSettings.peekPackageLPr(
7443                                pkg.mOriginalPackages.get(i))) != null) {
7444                            // We do have the package already installed under its
7445                            // original name...  should we use it?
7446                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7447                                // New package is not compatible with original.
7448                                origPackage = null;
7449                                continue;
7450                            } else if (origPackage.sharedUser != null) {
7451                                // Make sure uid is compatible between packages.
7452                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7453                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7454                                            + " to " + pkg.packageName + ": old uid "
7455                                            + origPackage.sharedUser.name
7456                                            + " differs from " + pkg.mSharedUserId);
7457                                    origPackage = null;
7458                                    continue;
7459                                }
7460                            } else {
7461                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7462                                        + pkg.packageName + " to old name " + origPackage.name);
7463                            }
7464                            break;
7465                        }
7466                    }
7467                }
7468            }
7469
7470            if (mTransferedPackages.contains(pkg.packageName)) {
7471                Slog.w(TAG, "Package " + pkg.packageName
7472                        + " was transferred to another, but its .apk remains");
7473            }
7474
7475            // See comments in nonMutatedPs declaration
7476            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7477                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7478                if (foundPs != null) {
7479                    nonMutatedPs = new PackageSetting(foundPs);
7480                }
7481            }
7482
7483            // Just create the setting, don't add it yet. For already existing packages
7484            // the PkgSetting exists already and doesn't have to be created.
7485            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7486                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7487                    pkg.applicationInfo.primaryCpuAbi,
7488                    pkg.applicationInfo.secondaryCpuAbi,
7489                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7490                    user, false);
7491            if (pkgSetting == null) {
7492                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7493                        "Creating application package " + pkg.packageName + " failed");
7494            }
7495
7496            if (pkgSetting.origPackage != null) {
7497                // If we are first transitioning from an original package,
7498                // fix up the new package's name now.  We need to do this after
7499                // looking up the package under its new name, so getPackageLP
7500                // can take care of fiddling things correctly.
7501                pkg.setPackageName(origPackage.name);
7502
7503                // File a report about this.
7504                String msg = "New package " + pkgSetting.realName
7505                        + " renamed to replace old package " + pkgSetting.name;
7506                reportSettingsProblem(Log.WARN, msg);
7507
7508                // Make a note of it.
7509                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7510                    mTransferedPackages.add(origPackage.name);
7511                }
7512
7513                // No longer need to retain this.
7514                pkgSetting.origPackage = null;
7515            }
7516
7517            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7518                // Make a note of it.
7519                mTransferedPackages.add(pkg.packageName);
7520            }
7521
7522            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7523                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7524            }
7525
7526            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7527                // Check all shared libraries and map to their actual file path.
7528                // We only do this here for apps not on a system dir, because those
7529                // are the only ones that can fail an install due to this.  We
7530                // will take care of the system apps by updating all of their
7531                // library paths after the scan is done.
7532                updateSharedLibrariesLPw(pkg, null);
7533            }
7534
7535            if (mFoundPolicyFile) {
7536                SELinuxMMAC.assignSeinfoValue(pkg);
7537            }
7538
7539            pkg.applicationInfo.uid = pkgSetting.appId;
7540            pkg.mExtras = pkgSetting;
7541            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7542                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7543                    // We just determined the app is signed correctly, so bring
7544                    // over the latest parsed certs.
7545                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7546                } else {
7547                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7548                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7549                                "Package " + pkg.packageName + " upgrade keys do not match the "
7550                                + "previously installed version");
7551                    } else {
7552                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7553                        String msg = "System package " + pkg.packageName
7554                            + " signature changed; retaining data.";
7555                        reportSettingsProblem(Log.WARN, msg);
7556                    }
7557                }
7558            } else {
7559                try {
7560                    verifySignaturesLP(pkgSetting, pkg);
7561                    // We just determined the app is signed correctly, so bring
7562                    // over the latest parsed certs.
7563                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7564                } catch (PackageManagerException e) {
7565                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7566                        throw e;
7567                    }
7568                    // The signature has changed, but this package is in the system
7569                    // image...  let's recover!
7570                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7571                    // However...  if this package is part of a shared user, but it
7572                    // doesn't match the signature of the shared user, let's fail.
7573                    // What this means is that you can't change the signatures
7574                    // associated with an overall shared user, which doesn't seem all
7575                    // that unreasonable.
7576                    if (pkgSetting.sharedUser != null) {
7577                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7578                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7579                            throw new PackageManagerException(
7580                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7581                                            "Signature mismatch for shared user: "
7582                                            + pkgSetting.sharedUser);
7583                        }
7584                    }
7585                    // File a report about this.
7586                    String msg = "System package " + pkg.packageName
7587                        + " signature changed; retaining data.";
7588                    reportSettingsProblem(Log.WARN, msg);
7589                }
7590            }
7591            // Verify that this new package doesn't have any content providers
7592            // that conflict with existing packages.  Only do this if the
7593            // package isn't already installed, since we don't want to break
7594            // things that are installed.
7595            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7596                final int N = pkg.providers.size();
7597                int i;
7598                for (i=0; i<N; i++) {
7599                    PackageParser.Provider p = pkg.providers.get(i);
7600                    if (p.info.authority != null) {
7601                        String names[] = p.info.authority.split(";");
7602                        for (int j = 0; j < names.length; j++) {
7603                            if (mProvidersByAuthority.containsKey(names[j])) {
7604                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7605                                final String otherPackageName =
7606                                        ((other != null && other.getComponentName() != null) ?
7607                                                other.getComponentName().getPackageName() : "?");
7608                                throw new PackageManagerException(
7609                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7610                                                "Can't install because provider name " + names[j]
7611                                                + " (in package " + pkg.applicationInfo.packageName
7612                                                + ") is already used by " + otherPackageName);
7613                            }
7614                        }
7615                    }
7616                }
7617            }
7618
7619            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7620                // This package wants to adopt ownership of permissions from
7621                // another package.
7622                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7623                    final String origName = pkg.mAdoptPermissions.get(i);
7624                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7625                    if (orig != null) {
7626                        if (verifyPackageUpdateLPr(orig, pkg)) {
7627                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7628                                    + pkg.packageName);
7629                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7630                        }
7631                    }
7632                }
7633            }
7634        }
7635
7636        final String pkgName = pkg.packageName;
7637
7638        final long scanFileTime = scanFile.lastModified();
7639        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7640        pkg.applicationInfo.processName = fixProcessName(
7641                pkg.applicationInfo.packageName,
7642                pkg.applicationInfo.processName,
7643                pkg.applicationInfo.uid);
7644
7645        if (pkg != mPlatformPackage) {
7646            // Get all of our default paths setup
7647            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7648        }
7649
7650        final String path = scanFile.getPath();
7651        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7652
7653        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7654            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7655
7656            // Some system apps still use directory structure for native libraries
7657            // in which case we might end up not detecting abi solely based on apk
7658            // structure. Try to detect abi based on directory structure.
7659            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7660                    pkg.applicationInfo.primaryCpuAbi == null) {
7661                setBundledAppAbisAndRoots(pkg, pkgSetting);
7662                setNativeLibraryPaths(pkg);
7663            }
7664
7665        } else {
7666            if ((scanFlags & SCAN_MOVE) != 0) {
7667                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7668                // but we already have this packages package info in the PackageSetting. We just
7669                // use that and derive the native library path based on the new codepath.
7670                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7671                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7672            }
7673
7674            // Set native library paths again. For moves, the path will be updated based on the
7675            // ABIs we've determined above. For non-moves, the path will be updated based on the
7676            // ABIs we determined during compilation, but the path will depend on the final
7677            // package path (after the rename away from the stage path).
7678            setNativeLibraryPaths(pkg);
7679        }
7680
7681        // This is a special case for the "system" package, where the ABI is
7682        // dictated by the zygote configuration (and init.rc). We should keep track
7683        // of this ABI so that we can deal with "normal" applications that run under
7684        // the same UID correctly.
7685        if (mPlatformPackage == pkg) {
7686            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7687                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7688        }
7689
7690        // If there's a mismatch between the abi-override in the package setting
7691        // and the abiOverride specified for the install. Warn about this because we
7692        // would've already compiled the app without taking the package setting into
7693        // account.
7694        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7695            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7696                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7697                        " for package " + pkg.packageName);
7698            }
7699        }
7700
7701        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7702        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7703        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7704
7705        // Copy the derived override back to the parsed package, so that we can
7706        // update the package settings accordingly.
7707        pkg.cpuAbiOverride = cpuAbiOverride;
7708
7709        if (DEBUG_ABI_SELECTION) {
7710            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7711                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7712                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7713        }
7714
7715        // Push the derived path down into PackageSettings so we know what to
7716        // clean up at uninstall time.
7717        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7718
7719        if (DEBUG_ABI_SELECTION) {
7720            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7721                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7722                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7723        }
7724
7725        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7726            // We don't do this here during boot because we can do it all
7727            // at once after scanning all existing packages.
7728            //
7729            // We also do this *before* we perform dexopt on this package, so that
7730            // we can avoid redundant dexopts, and also to make sure we've got the
7731            // code and package path correct.
7732            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7733                    pkg, true /* boot complete */);
7734        }
7735
7736        if (mFactoryTest && pkg.requestedPermissions.contains(
7737                android.Manifest.permission.FACTORY_TEST)) {
7738            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7739        }
7740
7741        ArrayList<PackageParser.Package> clientLibPkgs = null;
7742
7743        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7744            if (nonMutatedPs != null) {
7745                synchronized (mPackages) {
7746                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7747                }
7748            }
7749            return pkg;
7750        }
7751
7752        // Only privileged apps and updated privileged apps can add child packages.
7753        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7754            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7755                throw new PackageManagerException("Only privileged apps and updated "
7756                        + "privileged apps can add child packages. Ignoring package "
7757                        + pkg.packageName);
7758            }
7759            final int childCount = pkg.childPackages.size();
7760            for (int i = 0; i < childCount; i++) {
7761                PackageParser.Package childPkg = pkg.childPackages.get(i);
7762                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7763                        childPkg.packageName)) {
7764                    throw new PackageManagerException("Cannot override a child package of "
7765                            + "another disabled system app. Ignoring package " + pkg.packageName);
7766                }
7767            }
7768        }
7769
7770        // writer
7771        synchronized (mPackages) {
7772            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7773                // Only system apps can add new shared libraries.
7774                if (pkg.libraryNames != null) {
7775                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7776                        String name = pkg.libraryNames.get(i);
7777                        boolean allowed = false;
7778                        if (pkg.isUpdatedSystemApp()) {
7779                            // New library entries can only be added through the
7780                            // system image.  This is important to get rid of a lot
7781                            // of nasty edge cases: for example if we allowed a non-
7782                            // system update of the app to add a library, then uninstalling
7783                            // the update would make the library go away, and assumptions
7784                            // we made such as through app install filtering would now
7785                            // have allowed apps on the device which aren't compatible
7786                            // with it.  Better to just have the restriction here, be
7787                            // conservative, and create many fewer cases that can negatively
7788                            // impact the user experience.
7789                            final PackageSetting sysPs = mSettings
7790                                    .getDisabledSystemPkgLPr(pkg.packageName);
7791                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7792                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7793                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7794                                        allowed = true;
7795                                        break;
7796                                    }
7797                                }
7798                            }
7799                        } else {
7800                            allowed = true;
7801                        }
7802                        if (allowed) {
7803                            if (!mSharedLibraries.containsKey(name)) {
7804                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7805                            } else if (!name.equals(pkg.packageName)) {
7806                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7807                                        + name + " already exists; skipping");
7808                            }
7809                        } else {
7810                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7811                                    + name + " that is not declared on system image; skipping");
7812                        }
7813                    }
7814                    if ((scanFlags & SCAN_BOOTING) == 0) {
7815                        // If we are not booting, we need to update any applications
7816                        // that are clients of our shared library.  If we are booting,
7817                        // this will all be done once the scan is complete.
7818                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7819                    }
7820                }
7821            }
7822        }
7823
7824        // Request the ActivityManager to kill the process(only for existing packages)
7825        // so that we do not end up in a confused state while the user is still using the older
7826        // version of the application while the new one gets installed.
7827        if ((scanFlags & SCAN_REPLACING) != 0) {
7828            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7829
7830            killApplication(pkg.applicationInfo.packageName,
7831                        pkg.applicationInfo.uid, "replace pkg");
7832
7833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7834        }
7835
7836        // Also need to kill any apps that are dependent on the library.
7837        if (clientLibPkgs != null) {
7838            for (int i=0; i<clientLibPkgs.size(); i++) {
7839                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7840                killApplication(clientPkg.applicationInfo.packageName,
7841                        clientPkg.applicationInfo.uid, "update lib");
7842            }
7843        }
7844
7845        // Make sure we're not adding any bogus keyset info
7846        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7847        ksms.assertScannedPackageValid(pkg);
7848
7849        // writer
7850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7851
7852        boolean createIdmapFailed = false;
7853        synchronized (mPackages) {
7854            // We don't expect installation to fail beyond this point
7855
7856            // Add the new setting to mSettings
7857            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7858            // Add the new setting to mPackages
7859            mPackages.put(pkg.applicationInfo.packageName, pkg);
7860            // Make sure we don't accidentally delete its data.
7861            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7862            while (iter.hasNext()) {
7863                PackageCleanItem item = iter.next();
7864                if (pkgName.equals(item.packageName)) {
7865                    iter.remove();
7866                }
7867            }
7868
7869            // Take care of first install / last update times.
7870            if (currentTime != 0) {
7871                if (pkgSetting.firstInstallTime == 0) {
7872                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7873                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7874                    pkgSetting.lastUpdateTime = currentTime;
7875                }
7876            } else if (pkgSetting.firstInstallTime == 0) {
7877                // We need *something*.  Take time time stamp of the file.
7878                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7879            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7880                if (scanFileTime != pkgSetting.timeStamp) {
7881                    // A package on the system image has changed; consider this
7882                    // to be an update.
7883                    pkgSetting.lastUpdateTime = scanFileTime;
7884                }
7885            }
7886
7887            // Add the package's KeySets to the global KeySetManagerService
7888            ksms.addScannedPackageLPw(pkg);
7889
7890            int N = pkg.providers.size();
7891            StringBuilder r = null;
7892            int i;
7893            for (i=0; i<N; i++) {
7894                PackageParser.Provider p = pkg.providers.get(i);
7895                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7896                        p.info.processName, pkg.applicationInfo.uid);
7897                mProviders.addProvider(p);
7898                p.syncable = p.info.isSyncable;
7899                if (p.info.authority != null) {
7900                    String names[] = p.info.authority.split(";");
7901                    p.info.authority = null;
7902                    for (int j = 0; j < names.length; j++) {
7903                        if (j == 1 && p.syncable) {
7904                            // We only want the first authority for a provider to possibly be
7905                            // syncable, so if we already added this provider using a different
7906                            // authority clear the syncable flag. We copy the provider before
7907                            // changing it because the mProviders object contains a reference
7908                            // to a provider that we don't want to change.
7909                            // Only do this for the second authority since the resulting provider
7910                            // object can be the same for all future authorities for this provider.
7911                            p = new PackageParser.Provider(p);
7912                            p.syncable = false;
7913                        }
7914                        if (!mProvidersByAuthority.containsKey(names[j])) {
7915                            mProvidersByAuthority.put(names[j], p);
7916                            if (p.info.authority == null) {
7917                                p.info.authority = names[j];
7918                            } else {
7919                                p.info.authority = p.info.authority + ";" + names[j];
7920                            }
7921                            if (DEBUG_PACKAGE_SCANNING) {
7922                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7923                                    Log.d(TAG, "Registered content provider: " + names[j]
7924                                            + ", className = " + p.info.name + ", isSyncable = "
7925                                            + p.info.isSyncable);
7926                            }
7927                        } else {
7928                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7929                            Slog.w(TAG, "Skipping provider name " + names[j] +
7930                                    " (in package " + pkg.applicationInfo.packageName +
7931                                    "): name already used by "
7932                                    + ((other != null && other.getComponentName() != null)
7933                                            ? other.getComponentName().getPackageName() : "?"));
7934                        }
7935                    }
7936                }
7937                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7938                    if (r == null) {
7939                        r = new StringBuilder(256);
7940                    } else {
7941                        r.append(' ');
7942                    }
7943                    r.append(p.info.name);
7944                }
7945            }
7946            if (r != null) {
7947                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7948            }
7949
7950            N = pkg.services.size();
7951            r = null;
7952            for (i=0; i<N; i++) {
7953                PackageParser.Service s = pkg.services.get(i);
7954                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7955                        s.info.processName, pkg.applicationInfo.uid);
7956                mServices.addService(s);
7957                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7958                    if (r == null) {
7959                        r = new StringBuilder(256);
7960                    } else {
7961                        r.append(' ');
7962                    }
7963                    r.append(s.info.name);
7964                }
7965            }
7966            if (r != null) {
7967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7968            }
7969
7970            N = pkg.receivers.size();
7971            r = null;
7972            for (i=0; i<N; i++) {
7973                PackageParser.Activity a = pkg.receivers.get(i);
7974                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7975                        a.info.processName, pkg.applicationInfo.uid);
7976                mReceivers.addActivity(a, "receiver");
7977                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7978                    if (r == null) {
7979                        r = new StringBuilder(256);
7980                    } else {
7981                        r.append(' ');
7982                    }
7983                    r.append(a.info.name);
7984                }
7985            }
7986            if (r != null) {
7987                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7988            }
7989
7990            N = pkg.activities.size();
7991            r = null;
7992            for (i=0; i<N; i++) {
7993                PackageParser.Activity a = pkg.activities.get(i);
7994                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7995                        a.info.processName, pkg.applicationInfo.uid);
7996                mActivities.addActivity(a, "activity");
7997                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7998                    if (r == null) {
7999                        r = new StringBuilder(256);
8000                    } else {
8001                        r.append(' ');
8002                    }
8003                    r.append(a.info.name);
8004                }
8005            }
8006            if (r != null) {
8007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8008            }
8009
8010            N = pkg.permissionGroups.size();
8011            r = null;
8012            for (i=0; i<N; i++) {
8013                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8014                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8015                if (cur == null) {
8016                    mPermissionGroups.put(pg.info.name, pg);
8017                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8018                        if (r == null) {
8019                            r = new StringBuilder(256);
8020                        } else {
8021                            r.append(' ');
8022                        }
8023                        r.append(pg.info.name);
8024                    }
8025                } else {
8026                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8027                            + pg.info.packageName + " ignored: original from "
8028                            + cur.info.packageName);
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("DUP:");
8036                        r.append(pg.info.name);
8037                    }
8038                }
8039            }
8040            if (r != null) {
8041                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8042            }
8043
8044            N = pkg.permissions.size();
8045            r = null;
8046            for (i=0; i<N; i++) {
8047                PackageParser.Permission p = pkg.permissions.get(i);
8048
8049                // Assume by default that we did not install this permission into the system.
8050                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8051
8052                // Now that permission groups have a special meaning, we ignore permission
8053                // groups for legacy apps to prevent unexpected behavior. In particular,
8054                // permissions for one app being granted to someone just becase they happen
8055                // to be in a group defined by another app (before this had no implications).
8056                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8057                    p.group = mPermissionGroups.get(p.info.group);
8058                    // Warn for a permission in an unknown group.
8059                    if (p.info.group != null && p.group == null) {
8060                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8061                                + p.info.packageName + " in an unknown group " + p.info.group);
8062                    }
8063                }
8064
8065                ArrayMap<String, BasePermission> permissionMap =
8066                        p.tree ? mSettings.mPermissionTrees
8067                                : mSettings.mPermissions;
8068                BasePermission bp = permissionMap.get(p.info.name);
8069
8070                // Allow system apps to redefine non-system permissions
8071                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8072                    final boolean currentOwnerIsSystem = (bp.perm != null
8073                            && isSystemApp(bp.perm.owner));
8074                    if (isSystemApp(p.owner)) {
8075                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8076                            // It's a built-in permission and no owner, take ownership now
8077                            bp.packageSetting = pkgSetting;
8078                            bp.perm = p;
8079                            bp.uid = pkg.applicationInfo.uid;
8080                            bp.sourcePackage = p.info.packageName;
8081                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8082                        } else if (!currentOwnerIsSystem) {
8083                            String msg = "New decl " + p.owner + " of permission  "
8084                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8085                            reportSettingsProblem(Log.WARN, msg);
8086                            bp = null;
8087                        }
8088                    }
8089                }
8090
8091                if (bp == null) {
8092                    bp = new BasePermission(p.info.name, p.info.packageName,
8093                            BasePermission.TYPE_NORMAL);
8094                    permissionMap.put(p.info.name, bp);
8095                }
8096
8097                if (bp.perm == null) {
8098                    if (bp.sourcePackage == null
8099                            || bp.sourcePackage.equals(p.info.packageName)) {
8100                        BasePermission tree = findPermissionTreeLP(p.info.name);
8101                        if (tree == null
8102                                || tree.sourcePackage.equals(p.info.packageName)) {
8103                            bp.packageSetting = pkgSetting;
8104                            bp.perm = p;
8105                            bp.uid = pkg.applicationInfo.uid;
8106                            bp.sourcePackage = p.info.packageName;
8107                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8108                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8109                                if (r == null) {
8110                                    r = new StringBuilder(256);
8111                                } else {
8112                                    r.append(' ');
8113                                }
8114                                r.append(p.info.name);
8115                            }
8116                        } else {
8117                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8118                                    + p.info.packageName + " ignored: base tree "
8119                                    + tree.name + " is from package "
8120                                    + tree.sourcePackage);
8121                        }
8122                    } else {
8123                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8124                                + p.info.packageName + " ignored: original from "
8125                                + bp.sourcePackage);
8126                    }
8127                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8128                    if (r == null) {
8129                        r = new StringBuilder(256);
8130                    } else {
8131                        r.append(' ');
8132                    }
8133                    r.append("DUP:");
8134                    r.append(p.info.name);
8135                }
8136                if (bp.perm == p) {
8137                    bp.protectionLevel = p.info.protectionLevel;
8138                }
8139            }
8140
8141            if (r != null) {
8142                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8143            }
8144
8145            N = pkg.instrumentation.size();
8146            r = null;
8147            for (i=0; i<N; i++) {
8148                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8149                a.info.packageName = pkg.applicationInfo.packageName;
8150                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8151                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8152                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8153                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8154                a.info.dataDir = pkg.applicationInfo.dataDir;
8155                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8156                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8157
8158                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8159                // need other information about the application, like the ABI and what not ?
8160                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8161                mInstrumentation.put(a.getComponentName(), a);
8162                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8163                    if (r == null) {
8164                        r = new StringBuilder(256);
8165                    } else {
8166                        r.append(' ');
8167                    }
8168                    r.append(a.info.name);
8169                }
8170            }
8171            if (r != null) {
8172                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8173            }
8174
8175            if (pkg.protectedBroadcasts != null) {
8176                N = pkg.protectedBroadcasts.size();
8177                for (i=0; i<N; i++) {
8178                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8179                }
8180            }
8181
8182            pkgSetting.setTimeStamp(scanFileTime);
8183
8184            // Create idmap files for pairs of (packages, overlay packages).
8185            // Note: "android", ie framework-res.apk, is handled by native layers.
8186            if (pkg.mOverlayTarget != null) {
8187                // This is an overlay package.
8188                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8189                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8190                        mOverlays.put(pkg.mOverlayTarget,
8191                                new ArrayMap<String, PackageParser.Package>());
8192                    }
8193                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8194                    map.put(pkg.packageName, pkg);
8195                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8196                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8197                        createIdmapFailed = true;
8198                    }
8199                }
8200            } else if (mOverlays.containsKey(pkg.packageName) &&
8201                    !pkg.packageName.equals("android")) {
8202                // This is a regular package, with one or more known overlay packages.
8203                createIdmapsForPackageLI(pkg);
8204            }
8205        }
8206
8207        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8208
8209        if (createIdmapFailed) {
8210            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8211                    "scanPackageLI failed to createIdmap");
8212        }
8213        return pkg;
8214    }
8215
8216    /**
8217     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8218     * is derived purely on the basis of the contents of {@code scanFile} and
8219     * {@code cpuAbiOverride}.
8220     *
8221     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8222     */
8223    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8224                                 String cpuAbiOverride, boolean extractLibs)
8225            throws PackageManagerException {
8226        // TODO: We can probably be smarter about this stuff. For installed apps,
8227        // we can calculate this information at install time once and for all. For
8228        // system apps, we can probably assume that this information doesn't change
8229        // after the first boot scan. As things stand, we do lots of unnecessary work.
8230
8231        // Give ourselves some initial paths; we'll come back for another
8232        // pass once we've determined ABI below.
8233        setNativeLibraryPaths(pkg);
8234
8235        // We would never need to extract libs for forward-locked and external packages,
8236        // since the container service will do it for us. We shouldn't attempt to
8237        // extract libs from system app when it was not updated.
8238        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8239                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8240            extractLibs = false;
8241        }
8242
8243        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8244        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8245
8246        NativeLibraryHelper.Handle handle = null;
8247        try {
8248            handle = NativeLibraryHelper.Handle.create(pkg);
8249            // TODO(multiArch): This can be null for apps that didn't go through the
8250            // usual installation process. We can calculate it again, like we
8251            // do during install time.
8252            //
8253            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8254            // unnecessary.
8255            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8256
8257            // Null out the abis so that they can be recalculated.
8258            pkg.applicationInfo.primaryCpuAbi = null;
8259            pkg.applicationInfo.secondaryCpuAbi = null;
8260            if (isMultiArch(pkg.applicationInfo)) {
8261                // Warn if we've set an abiOverride for multi-lib packages..
8262                // By definition, we need to copy both 32 and 64 bit libraries for
8263                // such packages.
8264                if (pkg.cpuAbiOverride != null
8265                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8266                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8267                }
8268
8269                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8270                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8271                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8272                    if (extractLibs) {
8273                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8274                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8275                                useIsaSpecificSubdirs);
8276                    } else {
8277                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8278                    }
8279                }
8280
8281                maybeThrowExceptionForMultiArchCopy(
8282                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8283
8284                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8285                    if (extractLibs) {
8286                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8287                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8288                                useIsaSpecificSubdirs);
8289                    } else {
8290                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8291                    }
8292                }
8293
8294                maybeThrowExceptionForMultiArchCopy(
8295                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8296
8297                if (abi64 >= 0) {
8298                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8299                }
8300
8301                if (abi32 >= 0) {
8302                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8303                    if (abi64 >= 0) {
8304                        pkg.applicationInfo.secondaryCpuAbi = abi;
8305                    } else {
8306                        pkg.applicationInfo.primaryCpuAbi = abi;
8307                    }
8308                }
8309                if (cpuAbiOverride != null &&
8310                        cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) {
8311                    pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8312                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8313                }
8314            } else {
8315                String[] abiList = (cpuAbiOverride != null) ?
8316                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8317
8318                // Enable gross and lame hacks for apps that are built with old
8319                // SDK tools. We must scan their APKs for renderscript bitcode and
8320                // not launch them if it's present. Don't bother checking on devices
8321                // that don't have 64 bit support.
8322                boolean needsRenderScriptOverride = false;
8323                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8324                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8325                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8326                    needsRenderScriptOverride = true;
8327                }
8328
8329                final int copyRet;
8330                if (extractLibs) {
8331                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8332                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8333                } else {
8334                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8335                }
8336
8337                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8338                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8339                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8340                }
8341
8342                if (copyRet >= 0) {
8343                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8344                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8345                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8346                } else if (needsRenderScriptOverride) {
8347                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8348                }
8349            }
8350        } catch (IOException ioe) {
8351            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8352        } finally {
8353            IoUtils.closeQuietly(handle);
8354        }
8355
8356        // Now that we've calculated the ABIs and determined if it's an internal app,
8357        // we will go ahead and populate the nativeLibraryPath.
8358        setNativeLibraryPaths(pkg);
8359    }
8360
8361    /**
8362     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8363     * i.e, so that all packages can be run inside a single process if required.
8364     *
8365     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8366     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8367     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8368     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8369     * updating a package that belongs to a shared user.
8370     *
8371     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8372     * adds unnecessary complexity.
8373     */
8374    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8375            PackageParser.Package scannedPackage, boolean bootComplete) {
8376        String requiredInstructionSet = null;
8377        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8378            requiredInstructionSet = VMRuntime.getInstructionSet(
8379                     scannedPackage.applicationInfo.primaryCpuAbi);
8380        }
8381
8382        PackageSetting requirer = null;
8383        for (PackageSetting ps : packagesForUser) {
8384            // If packagesForUser contains scannedPackage, we skip it. This will happen
8385            // when scannedPackage is an update of an existing package. Without this check,
8386            // we will never be able to change the ABI of any package belonging to a shared
8387            // user, even if it's compatible with other packages.
8388            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8389                if (ps.primaryCpuAbiString == null) {
8390                    continue;
8391                }
8392
8393                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8394                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8395                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8396                    // this but there's not much we can do.
8397                    String errorMessage = "Instruction set mismatch, "
8398                            + ((requirer == null) ? "[caller]" : requirer)
8399                            + " requires " + requiredInstructionSet + " whereas " + ps
8400                            + " requires " + instructionSet;
8401                    Slog.w(TAG, errorMessage);
8402                }
8403
8404                if (requiredInstructionSet == null) {
8405                    requiredInstructionSet = instructionSet;
8406                    requirer = ps;
8407                }
8408            }
8409        }
8410
8411        if (requiredInstructionSet != null) {
8412            String adjustedAbi;
8413            if (requirer != null) {
8414                // requirer != null implies that either scannedPackage was null or that scannedPackage
8415                // did not require an ABI, in which case we have to adjust scannedPackage to match
8416                // the ABI of the set (which is the same as requirer's ABI)
8417                adjustedAbi = requirer.primaryCpuAbiString;
8418                if (scannedPackage != null) {
8419                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8420                }
8421            } else {
8422                // requirer == null implies that we're updating all ABIs in the set to
8423                // match scannedPackage.
8424                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8425            }
8426
8427            for (PackageSetting ps : packagesForUser) {
8428                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8429                    if (ps.primaryCpuAbiString != null) {
8430                        continue;
8431                    }
8432
8433                    ps.primaryCpuAbiString = adjustedAbi;
8434                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8435                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8436                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8437                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8438                                + " (requirer="
8439                                + (requirer == null ? "null" : requirer.pkg.packageName)
8440                                + ", scannedPackage="
8441                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8442                                + ")");
8443                        try {
8444                            mInstaller.rmdex(ps.codePathString,
8445                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8446                        } catch (InstallerException ignored) {
8447                        }
8448                    }
8449                }
8450            }
8451        }
8452    }
8453
8454    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8455        synchronized (mPackages) {
8456            mResolverReplaced = true;
8457            // Set up information for custom user intent resolution activity.
8458            mResolveActivity.applicationInfo = pkg.applicationInfo;
8459            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8460            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8461            mResolveActivity.processName = pkg.applicationInfo.packageName;
8462            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8463            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8464                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8465            mResolveActivity.theme = 0;
8466            mResolveActivity.exported = true;
8467            mResolveActivity.enabled = true;
8468            mResolveInfo.activityInfo = mResolveActivity;
8469            mResolveInfo.priority = 0;
8470            mResolveInfo.preferredOrder = 0;
8471            mResolveInfo.match = 0;
8472            mResolveComponentName = mCustomResolverComponentName;
8473            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8474                    mResolveComponentName);
8475        }
8476    }
8477
8478    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8479        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8480
8481        // Set up information for ephemeral installer activity
8482        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8483        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8484        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8485        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8486        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8487        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8488                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8489        mEphemeralInstallerActivity.theme = 0;
8490        mEphemeralInstallerActivity.exported = true;
8491        mEphemeralInstallerActivity.enabled = true;
8492        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8493        mEphemeralInstallerInfo.priority = 0;
8494        mEphemeralInstallerInfo.preferredOrder = 0;
8495        mEphemeralInstallerInfo.match = 0;
8496
8497        if (DEBUG_EPHEMERAL) {
8498            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8499        }
8500    }
8501
8502    private static String calculateBundledApkRoot(final String codePathString) {
8503        final File codePath = new File(codePathString);
8504        final File codeRoot;
8505        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8506            codeRoot = Environment.getRootDirectory();
8507        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8508            codeRoot = Environment.getOemDirectory();
8509        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8510            codeRoot = Environment.getVendorDirectory();
8511        } else {
8512            // Unrecognized code path; take its top real segment as the apk root:
8513            // e.g. /something/app/blah.apk => /something
8514            try {
8515                File f = codePath.getCanonicalFile();
8516                File parent = f.getParentFile();    // non-null because codePath is a file
8517                File tmp;
8518                while ((tmp = parent.getParentFile()) != null) {
8519                    f = parent;
8520                    parent = tmp;
8521                }
8522                codeRoot = f;
8523                Slog.w(TAG, "Unrecognized code path "
8524                        + codePath + " - using " + codeRoot);
8525            } catch (IOException e) {
8526                // Can't canonicalize the code path -- shenanigans?
8527                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8528                return Environment.getRootDirectory().getPath();
8529            }
8530        }
8531        return codeRoot.getPath();
8532    }
8533
8534    /**
8535     * Derive and set the location of native libraries for the given package,
8536     * which varies depending on where and how the package was installed.
8537     */
8538    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8539        final ApplicationInfo info = pkg.applicationInfo;
8540        final String codePath = pkg.codePath;
8541        final File codeFile = new File(codePath);
8542        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8543        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8544
8545        info.nativeLibraryRootDir = null;
8546        info.nativeLibraryRootRequiresIsa = false;
8547        info.nativeLibraryDir = null;
8548        info.secondaryNativeLibraryDir = null;
8549
8550        if (isApkFile(codeFile)) {
8551            // Monolithic install
8552            if (bundledApp) {
8553                // If "/system/lib64/apkname" exists, assume that is the per-package
8554                // native library directory to use; otherwise use "/system/lib/apkname".
8555                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8556                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8557                        getPrimaryInstructionSet(info));
8558
8559                // This is a bundled system app so choose the path based on the ABI.
8560                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8561                // is just the default path.
8562                final String apkName = deriveCodePathName(codePath);
8563                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8564                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8565                        apkName).getAbsolutePath();
8566
8567                if (info.secondaryCpuAbi != null) {
8568                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8569                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8570                            secondaryLibDir, apkName).getAbsolutePath();
8571                }
8572            } else if (asecApp) {
8573                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8574                        .getAbsolutePath();
8575            } else {
8576                final String apkName = deriveCodePathName(codePath);
8577                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8578                        .getAbsolutePath();
8579            }
8580
8581            info.nativeLibraryRootRequiresIsa = false;
8582            info.nativeLibraryDir = info.nativeLibraryRootDir;
8583        } else {
8584            // Cluster install
8585            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8586            info.nativeLibraryRootRequiresIsa = true;
8587
8588            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8589                    getPrimaryInstructionSet(info)).getAbsolutePath();
8590
8591            if (info.secondaryCpuAbi != null) {
8592                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8593                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8594            }
8595        }
8596    }
8597
8598    /**
8599     * Calculate the abis and roots for a bundled app. These can uniquely
8600     * be determined from the contents of the system partition, i.e whether
8601     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8602     * of this information, and instead assume that the system was built
8603     * sensibly.
8604     */
8605    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8606                                           PackageSetting pkgSetting) {
8607        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8608
8609        // If "/system/lib64/apkname" exists, assume that is the per-package
8610        // native library directory to use; otherwise use "/system/lib/apkname".
8611        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8612        setBundledAppAbi(pkg, apkRoot, apkName);
8613        // pkgSetting might be null during rescan following uninstall of updates
8614        // to a bundled app, so accommodate that possibility.  The settings in
8615        // that case will be established later from the parsed package.
8616        //
8617        // If the settings aren't null, sync them up with what we've just derived.
8618        // note that apkRoot isn't stored in the package settings.
8619        if (pkgSetting != null) {
8620            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8621            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8622        }
8623    }
8624
8625    /**
8626     * Deduces the ABI of a bundled app and sets the relevant fields on the
8627     * parsed pkg object.
8628     *
8629     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8630     *        under which system libraries are installed.
8631     * @param apkName the name of the installed package.
8632     */
8633    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8634        final File codeFile = new File(pkg.codePath);
8635
8636        final boolean has64BitLibs;
8637        final boolean has32BitLibs;
8638        if (isApkFile(codeFile)) {
8639            // Monolithic install
8640            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8641            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8642        } else {
8643            // Cluster install
8644            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8645            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8646                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8647                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8648                has64BitLibs = (new File(rootDir, isa)).exists();
8649            } else {
8650                has64BitLibs = false;
8651            }
8652            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8653                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8654                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8655                has32BitLibs = (new File(rootDir, isa)).exists();
8656            } else {
8657                has32BitLibs = false;
8658            }
8659        }
8660
8661        if (has64BitLibs && !has32BitLibs) {
8662            // The package has 64 bit libs, but not 32 bit libs. Its primary
8663            // ABI should be 64 bit. We can safely assume here that the bundled
8664            // native libraries correspond to the most preferred ABI in the list.
8665
8666            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8667            pkg.applicationInfo.secondaryCpuAbi = null;
8668        } else if (has32BitLibs && !has64BitLibs) {
8669            // The package has 32 bit libs but not 64 bit libs. Its primary
8670            // ABI should be 32 bit.
8671
8672            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8673            pkg.applicationInfo.secondaryCpuAbi = null;
8674        } else if (has32BitLibs && has64BitLibs) {
8675            // The application has both 64 and 32 bit bundled libraries. We check
8676            // here that the app declares multiArch support, and warn if it doesn't.
8677            //
8678            // We will be lenient here and record both ABIs. The primary will be the
8679            // ABI that's higher on the list, i.e, a device that's configured to prefer
8680            // 64 bit apps will see a 64 bit primary ABI,
8681
8682            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8683                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8684            }
8685
8686            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8687                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8688                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8689            } else {
8690                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8691                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8692            }
8693        } else {
8694            pkg.applicationInfo.primaryCpuAbi = null;
8695            pkg.applicationInfo.secondaryCpuAbi = null;
8696        }
8697    }
8698
8699    private void killPackage(PackageParser.Package pkg, String reason) {
8700        // Kill the parent package
8701        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8702        // Kill the child packages
8703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8704        for (int i = 0; i < childCount; i++) {
8705            PackageParser.Package childPkg = pkg.childPackages.get(i);
8706            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8707        }
8708    }
8709
8710    private void killApplication(String pkgName, int appId, String reason) {
8711        // Request the ActivityManager to kill the process(only for existing packages)
8712        // so that we do not end up in a confused state while the user is still using the older
8713        // version of the application while the new one gets installed.
8714        IActivityManager am = ActivityManagerNative.getDefault();
8715        if (am != null) {
8716            try {
8717                am.killApplicationWithAppId(pkgName, appId, reason);
8718            } catch (RemoteException e) {
8719            }
8720        }
8721    }
8722
8723    private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) {
8724        // Remove the parent package setting
8725        PackageSetting ps = (PackageSetting) pkg.mExtras;
8726        if (ps != null) {
8727            removePackageSettingLI(ps, chatty);
8728        }
8729        // Remove the child package setting
8730        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8731        for (int i = 0; i < childCount; i++) {
8732            PackageParser.Package childPkg = pkg.childPackages.get(i);
8733            ps = (PackageSetting) childPkg.mExtras;
8734            if (ps != null) {
8735                removePackageSettingLI(ps, chatty);
8736            }
8737        }
8738    }
8739
8740    void removePackageSettingLI(PackageSetting ps, boolean chatty) {
8741        if (DEBUG_INSTALL) {
8742            if (chatty)
8743                Log.d(TAG, "Removing package " + ps.name);
8744        }
8745
8746        // writer
8747        synchronized (mPackages) {
8748            mPackages.remove(ps.name);
8749            final PackageParser.Package pkg = ps.pkg;
8750            if (pkg != null) {
8751                cleanPackageDataStructuresLILPw(pkg, chatty);
8752            }
8753        }
8754    }
8755
8756    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8757        if (DEBUG_INSTALL) {
8758            if (chatty)
8759                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8760        }
8761
8762        // writer
8763        synchronized (mPackages) {
8764            // Remove the parent package
8765            mPackages.remove(pkg.applicationInfo.packageName);
8766            cleanPackageDataStructuresLILPw(pkg, chatty);
8767
8768            // Remove the child packages
8769            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8770            for (int i = 0; i < childCount; i++) {
8771                PackageParser.Package childPkg = pkg.childPackages.get(i);
8772                mPackages.remove(childPkg.applicationInfo.packageName);
8773                cleanPackageDataStructuresLILPw(childPkg, chatty);
8774            }
8775        }
8776    }
8777
8778    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8779        int N = pkg.providers.size();
8780        StringBuilder r = null;
8781        int i;
8782        for (i=0; i<N; i++) {
8783            PackageParser.Provider p = pkg.providers.get(i);
8784            mProviders.removeProvider(p);
8785            if (p.info.authority == null) {
8786
8787                /* There was another ContentProvider with this authority when
8788                 * this app was installed so this authority is null,
8789                 * Ignore it as we don't have to unregister the provider.
8790                 */
8791                continue;
8792            }
8793            String names[] = p.info.authority.split(";");
8794            for (int j = 0; j < names.length; j++) {
8795                if (mProvidersByAuthority.get(names[j]) == p) {
8796                    mProvidersByAuthority.remove(names[j]);
8797                    if (DEBUG_REMOVE) {
8798                        if (chatty)
8799                            Log.d(TAG, "Unregistered content provider: " + names[j]
8800                                    + ", className = " + p.info.name + ", isSyncable = "
8801                                    + p.info.isSyncable);
8802                    }
8803                }
8804            }
8805            if (DEBUG_REMOVE && chatty) {
8806                if (r == null) {
8807                    r = new StringBuilder(256);
8808                } else {
8809                    r.append(' ');
8810                }
8811                r.append(p.info.name);
8812            }
8813        }
8814        if (r != null) {
8815            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8816        }
8817
8818        N = pkg.services.size();
8819        r = null;
8820        for (i=0; i<N; i++) {
8821            PackageParser.Service s = pkg.services.get(i);
8822            mServices.removeService(s);
8823            if (chatty) {
8824                if (r == null) {
8825                    r = new StringBuilder(256);
8826                } else {
8827                    r.append(' ');
8828                }
8829                r.append(s.info.name);
8830            }
8831        }
8832        if (r != null) {
8833            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8834        }
8835
8836        N = pkg.receivers.size();
8837        r = null;
8838        for (i=0; i<N; i++) {
8839            PackageParser.Activity a = pkg.receivers.get(i);
8840            mReceivers.removeActivity(a, "receiver");
8841            if (DEBUG_REMOVE && chatty) {
8842                if (r == null) {
8843                    r = new StringBuilder(256);
8844                } else {
8845                    r.append(' ');
8846                }
8847                r.append(a.info.name);
8848            }
8849        }
8850        if (r != null) {
8851            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8852        }
8853
8854        N = pkg.activities.size();
8855        r = null;
8856        for (i=0; i<N; i++) {
8857            PackageParser.Activity a = pkg.activities.get(i);
8858            mActivities.removeActivity(a, "activity");
8859            if (DEBUG_REMOVE && chatty) {
8860                if (r == null) {
8861                    r = new StringBuilder(256);
8862                } else {
8863                    r.append(' ');
8864                }
8865                r.append(a.info.name);
8866            }
8867        }
8868        if (r != null) {
8869            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8870        }
8871
8872        N = pkg.permissions.size();
8873        r = null;
8874        for (i=0; i<N; i++) {
8875            PackageParser.Permission p = pkg.permissions.get(i);
8876            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8877            if (bp == null) {
8878                bp = mSettings.mPermissionTrees.get(p.info.name);
8879            }
8880            if (bp != null && bp.perm == p) {
8881                bp.perm = null;
8882                if (DEBUG_REMOVE && chatty) {
8883                    if (r == null) {
8884                        r = new StringBuilder(256);
8885                    } else {
8886                        r.append(' ');
8887                    }
8888                    r.append(p.info.name);
8889                }
8890            }
8891            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8892                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8893                if (appOpPkgs != null) {
8894                    appOpPkgs.remove(pkg.packageName);
8895                }
8896            }
8897        }
8898        if (r != null) {
8899            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8900        }
8901
8902        N = pkg.requestedPermissions.size();
8903        r = null;
8904        for (i=0; i<N; i++) {
8905            String perm = pkg.requestedPermissions.get(i);
8906            BasePermission bp = mSettings.mPermissions.get(perm);
8907            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8908                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8909                if (appOpPkgs != null) {
8910                    appOpPkgs.remove(pkg.packageName);
8911                    if (appOpPkgs.isEmpty()) {
8912                        mAppOpPermissionPackages.remove(perm);
8913                    }
8914                }
8915            }
8916        }
8917        if (r != null) {
8918            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8919        }
8920
8921        N = pkg.instrumentation.size();
8922        r = null;
8923        for (i=0; i<N; i++) {
8924            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8925            mInstrumentation.remove(a.getComponentName());
8926            if (DEBUG_REMOVE && chatty) {
8927                if (r == null) {
8928                    r = new StringBuilder(256);
8929                } else {
8930                    r.append(' ');
8931                }
8932                r.append(a.info.name);
8933            }
8934        }
8935        if (r != null) {
8936            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8937        }
8938
8939        r = null;
8940        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8941            // Only system apps can hold shared libraries.
8942            if (pkg.libraryNames != null) {
8943                for (i=0; i<pkg.libraryNames.size(); i++) {
8944                    String name = pkg.libraryNames.get(i);
8945                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8946                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8947                        mSharedLibraries.remove(name);
8948                        if (DEBUG_REMOVE && chatty) {
8949                            if (r == null) {
8950                                r = new StringBuilder(256);
8951                            } else {
8952                                r.append(' ');
8953                            }
8954                            r.append(name);
8955                        }
8956                    }
8957                }
8958            }
8959        }
8960        if (r != null) {
8961            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8962        }
8963    }
8964
8965    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8966        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8967            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8968                return true;
8969            }
8970        }
8971        return false;
8972    }
8973
8974    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8975    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8976    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8977
8978    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
8979        // Update the parent permissions
8980        updatePermissionsLPw(pkg.packageName, pkg, flags);
8981        // Update the child permissions
8982        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8983        for (int i = 0; i < childCount; i++) {
8984            PackageParser.Package childPkg = pkg.childPackages.get(i);
8985            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
8986        }
8987    }
8988
8989    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8990            int flags) {
8991        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8992        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8993    }
8994
8995    private void updatePermissionsLPw(String changingPkg,
8996            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8997        // Make sure there are no dangling permission trees.
8998        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8999        while (it.hasNext()) {
9000            final BasePermission bp = it.next();
9001            if (bp.packageSetting == null) {
9002                // We may not yet have parsed the package, so just see if
9003                // we still know about its settings.
9004                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9005            }
9006            if (bp.packageSetting == null) {
9007                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9008                        + " from package " + bp.sourcePackage);
9009                it.remove();
9010            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9011                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9012                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9013                            + " from package " + bp.sourcePackage);
9014                    flags |= UPDATE_PERMISSIONS_ALL;
9015                    it.remove();
9016                }
9017            }
9018        }
9019
9020        // Make sure all dynamic permissions have been assigned to a package,
9021        // and make sure there are no dangling permissions.
9022        it = mSettings.mPermissions.values().iterator();
9023        while (it.hasNext()) {
9024            final BasePermission bp = it.next();
9025            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9026                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9027                        + bp.name + " pkg=" + bp.sourcePackage
9028                        + " info=" + bp.pendingInfo);
9029                if (bp.packageSetting == null && bp.pendingInfo != null) {
9030                    final BasePermission tree = findPermissionTreeLP(bp.name);
9031                    if (tree != null && tree.perm != null) {
9032                        bp.packageSetting = tree.packageSetting;
9033                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9034                                new PermissionInfo(bp.pendingInfo));
9035                        bp.perm.info.packageName = tree.perm.info.packageName;
9036                        bp.perm.info.name = bp.name;
9037                        bp.uid = tree.uid;
9038                    }
9039                }
9040            }
9041            if (bp.packageSetting == null) {
9042                // We may not yet have parsed the package, so just see if
9043                // we still know about its settings.
9044                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9045            }
9046            if (bp.packageSetting == null) {
9047                Slog.w(TAG, "Removing dangling permission: " + bp.name
9048                        + " from package " + bp.sourcePackage);
9049                it.remove();
9050            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9051                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9052                    Slog.i(TAG, "Removing old permission: " + bp.name
9053                            + " from package " + bp.sourcePackage);
9054                    flags |= UPDATE_PERMISSIONS_ALL;
9055                    it.remove();
9056                }
9057            }
9058        }
9059
9060        // Now update the permissions for all packages, in particular
9061        // replace the granted permissions of the system packages.
9062        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9063            for (PackageParser.Package pkg : mPackages.values()) {
9064                if (pkg != pkgInfo) {
9065                    // Only replace for packages on requested volume
9066                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9067                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9068                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9069                    grantPermissionsLPw(pkg, replace, changingPkg);
9070                }
9071            }
9072        }
9073
9074        if (pkgInfo != null) {
9075            // Only replace for packages on requested volume
9076            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9077            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9078                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9079            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9080        }
9081    }
9082
9083    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9084            String packageOfInterest) {
9085        // IMPORTANT: There are two types of permissions: install and runtime.
9086        // Install time permissions are granted when the app is installed to
9087        // all device users and users added in the future. Runtime permissions
9088        // are granted at runtime explicitly to specific users. Normal and signature
9089        // protected permissions are install time permissions. Dangerous permissions
9090        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9091        // otherwise they are runtime permissions. This function does not manage
9092        // runtime permissions except for the case an app targeting Lollipop MR1
9093        // being upgraded to target a newer SDK, in which case dangerous permissions
9094        // are transformed from install time to runtime ones.
9095
9096        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9097        if (ps == null) {
9098            return;
9099        }
9100
9101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9102
9103        PermissionsState permissionsState = ps.getPermissionsState();
9104        PermissionsState origPermissions = permissionsState;
9105
9106        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9107
9108        boolean runtimePermissionsRevoked = false;
9109        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9110
9111        boolean changedInstallPermission = false;
9112
9113        if (replace) {
9114            ps.installPermissionsFixed = false;
9115            if (!ps.isSharedUser()) {
9116                origPermissions = new PermissionsState(permissionsState);
9117                permissionsState.reset();
9118            } else {
9119                // We need to know only about runtime permission changes since the
9120                // calling code always writes the install permissions state but
9121                // the runtime ones are written only if changed. The only cases of
9122                // changed runtime permissions here are promotion of an install to
9123                // runtime and revocation of a runtime from a shared user.
9124                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9125                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9126                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9127                    runtimePermissionsRevoked = true;
9128                }
9129            }
9130        }
9131
9132        permissionsState.setGlobalGids(mGlobalGids);
9133
9134        final int N = pkg.requestedPermissions.size();
9135        for (int i=0; i<N; i++) {
9136            final String name = pkg.requestedPermissions.get(i);
9137            final BasePermission bp = mSettings.mPermissions.get(name);
9138
9139            if (DEBUG_INSTALL) {
9140                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9141            }
9142
9143            if (bp == null || bp.packageSetting == null) {
9144                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9145                    Slog.w(TAG, "Unknown permission " + name
9146                            + " in package " + pkg.packageName);
9147                }
9148                continue;
9149            }
9150
9151            final String perm = bp.name;
9152            boolean allowedSig = false;
9153            int grant = GRANT_DENIED;
9154
9155            // Keep track of app op permissions.
9156            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9157                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9158                if (pkgs == null) {
9159                    pkgs = new ArraySet<>();
9160                    mAppOpPermissionPackages.put(bp.name, pkgs);
9161                }
9162                pkgs.add(pkg.packageName);
9163            }
9164
9165            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9166            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9167                    >= Build.VERSION_CODES.M;
9168            switch (level) {
9169                case PermissionInfo.PROTECTION_NORMAL: {
9170                    // For all apps normal permissions are install time ones.
9171                    grant = GRANT_INSTALL;
9172                } break;
9173
9174                case PermissionInfo.PROTECTION_DANGEROUS: {
9175                    // If a permission review is required for legacy apps we represent
9176                    // their permissions as always granted runtime ones since we need
9177                    // to keep the review required permission flag per user while an
9178                    // install permission's state is shared across all users.
9179                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9180                        // For legacy apps dangerous permissions are install time ones.
9181                        grant = GRANT_INSTALL;
9182                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9183                        // For legacy apps that became modern, install becomes runtime.
9184                        grant = GRANT_UPGRADE;
9185                    } else if (mPromoteSystemApps
9186                            && isSystemApp(ps)
9187                            && mExistingSystemPackages.contains(ps.name)) {
9188                        // For legacy system apps, install becomes runtime.
9189                        // We cannot check hasInstallPermission() for system apps since those
9190                        // permissions were granted implicitly and not persisted pre-M.
9191                        grant = GRANT_UPGRADE;
9192                    } else {
9193                        // For modern apps keep runtime permissions unchanged.
9194                        grant = GRANT_RUNTIME;
9195                    }
9196                } break;
9197
9198                case PermissionInfo.PROTECTION_SIGNATURE: {
9199                    // For all apps signature permissions are install time ones.
9200                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9201                    if (allowedSig) {
9202                        grant = GRANT_INSTALL;
9203                    }
9204                } break;
9205            }
9206
9207            if (DEBUG_INSTALL) {
9208                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9209            }
9210
9211            if (grant != GRANT_DENIED) {
9212                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9213                    // If this is an existing, non-system package, then
9214                    // we can't add any new permissions to it.
9215                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9216                        // Except...  if this is a permission that was added
9217                        // to the platform (note: need to only do this when
9218                        // updating the platform).
9219                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9220                            grant = GRANT_DENIED;
9221                        }
9222                    }
9223                }
9224
9225                switch (grant) {
9226                    case GRANT_INSTALL: {
9227                        // Revoke this as runtime permission to handle the case of
9228                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9229                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9230                            if (origPermissions.getRuntimePermissionState(
9231                                    bp.name, userId) != null) {
9232                                // Revoke the runtime permission and clear the flags.
9233                                origPermissions.revokeRuntimePermission(bp, userId);
9234                                origPermissions.updatePermissionFlags(bp, userId,
9235                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9236                                // If we revoked a permission permission, we have to write.
9237                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9238                                        changedRuntimePermissionUserIds, userId);
9239                            }
9240                        }
9241                        // Grant an install permission.
9242                        if (permissionsState.grantInstallPermission(bp) !=
9243                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9244                            changedInstallPermission = true;
9245                        }
9246                    } break;
9247
9248                    case GRANT_RUNTIME: {
9249                        // Grant previously granted runtime permissions.
9250                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9251                            PermissionState permissionState = origPermissions
9252                                    .getRuntimePermissionState(bp.name, userId);
9253                            int flags = permissionState != null
9254                                    ? permissionState.getFlags() : 0;
9255                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9256                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9257                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9258                                    // If we cannot put the permission as it was, we have to write.
9259                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9260                                            changedRuntimePermissionUserIds, userId);
9261                                }
9262                                // If the app supports runtime permissions no need for a review.
9263                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9264                                        && appSupportsRuntimePermissions
9265                                        && (flags & PackageManager
9266                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9267                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9268                                    // Since we changed the flags, we have to write.
9269                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9270                                            changedRuntimePermissionUserIds, userId);
9271                                }
9272                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9273                                    && !appSupportsRuntimePermissions) {
9274                                // For legacy apps that need a permission review, every new
9275                                // runtime permission is granted but it is pending a review.
9276                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9277                                    permissionsState.grantRuntimePermission(bp, userId);
9278                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9279                                    // We changed the permission and flags, hence have to write.
9280                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9281                                            changedRuntimePermissionUserIds, userId);
9282                                }
9283                            }
9284                            // Propagate the permission flags.
9285                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9286                        }
9287                    } break;
9288
9289                    case GRANT_UPGRADE: {
9290                        // Grant runtime permissions for a previously held install permission.
9291                        PermissionState permissionState = origPermissions
9292                                .getInstallPermissionState(bp.name);
9293                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9294
9295                        if (origPermissions.revokeInstallPermission(bp)
9296                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9297                            // We will be transferring the permission flags, so clear them.
9298                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9299                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9300                            changedInstallPermission = true;
9301                        }
9302
9303                        // If the permission is not to be promoted to runtime we ignore it and
9304                        // also its other flags as they are not applicable to install permissions.
9305                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9306                            for (int userId : currentUserIds) {
9307                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9308                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9309                                    // Transfer the permission flags.
9310                                    permissionsState.updatePermissionFlags(bp, userId,
9311                                            flags, flags);
9312                                    // If we granted the permission, we have to write.
9313                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9314                                            changedRuntimePermissionUserIds, userId);
9315                                }
9316                            }
9317                        }
9318                    } break;
9319
9320                    default: {
9321                        if (packageOfInterest == null
9322                                || packageOfInterest.equals(pkg.packageName)) {
9323                            Slog.w(TAG, "Not granting permission " + perm
9324                                    + " to package " + pkg.packageName
9325                                    + " because it was previously installed without");
9326                        }
9327                    } break;
9328                }
9329            } else {
9330                if (permissionsState.revokeInstallPermission(bp) !=
9331                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9332                    // Also drop the permission flags.
9333                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9334                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9335                    changedInstallPermission = true;
9336                    Slog.i(TAG, "Un-granting permission " + perm
9337                            + " from package " + pkg.packageName
9338                            + " (protectionLevel=" + bp.protectionLevel
9339                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9340                            + ")");
9341                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9342                    // Don't print warning for app op permissions, since it is fine for them
9343                    // not to be granted, there is a UI for the user to decide.
9344                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9345                        Slog.w(TAG, "Not granting permission " + perm
9346                                + " to package " + pkg.packageName
9347                                + " (protectionLevel=" + bp.protectionLevel
9348                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9349                                + ")");
9350                    }
9351                }
9352            }
9353        }
9354
9355        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9356                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9357            // This is the first that we have heard about this package, so the
9358            // permissions we have now selected are fixed until explicitly
9359            // changed.
9360            ps.installPermissionsFixed = true;
9361        }
9362
9363        // Persist the runtime permissions state for users with changes. If permissions
9364        // were revoked because no app in the shared user declares them we have to
9365        // write synchronously to avoid losing runtime permissions state.
9366        for (int userId : changedRuntimePermissionUserIds) {
9367            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9368        }
9369
9370        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9371    }
9372
9373    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9374        boolean allowed = false;
9375        final int NP = PackageParser.NEW_PERMISSIONS.length;
9376        for (int ip=0; ip<NP; ip++) {
9377            final PackageParser.NewPermissionInfo npi
9378                    = PackageParser.NEW_PERMISSIONS[ip];
9379            if (npi.name.equals(perm)
9380                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9381                allowed = true;
9382                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9383                        + pkg.packageName);
9384                break;
9385            }
9386        }
9387        return allowed;
9388    }
9389
9390    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9391            BasePermission bp, PermissionsState origPermissions) {
9392        boolean allowed;
9393        allowed = (compareSignatures(
9394                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9395                        == PackageManager.SIGNATURE_MATCH)
9396                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9397                        == PackageManager.SIGNATURE_MATCH);
9398        if (!allowed && (bp.protectionLevel
9399                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9400            if (isSystemApp(pkg)) {
9401                // For updated system applications, a system permission
9402                // is granted only if it had been defined by the original application.
9403                if (pkg.isUpdatedSystemApp()) {
9404                    final PackageSetting sysPs = mSettings
9405                            .getDisabledSystemPkgLPr(pkg.packageName);
9406                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9407                        // If the original was granted this permission, we take
9408                        // that grant decision as read and propagate it to the
9409                        // update.
9410                        if (sysPs.isPrivileged()) {
9411                            allowed = true;
9412                        }
9413                    } else {
9414                        // The system apk may have been updated with an older
9415                        // version of the one on the data partition, but which
9416                        // granted a new system permission that it didn't have
9417                        // before.  In this case we do want to allow the app to
9418                        // now get the new permission if the ancestral apk is
9419                        // privileged to get it.
9420                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9421                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9422                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9423                                    allowed = true;
9424                                    break;
9425                                }
9426                            }
9427                        }
9428                        // Also if a privileged parent package on the system image or any of
9429                        // its children requested a privileged permission, the updated child
9430                        // packages can also get the permission.
9431                        if (pkg.parentPackage != null) {
9432                            final PackageSetting disabledSysParentPs = mSettings
9433                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9434                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9435                                    && disabledSysParentPs.isPrivileged()) {
9436                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9437                                    allowed = true;
9438                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9439                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9440                                    for (int i = 0; i < count; i++) {
9441                                        PackageParser.Package disabledSysChildPkg =
9442                                                disabledSysParentPs.pkg.childPackages.get(i);
9443                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9444                                                perm)) {
9445                                            allowed = true;
9446                                            break;
9447                                        }
9448                                    }
9449                                }
9450                            }
9451                        }
9452                    }
9453                } else {
9454                    allowed = isPrivilegedApp(pkg);
9455                }
9456            }
9457        }
9458        if (!allowed) {
9459            if (!allowed && (bp.protectionLevel
9460                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9461                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9462                // If this was a previously normal/dangerous permission that got moved
9463                // to a system permission as part of the runtime permission redesign, then
9464                // we still want to blindly grant it to old apps.
9465                allowed = true;
9466            }
9467            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9468                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9469                // If this permission is to be granted to the system installer and
9470                // this app is an installer, then it gets the permission.
9471                allowed = true;
9472            }
9473            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9474                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9475                // If this permission is to be granted to the system verifier and
9476                // this app is a verifier, then it gets the permission.
9477                allowed = true;
9478            }
9479            if (!allowed && (bp.protectionLevel
9480                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9481                    && isSystemApp(pkg)) {
9482                // Any pre-installed system app is allowed to get this permission.
9483                allowed = true;
9484            }
9485            if (!allowed && (bp.protectionLevel
9486                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9487                // For development permissions, a development permission
9488                // is granted only if it was already granted.
9489                allowed = origPermissions.hasInstallPermission(perm);
9490            }
9491        }
9492        return allowed;
9493    }
9494
9495    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9496        final int permCount = pkg.requestedPermissions.size();
9497        for (int j = 0; j < permCount; j++) {
9498            String requestedPermission = pkg.requestedPermissions.get(j);
9499            if (permission.equals(requestedPermission)) {
9500                return true;
9501            }
9502        }
9503        return false;
9504    }
9505
9506    final class ActivityIntentResolver
9507            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9508        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9509                boolean defaultOnly, int userId) {
9510            if (!sUserManager.exists(userId)) return null;
9511            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9512            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9513        }
9514
9515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9516                int userId) {
9517            if (!sUserManager.exists(userId)) return null;
9518            mFlags = flags;
9519            return super.queryIntent(intent, resolvedType,
9520                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9521        }
9522
9523        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9524                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9525            if (!sUserManager.exists(userId)) return null;
9526            if (packageActivities == null) {
9527                return null;
9528            }
9529            mFlags = flags;
9530            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9531            final int N = packageActivities.size();
9532            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9533                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9534
9535            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9536            for (int i = 0; i < N; ++i) {
9537                intentFilters = packageActivities.get(i).intents;
9538                if (intentFilters != null && intentFilters.size() > 0) {
9539                    PackageParser.ActivityIntentInfo[] array =
9540                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9541                    intentFilters.toArray(array);
9542                    listCut.add(array);
9543                }
9544            }
9545            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9546        }
9547
9548        public final void addActivity(PackageParser.Activity a, String type) {
9549            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9550            mActivities.put(a.getComponentName(), a);
9551            if (DEBUG_SHOW_INFO)
9552                Log.v(
9553                TAG, "  " + type + " " +
9554                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9555            if (DEBUG_SHOW_INFO)
9556                Log.v(TAG, "    Class=" + a.info.name);
9557            final int NI = a.intents.size();
9558            for (int j=0; j<NI; j++) {
9559                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9560                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9561                    intent.setPriority(0);
9562                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9563                            + a.className + " with priority > 0, forcing to 0");
9564                }
9565                if (DEBUG_SHOW_INFO) {
9566                    Log.v(TAG, "    IntentFilter:");
9567                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9568                }
9569                if (!intent.debugCheck()) {
9570                    Log.w(TAG, "==> For Activity " + a.info.name);
9571                }
9572                addFilter(intent);
9573            }
9574        }
9575
9576        public final void removeActivity(PackageParser.Activity a, String type) {
9577            mActivities.remove(a.getComponentName());
9578            if (DEBUG_SHOW_INFO) {
9579                Log.v(TAG, "  " + type + " "
9580                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9581                                : a.info.name) + ":");
9582                Log.v(TAG, "    Class=" + a.info.name);
9583            }
9584            final int NI = a.intents.size();
9585            for (int j=0; j<NI; j++) {
9586                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9587                if (DEBUG_SHOW_INFO) {
9588                    Log.v(TAG, "    IntentFilter:");
9589                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9590                }
9591                removeFilter(intent);
9592            }
9593        }
9594
9595        @Override
9596        protected boolean allowFilterResult(
9597                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9598            ActivityInfo filterAi = filter.activity.info;
9599            for (int i=dest.size()-1; i>=0; i--) {
9600                ActivityInfo destAi = dest.get(i).activityInfo;
9601                if (destAi.name == filterAi.name
9602                        && destAi.packageName == filterAi.packageName) {
9603                    return false;
9604                }
9605            }
9606            return true;
9607        }
9608
9609        @Override
9610        protected ActivityIntentInfo[] newArray(int size) {
9611            return new ActivityIntentInfo[size];
9612        }
9613
9614        @Override
9615        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9616            if (!sUserManager.exists(userId)) return true;
9617            PackageParser.Package p = filter.activity.owner;
9618            if (p != null) {
9619                PackageSetting ps = (PackageSetting)p.mExtras;
9620                if (ps != null) {
9621                    // System apps are never considered stopped for purposes of
9622                    // filtering, because there may be no way for the user to
9623                    // actually re-launch them.
9624                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9625                            && ps.getStopped(userId);
9626                }
9627            }
9628            return false;
9629        }
9630
9631        @Override
9632        protected boolean isPackageForFilter(String packageName,
9633                PackageParser.ActivityIntentInfo info) {
9634            return packageName.equals(info.activity.owner.packageName);
9635        }
9636
9637        @Override
9638        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9639                int match, int userId) {
9640            if (!sUserManager.exists(userId)) return null;
9641            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9642                return null;
9643            }
9644            final PackageParser.Activity activity = info.activity;
9645            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9646            if (ps == null) {
9647                return null;
9648            }
9649            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9650                    ps.readUserState(userId), userId);
9651            if (ai == null) {
9652                return null;
9653            }
9654            final ResolveInfo res = new ResolveInfo();
9655            res.activityInfo = ai;
9656            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9657                res.filter = info;
9658            }
9659            if (info != null) {
9660                res.handleAllWebDataURI = info.handleAllWebDataURI();
9661            }
9662            res.priority = info.getPriority();
9663            res.preferredOrder = activity.owner.mPreferredOrder;
9664            //System.out.println("Result: " + res.activityInfo.className +
9665            //                   " = " + res.priority);
9666            res.match = match;
9667            res.isDefault = info.hasDefault;
9668            res.labelRes = info.labelRes;
9669            res.nonLocalizedLabel = info.nonLocalizedLabel;
9670            if (userNeedsBadging(userId)) {
9671                res.noResourceId = true;
9672            } else {
9673                res.icon = info.icon;
9674            }
9675            res.iconResourceId = info.icon;
9676            res.system = res.activityInfo.applicationInfo.isSystemApp();
9677            return res;
9678        }
9679
9680        @Override
9681        protected void sortResults(List<ResolveInfo> results) {
9682            Collections.sort(results, mResolvePrioritySorter);
9683        }
9684
9685        @Override
9686        protected void dumpFilter(PrintWriter out, String prefix,
9687                PackageParser.ActivityIntentInfo filter) {
9688            out.print(prefix); out.print(
9689                    Integer.toHexString(System.identityHashCode(filter.activity)));
9690                    out.print(' ');
9691                    filter.activity.printComponentShortName(out);
9692                    out.print(" filter ");
9693                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9694        }
9695
9696        @Override
9697        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9698            return filter.activity;
9699        }
9700
9701        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9702            PackageParser.Activity activity = (PackageParser.Activity)label;
9703            out.print(prefix); out.print(
9704                    Integer.toHexString(System.identityHashCode(activity)));
9705                    out.print(' ');
9706                    activity.printComponentShortName(out);
9707            if (count > 1) {
9708                out.print(" ("); out.print(count); out.print(" filters)");
9709            }
9710            out.println();
9711        }
9712
9713//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9714//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9715//            final List<ResolveInfo> retList = Lists.newArrayList();
9716//            while (i.hasNext()) {
9717//                final ResolveInfo resolveInfo = i.next();
9718//                if (isEnabledLP(resolveInfo.activityInfo)) {
9719//                    retList.add(resolveInfo);
9720//                }
9721//            }
9722//            return retList;
9723//        }
9724
9725        // Keys are String (activity class name), values are Activity.
9726        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9727                = new ArrayMap<ComponentName, PackageParser.Activity>();
9728        private int mFlags;
9729    }
9730
9731    private final class ServiceIntentResolver
9732            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9733        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9734                boolean defaultOnly, int userId) {
9735            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9736            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9737        }
9738
9739        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9740                int userId) {
9741            if (!sUserManager.exists(userId)) return null;
9742            mFlags = flags;
9743            return super.queryIntent(intent, resolvedType,
9744                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9745        }
9746
9747        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9748                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9749            if (!sUserManager.exists(userId)) return null;
9750            if (packageServices == null) {
9751                return null;
9752            }
9753            mFlags = flags;
9754            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9755            final int N = packageServices.size();
9756            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9757                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9758
9759            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9760            for (int i = 0; i < N; ++i) {
9761                intentFilters = packageServices.get(i).intents;
9762                if (intentFilters != null && intentFilters.size() > 0) {
9763                    PackageParser.ServiceIntentInfo[] array =
9764                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9765                    intentFilters.toArray(array);
9766                    listCut.add(array);
9767                }
9768            }
9769            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9770        }
9771
9772        public final void addService(PackageParser.Service s) {
9773            mServices.put(s.getComponentName(), s);
9774            if (DEBUG_SHOW_INFO) {
9775                Log.v(TAG, "  "
9776                        + (s.info.nonLocalizedLabel != null
9777                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9778                Log.v(TAG, "    Class=" + s.info.name);
9779            }
9780            final int NI = s.intents.size();
9781            int j;
9782            for (j=0; j<NI; j++) {
9783                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9784                if (DEBUG_SHOW_INFO) {
9785                    Log.v(TAG, "    IntentFilter:");
9786                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9787                }
9788                if (!intent.debugCheck()) {
9789                    Log.w(TAG, "==> For Service " + s.info.name);
9790                }
9791                addFilter(intent);
9792            }
9793        }
9794
9795        public final void removeService(PackageParser.Service s) {
9796            mServices.remove(s.getComponentName());
9797            if (DEBUG_SHOW_INFO) {
9798                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9799                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9800                Log.v(TAG, "    Class=" + s.info.name);
9801            }
9802            final int NI = s.intents.size();
9803            int j;
9804            for (j=0; j<NI; j++) {
9805                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9806                if (DEBUG_SHOW_INFO) {
9807                    Log.v(TAG, "    IntentFilter:");
9808                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9809                }
9810                removeFilter(intent);
9811            }
9812        }
9813
9814        @Override
9815        protected boolean allowFilterResult(
9816                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9817            ServiceInfo filterSi = filter.service.info;
9818            for (int i=dest.size()-1; i>=0; i--) {
9819                ServiceInfo destAi = dest.get(i).serviceInfo;
9820                if (destAi.name == filterSi.name
9821                        && destAi.packageName == filterSi.packageName) {
9822                    return false;
9823                }
9824            }
9825            return true;
9826        }
9827
9828        @Override
9829        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9830            return new PackageParser.ServiceIntentInfo[size];
9831        }
9832
9833        @Override
9834        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9835            if (!sUserManager.exists(userId)) return true;
9836            PackageParser.Package p = filter.service.owner;
9837            if (p != null) {
9838                PackageSetting ps = (PackageSetting)p.mExtras;
9839                if (ps != null) {
9840                    // System apps are never considered stopped for purposes of
9841                    // filtering, because there may be no way for the user to
9842                    // actually re-launch them.
9843                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9844                            && ps.getStopped(userId);
9845                }
9846            }
9847            return false;
9848        }
9849
9850        @Override
9851        protected boolean isPackageForFilter(String packageName,
9852                PackageParser.ServiceIntentInfo info) {
9853            return packageName.equals(info.service.owner.packageName);
9854        }
9855
9856        @Override
9857        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9858                int match, int userId) {
9859            if (!sUserManager.exists(userId)) return null;
9860            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9861            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9862                return null;
9863            }
9864            final PackageParser.Service service = info.service;
9865            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9866            if (ps == null) {
9867                return null;
9868            }
9869            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9870                    ps.readUserState(userId), userId);
9871            if (si == null) {
9872                return null;
9873            }
9874            final ResolveInfo res = new ResolveInfo();
9875            res.serviceInfo = si;
9876            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9877                res.filter = filter;
9878            }
9879            res.priority = info.getPriority();
9880            res.preferredOrder = service.owner.mPreferredOrder;
9881            res.match = match;
9882            res.isDefault = info.hasDefault;
9883            res.labelRes = info.labelRes;
9884            res.nonLocalizedLabel = info.nonLocalizedLabel;
9885            res.icon = info.icon;
9886            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9887            return res;
9888        }
9889
9890        @Override
9891        protected void sortResults(List<ResolveInfo> results) {
9892            Collections.sort(results, mResolvePrioritySorter);
9893        }
9894
9895        @Override
9896        protected void dumpFilter(PrintWriter out, String prefix,
9897                PackageParser.ServiceIntentInfo filter) {
9898            out.print(prefix); out.print(
9899                    Integer.toHexString(System.identityHashCode(filter.service)));
9900                    out.print(' ');
9901                    filter.service.printComponentShortName(out);
9902                    out.print(" filter ");
9903                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9904        }
9905
9906        @Override
9907        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9908            return filter.service;
9909        }
9910
9911        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9912            PackageParser.Service service = (PackageParser.Service)label;
9913            out.print(prefix); out.print(
9914                    Integer.toHexString(System.identityHashCode(service)));
9915                    out.print(' ');
9916                    service.printComponentShortName(out);
9917            if (count > 1) {
9918                out.print(" ("); out.print(count); out.print(" filters)");
9919            }
9920            out.println();
9921        }
9922
9923//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9924//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9925//            final List<ResolveInfo> retList = Lists.newArrayList();
9926//            while (i.hasNext()) {
9927//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9928//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9929//                    retList.add(resolveInfo);
9930//                }
9931//            }
9932//            return retList;
9933//        }
9934
9935        // Keys are String (activity class name), values are Activity.
9936        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9937                = new ArrayMap<ComponentName, PackageParser.Service>();
9938        private int mFlags;
9939    };
9940
9941    private final class ProviderIntentResolver
9942            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9943        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9944                boolean defaultOnly, int userId) {
9945            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9946            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9947        }
9948
9949        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9950                int userId) {
9951            if (!sUserManager.exists(userId))
9952                return null;
9953            mFlags = flags;
9954            return super.queryIntent(intent, resolvedType,
9955                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9956        }
9957
9958        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9959                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9960            if (!sUserManager.exists(userId))
9961                return null;
9962            if (packageProviders == null) {
9963                return null;
9964            }
9965            mFlags = flags;
9966            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9967            final int N = packageProviders.size();
9968            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9969                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9970
9971            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9972            for (int i = 0; i < N; ++i) {
9973                intentFilters = packageProviders.get(i).intents;
9974                if (intentFilters != null && intentFilters.size() > 0) {
9975                    PackageParser.ProviderIntentInfo[] array =
9976                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9977                    intentFilters.toArray(array);
9978                    listCut.add(array);
9979                }
9980            }
9981            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9982        }
9983
9984        public final void addProvider(PackageParser.Provider p) {
9985            if (mProviders.containsKey(p.getComponentName())) {
9986                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9987                return;
9988            }
9989
9990            mProviders.put(p.getComponentName(), p);
9991            if (DEBUG_SHOW_INFO) {
9992                Log.v(TAG, "  "
9993                        + (p.info.nonLocalizedLabel != null
9994                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9995                Log.v(TAG, "    Class=" + p.info.name);
9996            }
9997            final int NI = p.intents.size();
9998            int j;
9999            for (j = 0; j < NI; j++) {
10000                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10001                if (DEBUG_SHOW_INFO) {
10002                    Log.v(TAG, "    IntentFilter:");
10003                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10004                }
10005                if (!intent.debugCheck()) {
10006                    Log.w(TAG, "==> For Provider " + p.info.name);
10007                }
10008                addFilter(intent);
10009            }
10010        }
10011
10012        public final void removeProvider(PackageParser.Provider p) {
10013            mProviders.remove(p.getComponentName());
10014            if (DEBUG_SHOW_INFO) {
10015                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10016                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10017                Log.v(TAG, "    Class=" + p.info.name);
10018            }
10019            final int NI = p.intents.size();
10020            int j;
10021            for (j = 0; j < NI; j++) {
10022                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10023                if (DEBUG_SHOW_INFO) {
10024                    Log.v(TAG, "    IntentFilter:");
10025                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10026                }
10027                removeFilter(intent);
10028            }
10029        }
10030
10031        @Override
10032        protected boolean allowFilterResult(
10033                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10034            ProviderInfo filterPi = filter.provider.info;
10035            for (int i = dest.size() - 1; i >= 0; i--) {
10036                ProviderInfo destPi = dest.get(i).providerInfo;
10037                if (destPi.name == filterPi.name
10038                        && destPi.packageName == filterPi.packageName) {
10039                    return false;
10040                }
10041            }
10042            return true;
10043        }
10044
10045        @Override
10046        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10047            return new PackageParser.ProviderIntentInfo[size];
10048        }
10049
10050        @Override
10051        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10052            if (!sUserManager.exists(userId))
10053                return true;
10054            PackageParser.Package p = filter.provider.owner;
10055            if (p != null) {
10056                PackageSetting ps = (PackageSetting) p.mExtras;
10057                if (ps != null) {
10058                    // System apps are never considered stopped for purposes of
10059                    // filtering, because there may be no way for the user to
10060                    // actually re-launch them.
10061                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10062                            && ps.getStopped(userId);
10063                }
10064            }
10065            return false;
10066        }
10067
10068        @Override
10069        protected boolean isPackageForFilter(String packageName,
10070                PackageParser.ProviderIntentInfo info) {
10071            return packageName.equals(info.provider.owner.packageName);
10072        }
10073
10074        @Override
10075        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10076                int match, int userId) {
10077            if (!sUserManager.exists(userId))
10078                return null;
10079            final PackageParser.ProviderIntentInfo info = filter;
10080            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10081                return null;
10082            }
10083            final PackageParser.Provider provider = info.provider;
10084            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10085            if (ps == null) {
10086                return null;
10087            }
10088            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10089                    ps.readUserState(userId), userId);
10090            if (pi == null) {
10091                return null;
10092            }
10093            final ResolveInfo res = new ResolveInfo();
10094            res.providerInfo = pi;
10095            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10096                res.filter = filter;
10097            }
10098            res.priority = info.getPriority();
10099            res.preferredOrder = provider.owner.mPreferredOrder;
10100            res.match = match;
10101            res.isDefault = info.hasDefault;
10102            res.labelRes = info.labelRes;
10103            res.nonLocalizedLabel = info.nonLocalizedLabel;
10104            res.icon = info.icon;
10105            res.system = res.providerInfo.applicationInfo.isSystemApp();
10106            return res;
10107        }
10108
10109        @Override
10110        protected void sortResults(List<ResolveInfo> results) {
10111            Collections.sort(results, mResolvePrioritySorter);
10112        }
10113
10114        @Override
10115        protected void dumpFilter(PrintWriter out, String prefix,
10116                PackageParser.ProviderIntentInfo filter) {
10117            out.print(prefix);
10118            out.print(
10119                    Integer.toHexString(System.identityHashCode(filter.provider)));
10120            out.print(' ');
10121            filter.provider.printComponentShortName(out);
10122            out.print(" filter ");
10123            out.println(Integer.toHexString(System.identityHashCode(filter)));
10124        }
10125
10126        @Override
10127        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10128            return filter.provider;
10129        }
10130
10131        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10132            PackageParser.Provider provider = (PackageParser.Provider)label;
10133            out.print(prefix); out.print(
10134                    Integer.toHexString(System.identityHashCode(provider)));
10135                    out.print(' ');
10136                    provider.printComponentShortName(out);
10137            if (count > 1) {
10138                out.print(" ("); out.print(count); out.print(" filters)");
10139            }
10140            out.println();
10141        }
10142
10143        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10144                = new ArrayMap<ComponentName, PackageParser.Provider>();
10145        private int mFlags;
10146    }
10147
10148    private static final class EphemeralIntentResolver
10149            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10150        @Override
10151        protected EphemeralResolveIntentInfo[] newArray(int size) {
10152            return new EphemeralResolveIntentInfo[size];
10153        }
10154
10155        @Override
10156        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10157            return true;
10158        }
10159
10160        @Override
10161        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10162                int userId) {
10163            if (!sUserManager.exists(userId)) {
10164                return null;
10165            }
10166            return info.getEphemeralResolveInfo();
10167        }
10168    }
10169
10170    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10171            new Comparator<ResolveInfo>() {
10172        public int compare(ResolveInfo r1, ResolveInfo r2) {
10173            int v1 = r1.priority;
10174            int v2 = r2.priority;
10175            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10176            if (v1 != v2) {
10177                return (v1 > v2) ? -1 : 1;
10178            }
10179            v1 = r1.preferredOrder;
10180            v2 = r2.preferredOrder;
10181            if (v1 != v2) {
10182                return (v1 > v2) ? -1 : 1;
10183            }
10184            if (r1.isDefault != r2.isDefault) {
10185                return r1.isDefault ? -1 : 1;
10186            }
10187            v1 = r1.match;
10188            v2 = r2.match;
10189            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10190            if (v1 != v2) {
10191                return (v1 > v2) ? -1 : 1;
10192            }
10193            if (r1.system != r2.system) {
10194                return r1.system ? -1 : 1;
10195            }
10196            if (r1.activityInfo != null) {
10197                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10198            }
10199            if (r1.serviceInfo != null) {
10200                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10201            }
10202            if (r1.providerInfo != null) {
10203                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10204            }
10205            return 0;
10206        }
10207    };
10208
10209    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10210            new Comparator<ProviderInfo>() {
10211        public int compare(ProviderInfo p1, ProviderInfo p2) {
10212            final int v1 = p1.initOrder;
10213            final int v2 = p2.initOrder;
10214            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10215        }
10216    };
10217
10218    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10219            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10220            final int[] userIds) {
10221        mHandler.post(new Runnable() {
10222            @Override
10223            public void run() {
10224                try {
10225                    final IActivityManager am = ActivityManagerNative.getDefault();
10226                    if (am == null) return;
10227                    final int[] resolvedUserIds;
10228                    if (userIds == null) {
10229                        resolvedUserIds = am.getRunningUserIds();
10230                    } else {
10231                        resolvedUserIds = userIds;
10232                    }
10233                    for (int id : resolvedUserIds) {
10234                        final Intent intent = new Intent(action,
10235                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10236                        if (extras != null) {
10237                            intent.putExtras(extras);
10238                        }
10239                        if (targetPkg != null) {
10240                            intent.setPackage(targetPkg);
10241                        }
10242                        // Modify the UID when posting to other users
10243                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10244                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10245                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10246                            intent.putExtra(Intent.EXTRA_UID, uid);
10247                        }
10248                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10249                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10250                        if (DEBUG_BROADCASTS) {
10251                            RuntimeException here = new RuntimeException("here");
10252                            here.fillInStackTrace();
10253                            Slog.d(TAG, "Sending to user " + id + ": "
10254                                    + intent.toShortString(false, true, false, false)
10255                                    + " " + intent.getExtras(), here);
10256                        }
10257                        am.broadcastIntent(null, intent, null, finishedReceiver,
10258                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10259                                null, finishedReceiver != null, false, id);
10260                    }
10261                } catch (RemoteException ex) {
10262                }
10263            }
10264        });
10265    }
10266
10267    /**
10268     * Check if the external storage media is available. This is true if there
10269     * is a mounted external storage medium or if the external storage is
10270     * emulated.
10271     */
10272    private boolean isExternalMediaAvailable() {
10273        return mMediaMounted || Environment.isExternalStorageEmulated();
10274    }
10275
10276    @Override
10277    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10278        // writer
10279        synchronized (mPackages) {
10280            if (!isExternalMediaAvailable()) {
10281                // If the external storage is no longer mounted at this point,
10282                // the caller may not have been able to delete all of this
10283                // packages files and can not delete any more.  Bail.
10284                return null;
10285            }
10286            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10287            if (lastPackage != null) {
10288                pkgs.remove(lastPackage);
10289            }
10290            if (pkgs.size() > 0) {
10291                return pkgs.get(0);
10292            }
10293        }
10294        return null;
10295    }
10296
10297    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10298        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10299                userId, andCode ? 1 : 0, packageName);
10300        if (mSystemReady) {
10301            msg.sendToTarget();
10302        } else {
10303            if (mPostSystemReadyMessages == null) {
10304                mPostSystemReadyMessages = new ArrayList<>();
10305            }
10306            mPostSystemReadyMessages.add(msg);
10307        }
10308    }
10309
10310    void startCleaningPackages() {
10311        // reader
10312        synchronized (mPackages) {
10313            if (!isExternalMediaAvailable()) {
10314                return;
10315            }
10316            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10317                return;
10318            }
10319        }
10320        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10321        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10322        IActivityManager am = ActivityManagerNative.getDefault();
10323        if (am != null) {
10324            try {
10325                am.startService(null, intent, null, mContext.getOpPackageName(),
10326                        UserHandle.USER_SYSTEM);
10327            } catch (RemoteException e) {
10328            }
10329        }
10330    }
10331
10332    @Override
10333    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10334            int installFlags, String installerPackageName, VerificationParams verificationParams,
10335            String packageAbiOverride) {
10336        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10337                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10338    }
10339
10340    @Override
10341    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10342            int installFlags, String installerPackageName, VerificationParams verificationParams,
10343            String packageAbiOverride, int userId) {
10344        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10345
10346        final int callingUid = Binder.getCallingUid();
10347        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10348
10349        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10350            try {
10351                if (observer != null) {
10352                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10353                }
10354            } catch (RemoteException re) {
10355            }
10356            return;
10357        }
10358
10359        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10360            installFlags |= PackageManager.INSTALL_FROM_ADB;
10361
10362        } else {
10363            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10364            // about installerPackageName.
10365
10366            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10367            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10368        }
10369
10370        UserHandle user;
10371        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10372            user = UserHandle.ALL;
10373        } else {
10374            user = new UserHandle(userId);
10375        }
10376
10377        // Only system components can circumvent runtime permissions when installing.
10378        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10379                && mContext.checkCallingOrSelfPermission(Manifest.permission
10380                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10381            throw new SecurityException("You need the "
10382                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10383                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10384        }
10385
10386        verificationParams.setInstallerUid(callingUid);
10387
10388        final File originFile = new File(originPath);
10389        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10390
10391        final Message msg = mHandler.obtainMessage(INIT_COPY);
10392        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10393                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10394        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10395        msg.obj = params;
10396
10397        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10398                System.identityHashCode(msg.obj));
10399        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10400                System.identityHashCode(msg.obj));
10401
10402        mHandler.sendMessage(msg);
10403    }
10404
10405    void installStage(String packageName, File stagedDir, String stagedCid,
10406            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10407            String installerPackageName, int installerUid, UserHandle user) {
10408        if (DEBUG_EPHEMERAL) {
10409            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10410                Slog.d(TAG, "Ephemeral install of " + packageName);
10411            }
10412        }
10413        final VerificationParams verifParams = new VerificationParams(
10414                null, sessionParams.originatingUri, sessionParams.referrerUri,
10415                sessionParams.originatingUid);
10416        verifParams.setInstallerUid(installerUid);
10417
10418        final OriginInfo origin;
10419        if (stagedDir != null) {
10420            origin = OriginInfo.fromStagedFile(stagedDir);
10421        } else {
10422            origin = OriginInfo.fromStagedContainer(stagedCid);
10423        }
10424
10425        final Message msg = mHandler.obtainMessage(INIT_COPY);
10426        final InstallParams params = new InstallParams(origin, null, observer,
10427                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10428                verifParams, user, sessionParams.abiOverride,
10429                sessionParams.grantedRuntimePermissions);
10430        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10431        msg.obj = params;
10432
10433        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10434                System.identityHashCode(msg.obj));
10435        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10436                System.identityHashCode(msg.obj));
10437
10438        mHandler.sendMessage(msg);
10439    }
10440
10441    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10442        Bundle extras = new Bundle(1);
10443        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10444
10445        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10446                packageName, extras, 0, null, null, new int[] {userId});
10447        try {
10448            IActivityManager am = ActivityManagerNative.getDefault();
10449            final boolean isSystem =
10450                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10451            if (isSystem && am.isUserRunning(userId, 0)) {
10452                // The just-installed/enabled app is bundled on the system, so presumed
10453                // to be able to run automatically without needing an explicit launch.
10454                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10455                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10456                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10457                        .setPackage(packageName);
10458                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10459                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10460            }
10461        } catch (RemoteException e) {
10462            // shouldn't happen
10463            Slog.w(TAG, "Unable to bootstrap installed package", e);
10464        }
10465    }
10466
10467    @Override
10468    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10469            int userId) {
10470        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10471        PackageSetting pkgSetting;
10472        final int uid = Binder.getCallingUid();
10473        enforceCrossUserPermission(uid, userId, true, true,
10474                "setApplicationHiddenSetting for user " + userId);
10475
10476        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10477            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10478            return false;
10479        }
10480
10481        long callingId = Binder.clearCallingIdentity();
10482        try {
10483            boolean sendAdded = false;
10484            boolean sendRemoved = false;
10485            // writer
10486            synchronized (mPackages) {
10487                pkgSetting = mSettings.mPackages.get(packageName);
10488                if (pkgSetting == null) {
10489                    return false;
10490                }
10491                if (pkgSetting.getHidden(userId) != hidden) {
10492                    pkgSetting.setHidden(hidden, userId);
10493                    mSettings.writePackageRestrictionsLPr(userId);
10494                    if (hidden) {
10495                        sendRemoved = true;
10496                    } else {
10497                        sendAdded = true;
10498                    }
10499                }
10500            }
10501            if (sendAdded) {
10502                sendPackageAddedForUser(packageName, pkgSetting, userId);
10503                return true;
10504            }
10505            if (sendRemoved) {
10506                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10507                        "hiding pkg");
10508                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10509                return true;
10510            }
10511        } finally {
10512            Binder.restoreCallingIdentity(callingId);
10513        }
10514        return false;
10515    }
10516
10517    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10518            int userId) {
10519        final PackageRemovedInfo info = new PackageRemovedInfo();
10520        info.removedPackage = packageName;
10521        info.removedUsers = new int[] {userId};
10522        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10523        info.sendBroadcast(false, false, false);
10524    }
10525
10526    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10527        if (pkgList.length > 0) {
10528            Bundle extras = new Bundle(1);
10529            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10530
10531            sendPackageBroadcast(
10532                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10533                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10534                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10535                    new int[] {userId});
10536        }
10537    }
10538
10539    /**
10540     * Returns true if application is not found or there was an error. Otherwise it returns
10541     * the hidden state of the package for the given user.
10542     */
10543    @Override
10544    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10546        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10547                false, "getApplicationHidden for user " + userId);
10548        PackageSetting pkgSetting;
10549        long callingId = Binder.clearCallingIdentity();
10550        try {
10551            // writer
10552            synchronized (mPackages) {
10553                pkgSetting = mSettings.mPackages.get(packageName);
10554                if (pkgSetting == null) {
10555                    return true;
10556                }
10557                return pkgSetting.getHidden(userId);
10558            }
10559        } finally {
10560            Binder.restoreCallingIdentity(callingId);
10561        }
10562    }
10563
10564    /**
10565     * @hide
10566     */
10567    @Override
10568    public int installExistingPackageAsUser(String packageName, int userId) {
10569        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10570                null);
10571        PackageSetting pkgSetting;
10572        final int uid = Binder.getCallingUid();
10573        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10574                + userId);
10575        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10576            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10577        }
10578
10579        long callingId = Binder.clearCallingIdentity();
10580        try {
10581            boolean installed = false;
10582
10583            // writer
10584            synchronized (mPackages) {
10585                pkgSetting = mSettings.mPackages.get(packageName);
10586                if (pkgSetting == null) {
10587                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10588                }
10589                if (!pkgSetting.getInstalled(userId)) {
10590                    pkgSetting.setInstalled(true, userId);
10591                    pkgSetting.setHidden(false, userId);
10592                    mSettings.writePackageRestrictionsLPr(userId);
10593                    if (pkgSetting.pkg != null) {
10594                        prepareAppDataAfterInstall(pkgSetting.pkg);
10595                    }
10596                    installed = true;
10597                }
10598            }
10599
10600            if (installed) {
10601                sendPackageAddedForUser(packageName, pkgSetting, userId);
10602            }
10603        } finally {
10604            Binder.restoreCallingIdentity(callingId);
10605        }
10606
10607        return PackageManager.INSTALL_SUCCEEDED;
10608    }
10609
10610    boolean isUserRestricted(int userId, String restrictionKey) {
10611        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10612        if (restrictions.getBoolean(restrictionKey, false)) {
10613            Log.w(TAG, "User is restricted: " + restrictionKey);
10614            return true;
10615        }
10616        return false;
10617    }
10618
10619    @Override
10620    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10622        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10623                "setPackageSuspended for user " + userId);
10624
10625        // TODO: investigate and add more restrictions for suspending crucial packages.
10626        if (isPackageDeviceAdmin(packageName, userId)) {
10627            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10628                    + "\": has active device admin");
10629            return false;
10630        }
10631
10632        long callingId = Binder.clearCallingIdentity();
10633        try {
10634            boolean changed = false;
10635            boolean success = false;
10636            int appId = -1;
10637            synchronized (mPackages) {
10638                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10639                if (pkgSetting != null) {
10640                    if (pkgSetting.getSuspended(userId) != suspended) {
10641                        pkgSetting.setSuspended(suspended, userId);
10642                        mSettings.writePackageRestrictionsLPr(userId);
10643                        appId = pkgSetting.appId;
10644                        changed = true;
10645                    }
10646                    success = true;
10647                }
10648            }
10649
10650            if (changed) {
10651                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10652                if (suspended) {
10653                    killApplication(packageName, UserHandle.getUid(userId, appId),
10654                            "suspending package");
10655                }
10656            }
10657            return success;
10658        } finally {
10659            Binder.restoreCallingIdentity(callingId);
10660        }
10661    }
10662
10663    @Override
10664    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10665        mContext.enforceCallingOrSelfPermission(
10666                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10667                "Only package verification agents can verify applications");
10668
10669        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10670        final PackageVerificationResponse response = new PackageVerificationResponse(
10671                verificationCode, Binder.getCallingUid());
10672        msg.arg1 = id;
10673        msg.obj = response;
10674        mHandler.sendMessage(msg);
10675    }
10676
10677    @Override
10678    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10679            long millisecondsToDelay) {
10680        mContext.enforceCallingOrSelfPermission(
10681                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10682                "Only package verification agents can extend verification timeouts");
10683
10684        final PackageVerificationState state = mPendingVerification.get(id);
10685        final PackageVerificationResponse response = new PackageVerificationResponse(
10686                verificationCodeAtTimeout, Binder.getCallingUid());
10687
10688        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10689            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10690        }
10691        if (millisecondsToDelay < 0) {
10692            millisecondsToDelay = 0;
10693        }
10694        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10695                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10696            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10697        }
10698
10699        if ((state != null) && !state.timeoutExtended()) {
10700            state.extendTimeout();
10701
10702            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10703            msg.arg1 = id;
10704            msg.obj = response;
10705            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10706        }
10707    }
10708
10709    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10710            int verificationCode, UserHandle user) {
10711        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10712        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10713        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10714        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10715        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10716
10717        mContext.sendBroadcastAsUser(intent, user,
10718                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10719    }
10720
10721    private ComponentName matchComponentForVerifier(String packageName,
10722            List<ResolveInfo> receivers) {
10723        ActivityInfo targetReceiver = null;
10724
10725        final int NR = receivers.size();
10726        for (int i = 0; i < NR; i++) {
10727            final ResolveInfo info = receivers.get(i);
10728            if (info.activityInfo == null) {
10729                continue;
10730            }
10731
10732            if (packageName.equals(info.activityInfo.packageName)) {
10733                targetReceiver = info.activityInfo;
10734                break;
10735            }
10736        }
10737
10738        if (targetReceiver == null) {
10739            return null;
10740        }
10741
10742        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10743    }
10744
10745    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10746            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10747        if (pkgInfo.verifiers.length == 0) {
10748            return null;
10749        }
10750
10751        final int N = pkgInfo.verifiers.length;
10752        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10753        for (int i = 0; i < N; i++) {
10754            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10755
10756            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10757                    receivers);
10758            if (comp == null) {
10759                continue;
10760            }
10761
10762            final int verifierUid = getUidForVerifier(verifierInfo);
10763            if (verifierUid == -1) {
10764                continue;
10765            }
10766
10767            if (DEBUG_VERIFY) {
10768                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10769                        + " with the correct signature");
10770            }
10771            sufficientVerifiers.add(comp);
10772            verificationState.addSufficientVerifier(verifierUid);
10773        }
10774
10775        return sufficientVerifiers;
10776    }
10777
10778    private int getUidForVerifier(VerifierInfo verifierInfo) {
10779        synchronized (mPackages) {
10780            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10781            if (pkg == null) {
10782                return -1;
10783            } else if (pkg.mSignatures.length != 1) {
10784                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10785                        + " has more than one signature; ignoring");
10786                return -1;
10787            }
10788
10789            /*
10790             * If the public key of the package's signature does not match
10791             * our expected public key, then this is a different package and
10792             * we should skip.
10793             */
10794
10795            final byte[] expectedPublicKey;
10796            try {
10797                final Signature verifierSig = pkg.mSignatures[0];
10798                final PublicKey publicKey = verifierSig.getPublicKey();
10799                expectedPublicKey = publicKey.getEncoded();
10800            } catch (CertificateException e) {
10801                return -1;
10802            }
10803
10804            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10805
10806            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10807                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10808                        + " does not have the expected public key; ignoring");
10809                return -1;
10810            }
10811
10812            return pkg.applicationInfo.uid;
10813        }
10814    }
10815
10816    @Override
10817    public void finishPackageInstall(int token) {
10818        enforceSystemOrRoot("Only the system is allowed to finish installs");
10819
10820        if (DEBUG_INSTALL) {
10821            Slog.v(TAG, "BM finishing package install for " + token);
10822        }
10823        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10824
10825        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10826        mHandler.sendMessage(msg);
10827    }
10828
10829    /**
10830     * Get the verification agent timeout.
10831     *
10832     * @return verification timeout in milliseconds
10833     */
10834    private long getVerificationTimeout() {
10835        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10836                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10837                DEFAULT_VERIFICATION_TIMEOUT);
10838    }
10839
10840    /**
10841     * Get the default verification agent response code.
10842     *
10843     * @return default verification response code
10844     */
10845    private int getDefaultVerificationResponse() {
10846        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10847                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10848                DEFAULT_VERIFICATION_RESPONSE);
10849    }
10850
10851    /**
10852     * Check whether or not package verification has been enabled.
10853     *
10854     * @return true if verification should be performed
10855     */
10856    private boolean isVerificationEnabled(int userId, int installFlags) {
10857        if (!DEFAULT_VERIFY_ENABLE) {
10858            return false;
10859        }
10860        // Ephemeral apps don't get the full verification treatment
10861        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10862            if (DEBUG_EPHEMERAL) {
10863                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10864            }
10865            return false;
10866        }
10867
10868        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10869
10870        // Check if installing from ADB
10871        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10872            // Do not run verification in a test harness environment
10873            if (ActivityManager.isRunningInTestHarness()) {
10874                return false;
10875            }
10876            if (ensureVerifyAppsEnabled) {
10877                return true;
10878            }
10879            // Check if the developer does not want package verification for ADB installs
10880            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10881                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10882                return false;
10883            }
10884        }
10885
10886        if (ensureVerifyAppsEnabled) {
10887            return true;
10888        }
10889
10890        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10891                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10892    }
10893
10894    @Override
10895    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10896            throws RemoteException {
10897        mContext.enforceCallingOrSelfPermission(
10898                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10899                "Only intentfilter verification agents can verify applications");
10900
10901        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10902        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10903                Binder.getCallingUid(), verificationCode, failedDomains);
10904        msg.arg1 = id;
10905        msg.obj = response;
10906        mHandler.sendMessage(msg);
10907    }
10908
10909    @Override
10910    public int getIntentVerificationStatus(String packageName, int userId) {
10911        synchronized (mPackages) {
10912            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10913        }
10914    }
10915
10916    @Override
10917    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10918        mContext.enforceCallingOrSelfPermission(
10919                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10920
10921        boolean result = false;
10922        synchronized (mPackages) {
10923            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10924        }
10925        if (result) {
10926            scheduleWritePackageRestrictionsLocked(userId);
10927        }
10928        return result;
10929    }
10930
10931    @Override
10932    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10933        synchronized (mPackages) {
10934            return mSettings.getIntentFilterVerificationsLPr(packageName);
10935        }
10936    }
10937
10938    @Override
10939    public List<IntentFilter> getAllIntentFilters(String packageName) {
10940        if (TextUtils.isEmpty(packageName)) {
10941            return Collections.<IntentFilter>emptyList();
10942        }
10943        synchronized (mPackages) {
10944            PackageParser.Package pkg = mPackages.get(packageName);
10945            if (pkg == null || pkg.activities == null) {
10946                return Collections.<IntentFilter>emptyList();
10947            }
10948            final int count = pkg.activities.size();
10949            ArrayList<IntentFilter> result = new ArrayList<>();
10950            for (int n=0; n<count; n++) {
10951                PackageParser.Activity activity = pkg.activities.get(n);
10952                if (activity.intents != null && activity.intents.size() > 0) {
10953                    result.addAll(activity.intents);
10954                }
10955            }
10956            return result;
10957        }
10958    }
10959
10960    @Override
10961    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10962        mContext.enforceCallingOrSelfPermission(
10963                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10964
10965        synchronized (mPackages) {
10966            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10967            if (packageName != null) {
10968                result |= updateIntentVerificationStatus(packageName,
10969                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10970                        userId);
10971                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10972                        packageName, userId);
10973            }
10974            return result;
10975        }
10976    }
10977
10978    @Override
10979    public String getDefaultBrowserPackageName(int userId) {
10980        synchronized (mPackages) {
10981            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10982        }
10983    }
10984
10985    /**
10986     * Get the "allow unknown sources" setting.
10987     *
10988     * @return the current "allow unknown sources" setting
10989     */
10990    private int getUnknownSourcesSettings() {
10991        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10992                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10993                -1);
10994    }
10995
10996    @Override
10997    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10998        final int uid = Binder.getCallingUid();
10999        // writer
11000        synchronized (mPackages) {
11001            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11002            if (targetPackageSetting == null) {
11003                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11004            }
11005
11006            PackageSetting installerPackageSetting;
11007            if (installerPackageName != null) {
11008                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11009                if (installerPackageSetting == null) {
11010                    throw new IllegalArgumentException("Unknown installer package: "
11011                            + installerPackageName);
11012                }
11013            } else {
11014                installerPackageSetting = null;
11015            }
11016
11017            Signature[] callerSignature;
11018            Object obj = mSettings.getUserIdLPr(uid);
11019            if (obj != null) {
11020                if (obj instanceof SharedUserSetting) {
11021                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11022                } else if (obj instanceof PackageSetting) {
11023                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11024                } else {
11025                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11026                }
11027            } else {
11028                throw new SecurityException("Unknown calling UID: " + uid);
11029            }
11030
11031            // Verify: can't set installerPackageName to a package that is
11032            // not signed with the same cert as the caller.
11033            if (installerPackageSetting != null) {
11034                if (compareSignatures(callerSignature,
11035                        installerPackageSetting.signatures.mSignatures)
11036                        != PackageManager.SIGNATURE_MATCH) {
11037                    throw new SecurityException(
11038                            "Caller does not have same cert as new installer package "
11039                            + installerPackageName);
11040                }
11041            }
11042
11043            // Verify: if target already has an installer package, it must
11044            // be signed with the same cert as the caller.
11045            if (targetPackageSetting.installerPackageName != null) {
11046                PackageSetting setting = mSettings.mPackages.get(
11047                        targetPackageSetting.installerPackageName);
11048                // If the currently set package isn't valid, then it's always
11049                // okay to change it.
11050                if (setting != null) {
11051                    if (compareSignatures(callerSignature,
11052                            setting.signatures.mSignatures)
11053                            != PackageManager.SIGNATURE_MATCH) {
11054                        throw new SecurityException(
11055                                "Caller does not have same cert as old installer package "
11056                                + targetPackageSetting.installerPackageName);
11057                    }
11058                }
11059            }
11060
11061            // Okay!
11062            targetPackageSetting.installerPackageName = installerPackageName;
11063            scheduleWriteSettingsLocked();
11064        }
11065    }
11066
11067    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11068        // Queue up an async operation since the package installation may take a little while.
11069        mHandler.post(new Runnable() {
11070            public void run() {
11071                mHandler.removeCallbacks(this);
11072                 // Result object to be returned
11073                PackageInstalledInfo res = new PackageInstalledInfo();
11074                res.returnCode = currentStatus;
11075                res.uid = -1;
11076                res.pkg = null;
11077                res.removedInfo = new PackageRemovedInfo();
11078                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11079                    args.doPreInstall(res.returnCode);
11080                    synchronized (mInstallLock) {
11081                        installPackageTracedLI(args, res);
11082                    }
11083                    args.doPostInstall(res.returnCode, res.uid);
11084                }
11085
11086                // A restore should be performed at this point if (a) the install
11087                // succeeded, (b) the operation is not an update, and (c) the new
11088                // package has not opted out of backup participation.
11089                final boolean update = res.removedInfo.removedPackage != null;
11090                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11091                boolean doRestore = !update
11092                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11093
11094                // Set up the post-install work request bookkeeping.  This will be used
11095                // and cleaned up by the post-install event handling regardless of whether
11096                // there's a restore pass performed.  Token values are >= 1.
11097                int token;
11098                if (mNextInstallToken < 0) mNextInstallToken = 1;
11099                token = mNextInstallToken++;
11100
11101                PostInstallData data = new PostInstallData(args, res);
11102                mRunningInstalls.put(token, data);
11103                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11104
11105                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11106                    // Pass responsibility to the Backup Manager.  It will perform a
11107                    // restore if appropriate, then pass responsibility back to the
11108                    // Package Manager to run the post-install observer callbacks
11109                    // and broadcasts.
11110                    IBackupManager bm = IBackupManager.Stub.asInterface(
11111                            ServiceManager.getService(Context.BACKUP_SERVICE));
11112                    if (bm != null) {
11113                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11114                                + " to BM for possible restore");
11115                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11116                        try {
11117                            // TODO: http://b/22388012
11118                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11119                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11120                            } else {
11121                                doRestore = false;
11122                            }
11123                        } catch (RemoteException e) {
11124                            // can't happen; the backup manager is local
11125                        } catch (Exception e) {
11126                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11127                            doRestore = false;
11128                        }
11129                    } else {
11130                        Slog.e(TAG, "Backup Manager not found!");
11131                        doRestore = false;
11132                    }
11133                }
11134
11135                if (!doRestore) {
11136                    // No restore possible, or the Backup Manager was mysteriously not
11137                    // available -- just fire the post-install work request directly.
11138                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11139
11140                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11141
11142                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11143                    mHandler.sendMessage(msg);
11144                }
11145            }
11146        });
11147    }
11148
11149    private abstract class HandlerParams {
11150        private static final int MAX_RETRIES = 4;
11151
11152        /**
11153         * Number of times startCopy() has been attempted and had a non-fatal
11154         * error.
11155         */
11156        private int mRetries = 0;
11157
11158        /** User handle for the user requesting the information or installation. */
11159        private final UserHandle mUser;
11160        String traceMethod;
11161        int traceCookie;
11162
11163        HandlerParams(UserHandle user) {
11164            mUser = user;
11165        }
11166
11167        UserHandle getUser() {
11168            return mUser;
11169        }
11170
11171        HandlerParams setTraceMethod(String traceMethod) {
11172            this.traceMethod = traceMethod;
11173            return this;
11174        }
11175
11176        HandlerParams setTraceCookie(int traceCookie) {
11177            this.traceCookie = traceCookie;
11178            return this;
11179        }
11180
11181        final boolean startCopy() {
11182            boolean res;
11183            try {
11184                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11185
11186                if (++mRetries > MAX_RETRIES) {
11187                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11188                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11189                    handleServiceError();
11190                    return false;
11191                } else {
11192                    handleStartCopy();
11193                    res = true;
11194                }
11195            } catch (RemoteException e) {
11196                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11197                mHandler.sendEmptyMessage(MCS_RECONNECT);
11198                res = false;
11199            }
11200            handleReturnCode();
11201            return res;
11202        }
11203
11204        final void serviceError() {
11205            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11206            handleServiceError();
11207            handleReturnCode();
11208        }
11209
11210        abstract void handleStartCopy() throws RemoteException;
11211        abstract void handleServiceError();
11212        abstract void handleReturnCode();
11213    }
11214
11215    class MeasureParams extends HandlerParams {
11216        private final PackageStats mStats;
11217        private boolean mSuccess;
11218
11219        private final IPackageStatsObserver mObserver;
11220
11221        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11222            super(new UserHandle(stats.userHandle));
11223            mObserver = observer;
11224            mStats = stats;
11225        }
11226
11227        @Override
11228        public String toString() {
11229            return "MeasureParams{"
11230                + Integer.toHexString(System.identityHashCode(this))
11231                + " " + mStats.packageName + "}";
11232        }
11233
11234        @Override
11235        void handleStartCopy() throws RemoteException {
11236            synchronized (mInstallLock) {
11237                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11238            }
11239
11240            if (mSuccess) {
11241                final boolean mounted;
11242                if (Environment.isExternalStorageEmulated()) {
11243                    mounted = true;
11244                } else {
11245                    final String status = Environment.getExternalStorageState();
11246                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11247                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11248                }
11249
11250                if (mounted) {
11251                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11252
11253                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11254                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11255
11256                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11257                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11258
11259                    // Always subtract cache size, since it's a subdirectory
11260                    mStats.externalDataSize -= mStats.externalCacheSize;
11261
11262                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11263                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11264
11265                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11266                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11267                }
11268            }
11269        }
11270
11271        @Override
11272        void handleReturnCode() {
11273            if (mObserver != null) {
11274                try {
11275                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11276                } catch (RemoteException e) {
11277                    Slog.i(TAG, "Observer no longer exists.");
11278                }
11279            }
11280        }
11281
11282        @Override
11283        void handleServiceError() {
11284            Slog.e(TAG, "Could not measure application " + mStats.packageName
11285                            + " external storage");
11286        }
11287    }
11288
11289    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11290            throws RemoteException {
11291        long result = 0;
11292        for (File path : paths) {
11293            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11294        }
11295        return result;
11296    }
11297
11298    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11299        for (File path : paths) {
11300            try {
11301                mcs.clearDirectory(path.getAbsolutePath());
11302            } catch (RemoteException e) {
11303            }
11304        }
11305    }
11306
11307    static class OriginInfo {
11308        /**
11309         * Location where install is coming from, before it has been
11310         * copied/renamed into place. This could be a single monolithic APK
11311         * file, or a cluster directory. This location may be untrusted.
11312         */
11313        final File file;
11314        final String cid;
11315
11316        /**
11317         * Flag indicating that {@link #file} or {@link #cid} has already been
11318         * staged, meaning downstream users don't need to defensively copy the
11319         * contents.
11320         */
11321        final boolean staged;
11322
11323        /**
11324         * Flag indicating that {@link #file} or {@link #cid} is an already
11325         * installed app that is being moved.
11326         */
11327        final boolean existing;
11328
11329        final String resolvedPath;
11330        final File resolvedFile;
11331
11332        static OriginInfo fromNothing() {
11333            return new OriginInfo(null, null, false, false);
11334        }
11335
11336        static OriginInfo fromUntrustedFile(File file) {
11337            return new OriginInfo(file, null, false, false);
11338        }
11339
11340        static OriginInfo fromExistingFile(File file) {
11341            return new OriginInfo(file, null, false, true);
11342        }
11343
11344        static OriginInfo fromStagedFile(File file) {
11345            return new OriginInfo(file, null, true, false);
11346        }
11347
11348        static OriginInfo fromStagedContainer(String cid) {
11349            return new OriginInfo(null, cid, true, false);
11350        }
11351
11352        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11353            this.file = file;
11354            this.cid = cid;
11355            this.staged = staged;
11356            this.existing = existing;
11357
11358            if (cid != null) {
11359                resolvedPath = PackageHelper.getSdDir(cid);
11360                resolvedFile = new File(resolvedPath);
11361            } else if (file != null) {
11362                resolvedPath = file.getAbsolutePath();
11363                resolvedFile = file;
11364            } else {
11365                resolvedPath = null;
11366                resolvedFile = null;
11367            }
11368        }
11369    }
11370
11371    static class MoveInfo {
11372        final int moveId;
11373        final String fromUuid;
11374        final String toUuid;
11375        final String packageName;
11376        final String dataAppName;
11377        final int appId;
11378        final String seinfo;
11379        final int targetSdkVersion;
11380
11381        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11382                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11383            this.moveId = moveId;
11384            this.fromUuid = fromUuid;
11385            this.toUuid = toUuid;
11386            this.packageName = packageName;
11387            this.dataAppName = dataAppName;
11388            this.appId = appId;
11389            this.seinfo = seinfo;
11390            this.targetSdkVersion = targetSdkVersion;
11391        }
11392    }
11393
11394    class InstallParams extends HandlerParams {
11395        final OriginInfo origin;
11396        final MoveInfo move;
11397        final IPackageInstallObserver2 observer;
11398        int installFlags;
11399        final String installerPackageName;
11400        final String volumeUuid;
11401        final VerificationParams verificationParams;
11402        private InstallArgs mArgs;
11403        private int mRet;
11404        final String packageAbiOverride;
11405        final String[] grantedRuntimePermissions;
11406
11407        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11408                int installFlags, String installerPackageName, String volumeUuid,
11409                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11410                String[] grantedPermissions) {
11411            super(user);
11412            this.origin = origin;
11413            this.move = move;
11414            this.observer = observer;
11415            this.installFlags = installFlags;
11416            this.installerPackageName = installerPackageName;
11417            this.volumeUuid = volumeUuid;
11418            this.verificationParams = verificationParams;
11419            this.packageAbiOverride = packageAbiOverride;
11420            this.grantedRuntimePermissions = grantedPermissions;
11421        }
11422
11423        @Override
11424        public String toString() {
11425            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11426                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11427        }
11428
11429        private int installLocationPolicy(PackageInfoLite pkgLite) {
11430            String packageName = pkgLite.packageName;
11431            int installLocation = pkgLite.installLocation;
11432            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11433            // reader
11434            synchronized (mPackages) {
11435                PackageParser.Package pkg = mPackages.get(packageName);
11436                if (pkg != null) {
11437                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11438                        // Check for downgrading.
11439                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11440                            try {
11441                                checkDowngrade(pkg, pkgLite);
11442                            } catch (PackageManagerException e) {
11443                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11444                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11445                            }
11446                        }
11447                        // Check for updated system application.
11448                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11449                            if (onSd) {
11450                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11451                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11452                            }
11453                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11454                        } else {
11455                            if (onSd) {
11456                                // Install flag overrides everything.
11457                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11458                            }
11459                            // If current upgrade specifies particular preference
11460                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11461                                // Application explicitly specified internal.
11462                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11463                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11464                                // App explictly prefers external. Let policy decide
11465                            } else {
11466                                // Prefer previous location
11467                                if (isExternal(pkg)) {
11468                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11469                                }
11470                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11471                            }
11472                        }
11473                    } else {
11474                        // Invalid install. Return error code
11475                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11476                    }
11477                }
11478            }
11479            // All the special cases have been taken care of.
11480            // Return result based on recommended install location.
11481            if (onSd) {
11482                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11483            }
11484            return pkgLite.recommendedInstallLocation;
11485        }
11486
11487        /*
11488         * Invoke remote method to get package information and install
11489         * location values. Override install location based on default
11490         * policy if needed and then create install arguments based
11491         * on the install location.
11492         */
11493        public void handleStartCopy() throws RemoteException {
11494            int ret = PackageManager.INSTALL_SUCCEEDED;
11495
11496            // If we're already staged, we've firmly committed to an install location
11497            if (origin.staged) {
11498                if (origin.file != null) {
11499                    installFlags |= PackageManager.INSTALL_INTERNAL;
11500                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11501                } else if (origin.cid != null) {
11502                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11503                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11504                } else {
11505                    throw new IllegalStateException("Invalid stage location");
11506                }
11507            }
11508
11509            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11510            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11511            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11512            PackageInfoLite pkgLite = null;
11513
11514            if (onInt && onSd) {
11515                // Check if both bits are set.
11516                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11517                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11518            } else if (onSd && ephemeral) {
11519                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11520                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11521            } else {
11522                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11523                        packageAbiOverride);
11524
11525                if (DEBUG_EPHEMERAL && ephemeral) {
11526                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11527                }
11528
11529                /*
11530                 * If we have too little free space, try to free cache
11531                 * before giving up.
11532                 */
11533                if (!origin.staged && pkgLite.recommendedInstallLocation
11534                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11535                    // TODO: focus freeing disk space on the target device
11536                    final StorageManager storage = StorageManager.from(mContext);
11537                    final long lowThreshold = storage.getStorageLowBytes(
11538                            Environment.getDataDirectory());
11539
11540                    final long sizeBytes = mContainerService.calculateInstalledSize(
11541                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11542
11543                    try {
11544                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11545                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11546                                installFlags, packageAbiOverride);
11547                    } catch (InstallerException e) {
11548                        Slog.w(TAG, "Failed to free cache", e);
11549                    }
11550
11551                    /*
11552                     * The cache free must have deleted the file we
11553                     * downloaded to install.
11554                     *
11555                     * TODO: fix the "freeCache" call to not delete
11556                     *       the file we care about.
11557                     */
11558                    if (pkgLite.recommendedInstallLocation
11559                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11560                        pkgLite.recommendedInstallLocation
11561                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11562                    }
11563                }
11564            }
11565
11566            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11567                int loc = pkgLite.recommendedInstallLocation;
11568                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11569                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11570                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11571                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11572                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11573                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11574                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11575                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11576                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11577                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11578                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11579                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11580                } else {
11581                    // Override with defaults if needed.
11582                    loc = installLocationPolicy(pkgLite);
11583                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11584                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11585                    } else if (!onSd && !onInt) {
11586                        // Override install location with flags
11587                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11588                            // Set the flag to install on external media.
11589                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11590                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11591                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11592                            if (DEBUG_EPHEMERAL) {
11593                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11594                            }
11595                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11596                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11597                                    |PackageManager.INSTALL_INTERNAL);
11598                        } else {
11599                            // Make sure the flag for installing on external
11600                            // media is unset
11601                            installFlags |= PackageManager.INSTALL_INTERNAL;
11602                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11603                        }
11604                    }
11605                }
11606            }
11607
11608            final InstallArgs args = createInstallArgs(this);
11609            mArgs = args;
11610
11611            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11612                // TODO: http://b/22976637
11613                // Apps installed for "all" users use the device owner to verify the app
11614                UserHandle verifierUser = getUser();
11615                if (verifierUser == UserHandle.ALL) {
11616                    verifierUser = UserHandle.SYSTEM;
11617                }
11618
11619                /*
11620                 * Determine if we have any installed package verifiers. If we
11621                 * do, then we'll defer to them to verify the packages.
11622                 */
11623                final int requiredUid = mRequiredVerifierPackage == null ? -1
11624                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11625                                verifierUser.getIdentifier());
11626                if (!origin.existing && requiredUid != -1
11627                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11628                    final Intent verification = new Intent(
11629                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11630                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11631                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11632                            PACKAGE_MIME_TYPE);
11633                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11634
11635                    // Query all live verifiers based on current user state
11636                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11637                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11638
11639                    if (DEBUG_VERIFY) {
11640                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11641                                + verification.toString() + " with " + pkgLite.verifiers.length
11642                                + " optional verifiers");
11643                    }
11644
11645                    final int verificationId = mPendingVerificationToken++;
11646
11647                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11648
11649                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11650                            installerPackageName);
11651
11652                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11653                            installFlags);
11654
11655                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11656                            pkgLite.packageName);
11657
11658                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11659                            pkgLite.versionCode);
11660
11661                    if (verificationParams != null) {
11662                        if (verificationParams.getVerificationURI() != null) {
11663                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11664                                 verificationParams.getVerificationURI());
11665                        }
11666                        if (verificationParams.getOriginatingURI() != null) {
11667                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11668                                  verificationParams.getOriginatingURI());
11669                        }
11670                        if (verificationParams.getReferrer() != null) {
11671                            verification.putExtra(Intent.EXTRA_REFERRER,
11672                                  verificationParams.getReferrer());
11673                        }
11674                        if (verificationParams.getOriginatingUid() >= 0) {
11675                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11676                                  verificationParams.getOriginatingUid());
11677                        }
11678                        if (verificationParams.getInstallerUid() >= 0) {
11679                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11680                                  verificationParams.getInstallerUid());
11681                        }
11682                    }
11683
11684                    final PackageVerificationState verificationState = new PackageVerificationState(
11685                            requiredUid, args);
11686
11687                    mPendingVerification.append(verificationId, verificationState);
11688
11689                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11690                            receivers, verificationState);
11691
11692                    /*
11693                     * If any sufficient verifiers were listed in the package
11694                     * manifest, attempt to ask them.
11695                     */
11696                    if (sufficientVerifiers != null) {
11697                        final int N = sufficientVerifiers.size();
11698                        if (N == 0) {
11699                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11700                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11701                        } else {
11702                            for (int i = 0; i < N; i++) {
11703                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11704
11705                                final Intent sufficientIntent = new Intent(verification);
11706                                sufficientIntent.setComponent(verifierComponent);
11707                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11708                            }
11709                        }
11710                    }
11711
11712                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11713                            mRequiredVerifierPackage, receivers);
11714                    if (ret == PackageManager.INSTALL_SUCCEEDED
11715                            && mRequiredVerifierPackage != null) {
11716                        Trace.asyncTraceBegin(
11717                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11718                        /*
11719                         * Send the intent to the required verification agent,
11720                         * but only start the verification timeout after the
11721                         * target BroadcastReceivers have run.
11722                         */
11723                        verification.setComponent(requiredVerifierComponent);
11724                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11725                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11726                                new BroadcastReceiver() {
11727                                    @Override
11728                                    public void onReceive(Context context, Intent intent) {
11729                                        final Message msg = mHandler
11730                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11731                                        msg.arg1 = verificationId;
11732                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11733                                    }
11734                                }, null, 0, null, null);
11735
11736                        /*
11737                         * We don't want the copy to proceed until verification
11738                         * succeeds, so null out this field.
11739                         */
11740                        mArgs = null;
11741                    }
11742                } else {
11743                    /*
11744                     * No package verification is enabled, so immediately start
11745                     * the remote call to initiate copy using temporary file.
11746                     */
11747                    ret = args.copyApk(mContainerService, true);
11748                }
11749            }
11750
11751            mRet = ret;
11752        }
11753
11754        @Override
11755        void handleReturnCode() {
11756            // If mArgs is null, then MCS couldn't be reached. When it
11757            // reconnects, it will try again to install. At that point, this
11758            // will succeed.
11759            if (mArgs != null) {
11760                processPendingInstall(mArgs, mRet);
11761            }
11762        }
11763
11764        @Override
11765        void handleServiceError() {
11766            mArgs = createInstallArgs(this);
11767            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11768        }
11769
11770        public boolean isForwardLocked() {
11771            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11772        }
11773    }
11774
11775    /**
11776     * Used during creation of InstallArgs
11777     *
11778     * @param installFlags package installation flags
11779     * @return true if should be installed on external storage
11780     */
11781    private static boolean installOnExternalAsec(int installFlags) {
11782        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11783            return false;
11784        }
11785        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11786            return true;
11787        }
11788        return false;
11789    }
11790
11791    /**
11792     * Used during creation of InstallArgs
11793     *
11794     * @param installFlags package installation flags
11795     * @return true if should be installed as forward locked
11796     */
11797    private static boolean installForwardLocked(int installFlags) {
11798        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11799    }
11800
11801    private InstallArgs createInstallArgs(InstallParams params) {
11802        if (params.move != null) {
11803            return new MoveInstallArgs(params);
11804        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11805            return new AsecInstallArgs(params);
11806        } else {
11807            return new FileInstallArgs(params);
11808        }
11809    }
11810
11811    /**
11812     * Create args that describe an existing installed package. Typically used
11813     * when cleaning up old installs, or used as a move source.
11814     */
11815    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11816            String resourcePath, String[] instructionSets) {
11817        final boolean isInAsec;
11818        if (installOnExternalAsec(installFlags)) {
11819            /* Apps on SD card are always in ASEC containers. */
11820            isInAsec = true;
11821        } else if (installForwardLocked(installFlags)
11822                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11823            /*
11824             * Forward-locked apps are only in ASEC containers if they're the
11825             * new style
11826             */
11827            isInAsec = true;
11828        } else {
11829            isInAsec = false;
11830        }
11831
11832        if (isInAsec) {
11833            return new AsecInstallArgs(codePath, instructionSets,
11834                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11835        } else {
11836            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11837        }
11838    }
11839
11840    static abstract class InstallArgs {
11841        /** @see InstallParams#origin */
11842        final OriginInfo origin;
11843        /** @see InstallParams#move */
11844        final MoveInfo move;
11845
11846        final IPackageInstallObserver2 observer;
11847        // Always refers to PackageManager flags only
11848        final int installFlags;
11849        final String installerPackageName;
11850        final String volumeUuid;
11851        final UserHandle user;
11852        final String abiOverride;
11853        final String[] installGrantPermissions;
11854        /** If non-null, drop an async trace when the install completes */
11855        final String traceMethod;
11856        final int traceCookie;
11857
11858        // The list of instruction sets supported by this app. This is currently
11859        // only used during the rmdex() phase to clean up resources. We can get rid of this
11860        // if we move dex files under the common app path.
11861        /* nullable */ String[] instructionSets;
11862
11863        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11864                int installFlags, String installerPackageName, String volumeUuid,
11865                UserHandle user, String[] instructionSets,
11866                String abiOverride, String[] installGrantPermissions,
11867                String traceMethod, int traceCookie) {
11868            this.origin = origin;
11869            this.move = move;
11870            this.installFlags = installFlags;
11871            this.observer = observer;
11872            this.installerPackageName = installerPackageName;
11873            this.volumeUuid = volumeUuid;
11874            this.user = user;
11875            this.instructionSets = instructionSets;
11876            this.abiOverride = abiOverride;
11877            this.installGrantPermissions = installGrantPermissions;
11878            this.traceMethod = traceMethod;
11879            this.traceCookie = traceCookie;
11880        }
11881
11882        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11883        abstract int doPreInstall(int status);
11884
11885        /**
11886         * Rename package into final resting place. All paths on the given
11887         * scanned package should be updated to reflect the rename.
11888         */
11889        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11890        abstract int doPostInstall(int status, int uid);
11891
11892        /** @see PackageSettingBase#codePathString */
11893        abstract String getCodePath();
11894        /** @see PackageSettingBase#resourcePathString */
11895        abstract String getResourcePath();
11896
11897        // Need installer lock especially for dex file removal.
11898        abstract void cleanUpResourcesLI();
11899        abstract boolean doPostDeleteLI(boolean delete);
11900
11901        /**
11902         * Called before the source arguments are copied. This is used mostly
11903         * for MoveParams when it needs to read the source file to put it in the
11904         * destination.
11905         */
11906        int doPreCopy() {
11907            return PackageManager.INSTALL_SUCCEEDED;
11908        }
11909
11910        /**
11911         * Called after the source arguments are copied. This is used mostly for
11912         * MoveParams when it needs to read the source file to put it in the
11913         * destination.
11914         *
11915         * @return
11916         */
11917        int doPostCopy(int uid) {
11918            return PackageManager.INSTALL_SUCCEEDED;
11919        }
11920
11921        protected boolean isFwdLocked() {
11922            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11923        }
11924
11925        protected boolean isExternalAsec() {
11926            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11927        }
11928
11929        protected boolean isEphemeral() {
11930            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11931        }
11932
11933        UserHandle getUser() {
11934            return user;
11935        }
11936    }
11937
11938    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11939        if (!allCodePaths.isEmpty()) {
11940            if (instructionSets == null) {
11941                throw new IllegalStateException("instructionSet == null");
11942            }
11943            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11944            for (String codePath : allCodePaths) {
11945                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11946                    try {
11947                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11948                    } catch (InstallerException ignored) {
11949                    }
11950                }
11951            }
11952        }
11953    }
11954
11955    /**
11956     * Logic to handle installation of non-ASEC applications, including copying
11957     * and renaming logic.
11958     */
11959    class FileInstallArgs extends InstallArgs {
11960        private File codeFile;
11961        private File resourceFile;
11962
11963        // Example topology:
11964        // /data/app/com.example/base.apk
11965        // /data/app/com.example/split_foo.apk
11966        // /data/app/com.example/lib/arm/libfoo.so
11967        // /data/app/com.example/lib/arm64/libfoo.so
11968        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11969
11970        /** New install */
11971        FileInstallArgs(InstallParams params) {
11972            super(params.origin, params.move, params.observer, params.installFlags,
11973                    params.installerPackageName, params.volumeUuid,
11974                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11975                    params.grantedRuntimePermissions,
11976                    params.traceMethod, params.traceCookie);
11977            if (isFwdLocked()) {
11978                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11979            }
11980        }
11981
11982        /** Existing install */
11983        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11984            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11985                    null, null, null, 0);
11986            this.codeFile = (codePath != null) ? new File(codePath) : null;
11987            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11988        }
11989
11990        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11991            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11992            try {
11993                return doCopyApk(imcs, temp);
11994            } finally {
11995                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11996            }
11997        }
11998
11999        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12000            if (origin.staged) {
12001                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12002                codeFile = origin.file;
12003                resourceFile = origin.file;
12004                return PackageManager.INSTALL_SUCCEEDED;
12005            }
12006
12007            try {
12008                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12009                final File tempDir =
12010                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12011                codeFile = tempDir;
12012                resourceFile = tempDir;
12013            } catch (IOException e) {
12014                Slog.w(TAG, "Failed to create copy file: " + e);
12015                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12016            }
12017
12018            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12019                @Override
12020                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12021                    if (!FileUtils.isValidExtFilename(name)) {
12022                        throw new IllegalArgumentException("Invalid filename: " + name);
12023                    }
12024                    try {
12025                        final File file = new File(codeFile, name);
12026                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12027                                O_RDWR | O_CREAT, 0644);
12028                        Os.chmod(file.getAbsolutePath(), 0644);
12029                        return new ParcelFileDescriptor(fd);
12030                    } catch (ErrnoException e) {
12031                        throw new RemoteException("Failed to open: " + e.getMessage());
12032                    }
12033                }
12034            };
12035
12036            int ret = PackageManager.INSTALL_SUCCEEDED;
12037            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12038            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12039                Slog.e(TAG, "Failed to copy package");
12040                return ret;
12041            }
12042
12043            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12044            NativeLibraryHelper.Handle handle = null;
12045            try {
12046                handle = NativeLibraryHelper.Handle.create(codeFile);
12047                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12048                        abiOverride);
12049            } catch (IOException e) {
12050                Slog.e(TAG, "Copying native libraries failed", e);
12051                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12052            } finally {
12053                IoUtils.closeQuietly(handle);
12054            }
12055
12056            return ret;
12057        }
12058
12059        int doPreInstall(int status) {
12060            if (status != PackageManager.INSTALL_SUCCEEDED) {
12061                cleanUp();
12062            }
12063            return status;
12064        }
12065
12066        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12067            if (status != PackageManager.INSTALL_SUCCEEDED) {
12068                cleanUp();
12069                return false;
12070            }
12071
12072            final File targetDir = codeFile.getParentFile();
12073            final File beforeCodeFile = codeFile;
12074            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12075
12076            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12077            try {
12078                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12079            } catch (ErrnoException e) {
12080                Slog.w(TAG, "Failed to rename", e);
12081                return false;
12082            }
12083
12084            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12085                Slog.w(TAG, "Failed to restorecon");
12086                return false;
12087            }
12088
12089            // Reflect the rename internally
12090            codeFile = afterCodeFile;
12091            resourceFile = afterCodeFile;
12092
12093            // Reflect the rename in scanned details
12094            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12095            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12096                    afterCodeFile, pkg.baseCodePath));
12097            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12098                    afterCodeFile, pkg.splitCodePaths));
12099
12100            // Reflect the rename in app info
12101            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12102            pkg.setApplicationInfoCodePath(pkg.codePath);
12103            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12104            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12105            pkg.setApplicationInfoResourcePath(pkg.codePath);
12106            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12107            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12108
12109            return true;
12110        }
12111
12112        int doPostInstall(int status, int uid) {
12113            if (status != PackageManager.INSTALL_SUCCEEDED) {
12114                cleanUp();
12115            }
12116            return status;
12117        }
12118
12119        @Override
12120        String getCodePath() {
12121            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12122        }
12123
12124        @Override
12125        String getResourcePath() {
12126            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12127        }
12128
12129        private boolean cleanUp() {
12130            if (codeFile == null || !codeFile.exists()) {
12131                return false;
12132            }
12133
12134            removeCodePathLI(codeFile);
12135
12136            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12137                resourceFile.delete();
12138            }
12139
12140            return true;
12141        }
12142
12143        void cleanUpResourcesLI() {
12144            // Try enumerating all code paths before deleting
12145            List<String> allCodePaths = Collections.EMPTY_LIST;
12146            if (codeFile != null && codeFile.exists()) {
12147                try {
12148                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12149                    allCodePaths = pkg.getAllCodePaths();
12150                } catch (PackageParserException e) {
12151                    // Ignored; we tried our best
12152                }
12153            }
12154
12155            cleanUp();
12156            removeDexFiles(allCodePaths, instructionSets);
12157        }
12158
12159        boolean doPostDeleteLI(boolean delete) {
12160            // XXX err, shouldn't we respect the delete flag?
12161            cleanUpResourcesLI();
12162            return true;
12163        }
12164    }
12165
12166    private boolean isAsecExternal(String cid) {
12167        final String asecPath = PackageHelper.getSdFilesystem(cid);
12168        return !asecPath.startsWith(mAsecInternalPath);
12169    }
12170
12171    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12172            PackageManagerException {
12173        if (copyRet < 0) {
12174            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12175                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12176                throw new PackageManagerException(copyRet, message);
12177            }
12178        }
12179    }
12180
12181    /**
12182     * Extract the MountService "container ID" from the full code path of an
12183     * .apk.
12184     */
12185    static String cidFromCodePath(String fullCodePath) {
12186        int eidx = fullCodePath.lastIndexOf("/");
12187        String subStr1 = fullCodePath.substring(0, eidx);
12188        int sidx = subStr1.lastIndexOf("/");
12189        return subStr1.substring(sidx+1, eidx);
12190    }
12191
12192    /**
12193     * Logic to handle installation of ASEC applications, including copying and
12194     * renaming logic.
12195     */
12196    class AsecInstallArgs extends InstallArgs {
12197        static final String RES_FILE_NAME = "pkg.apk";
12198        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12199
12200        String cid;
12201        String packagePath;
12202        String resourcePath;
12203
12204        /** New install */
12205        AsecInstallArgs(InstallParams params) {
12206            super(params.origin, params.move, params.observer, params.installFlags,
12207                    params.installerPackageName, params.volumeUuid,
12208                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12209                    params.grantedRuntimePermissions,
12210                    params.traceMethod, params.traceCookie);
12211        }
12212
12213        /** Existing install */
12214        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12215                        boolean isExternal, boolean isForwardLocked) {
12216            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12217                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12218                    instructionSets, null, null, null, 0);
12219            // Hackily pretend we're still looking at a full code path
12220            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12221                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12222            }
12223
12224            // Extract cid from fullCodePath
12225            int eidx = fullCodePath.lastIndexOf("/");
12226            String subStr1 = fullCodePath.substring(0, eidx);
12227            int sidx = subStr1.lastIndexOf("/");
12228            cid = subStr1.substring(sidx+1, eidx);
12229            setMountPath(subStr1);
12230        }
12231
12232        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12233            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12234                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12235                    instructionSets, null, null, null, 0);
12236            this.cid = cid;
12237            setMountPath(PackageHelper.getSdDir(cid));
12238        }
12239
12240        void createCopyFile() {
12241            cid = mInstallerService.allocateExternalStageCidLegacy();
12242        }
12243
12244        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12245            if (origin.staged && origin.cid != null) {
12246                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12247                cid = origin.cid;
12248                setMountPath(PackageHelper.getSdDir(cid));
12249                return PackageManager.INSTALL_SUCCEEDED;
12250            }
12251
12252            if (temp) {
12253                createCopyFile();
12254            } else {
12255                /*
12256                 * Pre-emptively destroy the container since it's destroyed if
12257                 * copying fails due to it existing anyway.
12258                 */
12259                PackageHelper.destroySdDir(cid);
12260            }
12261
12262            final String newMountPath = imcs.copyPackageToContainer(
12263                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12264                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12265
12266            if (newMountPath != null) {
12267                setMountPath(newMountPath);
12268                return PackageManager.INSTALL_SUCCEEDED;
12269            } else {
12270                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12271            }
12272        }
12273
12274        @Override
12275        String getCodePath() {
12276            return packagePath;
12277        }
12278
12279        @Override
12280        String getResourcePath() {
12281            return resourcePath;
12282        }
12283
12284        int doPreInstall(int status) {
12285            if (status != PackageManager.INSTALL_SUCCEEDED) {
12286                // Destroy container
12287                PackageHelper.destroySdDir(cid);
12288            } else {
12289                boolean mounted = PackageHelper.isContainerMounted(cid);
12290                if (!mounted) {
12291                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12292                            Process.SYSTEM_UID);
12293                    if (newMountPath != null) {
12294                        setMountPath(newMountPath);
12295                    } else {
12296                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12297                    }
12298                }
12299            }
12300            return status;
12301        }
12302
12303        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12304            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12305            String newMountPath = null;
12306            if (PackageHelper.isContainerMounted(cid)) {
12307                // Unmount the container
12308                if (!PackageHelper.unMountSdDir(cid)) {
12309                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12310                    return false;
12311                }
12312            }
12313            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12314                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12315                        " which might be stale. Will try to clean up.");
12316                // Clean up the stale container and proceed to recreate.
12317                if (!PackageHelper.destroySdDir(newCacheId)) {
12318                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12319                    return false;
12320                }
12321                // Successfully cleaned up stale container. Try to rename again.
12322                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12323                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12324                            + " inspite of cleaning it up.");
12325                    return false;
12326                }
12327            }
12328            if (!PackageHelper.isContainerMounted(newCacheId)) {
12329                Slog.w(TAG, "Mounting container " + newCacheId);
12330                newMountPath = PackageHelper.mountSdDir(newCacheId,
12331                        getEncryptKey(), Process.SYSTEM_UID);
12332            } else {
12333                newMountPath = PackageHelper.getSdDir(newCacheId);
12334            }
12335            if (newMountPath == null) {
12336                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12337                return false;
12338            }
12339            Log.i(TAG, "Succesfully renamed " + cid +
12340                    " to " + newCacheId +
12341                    " at new path: " + newMountPath);
12342            cid = newCacheId;
12343
12344            final File beforeCodeFile = new File(packagePath);
12345            setMountPath(newMountPath);
12346            final File afterCodeFile = new File(packagePath);
12347
12348            // Reflect the rename in scanned details
12349            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12350            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12351                    afterCodeFile, pkg.baseCodePath));
12352            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12353                    afterCodeFile, pkg.splitCodePaths));
12354
12355            // Reflect the rename in app info
12356            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12357            pkg.setApplicationInfoCodePath(pkg.codePath);
12358            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12359            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12360            pkg.setApplicationInfoResourcePath(pkg.codePath);
12361            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12362            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12363
12364            return true;
12365        }
12366
12367        private void setMountPath(String mountPath) {
12368            final File mountFile = new File(mountPath);
12369
12370            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12371            if (monolithicFile.exists()) {
12372                packagePath = monolithicFile.getAbsolutePath();
12373                if (isFwdLocked()) {
12374                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12375                } else {
12376                    resourcePath = packagePath;
12377                }
12378            } else {
12379                packagePath = mountFile.getAbsolutePath();
12380                resourcePath = packagePath;
12381            }
12382        }
12383
12384        int doPostInstall(int status, int uid) {
12385            if (status != PackageManager.INSTALL_SUCCEEDED) {
12386                cleanUp();
12387            } else {
12388                final int groupOwner;
12389                final String protectedFile;
12390                if (isFwdLocked()) {
12391                    groupOwner = UserHandle.getSharedAppGid(uid);
12392                    protectedFile = RES_FILE_NAME;
12393                } else {
12394                    groupOwner = -1;
12395                    protectedFile = null;
12396                }
12397
12398                if (uid < Process.FIRST_APPLICATION_UID
12399                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12400                    Slog.e(TAG, "Failed to finalize " + cid);
12401                    PackageHelper.destroySdDir(cid);
12402                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12403                }
12404
12405                boolean mounted = PackageHelper.isContainerMounted(cid);
12406                if (!mounted) {
12407                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12408                }
12409            }
12410            return status;
12411        }
12412
12413        private void cleanUp() {
12414            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12415
12416            // Destroy secure container
12417            PackageHelper.destroySdDir(cid);
12418        }
12419
12420        private List<String> getAllCodePaths() {
12421            final File codeFile = new File(getCodePath());
12422            if (codeFile != null && codeFile.exists()) {
12423                try {
12424                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12425                    return pkg.getAllCodePaths();
12426                } catch (PackageParserException e) {
12427                    // Ignored; we tried our best
12428                }
12429            }
12430            return Collections.EMPTY_LIST;
12431        }
12432
12433        void cleanUpResourcesLI() {
12434            // Enumerate all code paths before deleting
12435            cleanUpResourcesLI(getAllCodePaths());
12436        }
12437
12438        private void cleanUpResourcesLI(List<String> allCodePaths) {
12439            cleanUp();
12440            removeDexFiles(allCodePaths, instructionSets);
12441        }
12442
12443        String getPackageName() {
12444            return getAsecPackageName(cid);
12445        }
12446
12447        boolean doPostDeleteLI(boolean delete) {
12448            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12449            final List<String> allCodePaths = getAllCodePaths();
12450            boolean mounted = PackageHelper.isContainerMounted(cid);
12451            if (mounted) {
12452                // Unmount first
12453                if (PackageHelper.unMountSdDir(cid)) {
12454                    mounted = false;
12455                }
12456            }
12457            if (!mounted && delete) {
12458                cleanUpResourcesLI(allCodePaths);
12459            }
12460            return !mounted;
12461        }
12462
12463        @Override
12464        int doPreCopy() {
12465            if (isFwdLocked()) {
12466                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12467                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12468                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12469                }
12470            }
12471
12472            return PackageManager.INSTALL_SUCCEEDED;
12473        }
12474
12475        @Override
12476        int doPostCopy(int uid) {
12477            if (isFwdLocked()) {
12478                if (uid < Process.FIRST_APPLICATION_UID
12479                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12480                                RES_FILE_NAME)) {
12481                    Slog.e(TAG, "Failed to finalize " + cid);
12482                    PackageHelper.destroySdDir(cid);
12483                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12484                }
12485            }
12486
12487            return PackageManager.INSTALL_SUCCEEDED;
12488        }
12489    }
12490
12491    /**
12492     * Logic to handle movement of existing installed applications.
12493     */
12494    class MoveInstallArgs extends InstallArgs {
12495        private File codeFile;
12496        private File resourceFile;
12497
12498        /** New install */
12499        MoveInstallArgs(InstallParams params) {
12500            super(params.origin, params.move, params.observer, params.installFlags,
12501                    params.installerPackageName, params.volumeUuid,
12502                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12503                    params.grantedRuntimePermissions,
12504                    params.traceMethod, params.traceCookie);
12505        }
12506
12507        int copyApk(IMediaContainerService imcs, boolean temp) {
12508            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12509                    + move.fromUuid + " to " + move.toUuid);
12510            synchronized (mInstaller) {
12511                try {
12512                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12513                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12514                } catch (InstallerException e) {
12515                    Slog.w(TAG, "Failed to move app", e);
12516                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12517                }
12518            }
12519
12520            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12521            resourceFile = codeFile;
12522            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12523
12524            return PackageManager.INSTALL_SUCCEEDED;
12525        }
12526
12527        int doPreInstall(int status) {
12528            if (status != PackageManager.INSTALL_SUCCEEDED) {
12529                cleanUp(move.toUuid);
12530            }
12531            return status;
12532        }
12533
12534        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12535            if (status != PackageManager.INSTALL_SUCCEEDED) {
12536                cleanUp(move.toUuid);
12537                return false;
12538            }
12539
12540            // Reflect the move in app info
12541            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12542            pkg.setApplicationInfoCodePath(pkg.codePath);
12543            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12544            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12545            pkg.setApplicationInfoResourcePath(pkg.codePath);
12546            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12547            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12548
12549            return true;
12550        }
12551
12552        int doPostInstall(int status, int uid) {
12553            if (status == PackageManager.INSTALL_SUCCEEDED) {
12554                cleanUp(move.fromUuid);
12555            } else {
12556                cleanUp(move.toUuid);
12557            }
12558            return status;
12559        }
12560
12561        @Override
12562        String getCodePath() {
12563            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12564        }
12565
12566        @Override
12567        String getResourcePath() {
12568            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12569        }
12570
12571        private boolean cleanUp(String volumeUuid) {
12572            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12573                    move.dataAppName);
12574            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12575            synchronized (mInstallLock) {
12576                // Clean up both app data and code
12577                removeDataDirsLI(volumeUuid, move.packageName);
12578                removeCodePathLI(codeFile);
12579            }
12580            return true;
12581        }
12582
12583        void cleanUpResourcesLI() {
12584            throw new UnsupportedOperationException();
12585        }
12586
12587        boolean doPostDeleteLI(boolean delete) {
12588            throw new UnsupportedOperationException();
12589        }
12590    }
12591
12592    static String getAsecPackageName(String packageCid) {
12593        int idx = packageCid.lastIndexOf("-");
12594        if (idx == -1) {
12595            return packageCid;
12596        }
12597        return packageCid.substring(0, idx);
12598    }
12599
12600    // Utility method used to create code paths based on package name and available index.
12601    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12602        String idxStr = "";
12603        int idx = 1;
12604        // Fall back to default value of idx=1 if prefix is not
12605        // part of oldCodePath
12606        if (oldCodePath != null) {
12607            String subStr = oldCodePath;
12608            // Drop the suffix right away
12609            if (suffix != null && subStr.endsWith(suffix)) {
12610                subStr = subStr.substring(0, subStr.length() - suffix.length());
12611            }
12612            // If oldCodePath already contains prefix find out the
12613            // ending index to either increment or decrement.
12614            int sidx = subStr.lastIndexOf(prefix);
12615            if (sidx != -1) {
12616                subStr = subStr.substring(sidx + prefix.length());
12617                if (subStr != null) {
12618                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12619                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12620                    }
12621                    try {
12622                        idx = Integer.parseInt(subStr);
12623                        if (idx <= 1) {
12624                            idx++;
12625                        } else {
12626                            idx--;
12627                        }
12628                    } catch(NumberFormatException e) {
12629                    }
12630                }
12631            }
12632        }
12633        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12634        return prefix + idxStr;
12635    }
12636
12637    private File getNextCodePath(File targetDir, String packageName) {
12638        int suffix = 1;
12639        File result;
12640        do {
12641            result = new File(targetDir, packageName + "-" + suffix);
12642            suffix++;
12643        } while (result.exists());
12644        return result;
12645    }
12646
12647    // Utility method that returns the relative package path with respect
12648    // to the installation directory. Like say for /data/data/com.test-1.apk
12649    // string com.test-1 is returned.
12650    static String deriveCodePathName(String codePath) {
12651        if (codePath == null) {
12652            return null;
12653        }
12654        final File codeFile = new File(codePath);
12655        final String name = codeFile.getName();
12656        if (codeFile.isDirectory()) {
12657            return name;
12658        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12659            final int lastDot = name.lastIndexOf('.');
12660            return name.substring(0, lastDot);
12661        } else {
12662            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12663            return null;
12664        }
12665    }
12666
12667    static class PackageInstalledInfo {
12668        String name;
12669        int uid;
12670        // The set of users that originally had this package installed.
12671        int[] origUsers;
12672        // The set of users that now have this package installed.
12673        int[] newUsers;
12674        PackageParser.Package pkg;
12675        int returnCode;
12676        String returnMsg;
12677        PackageRemovedInfo removedInfo;
12678
12679        public void setError(int code, String msg) {
12680            returnCode = code;
12681            returnMsg = msg;
12682            Slog.w(TAG, msg);
12683        }
12684
12685        public void setError(String msg, PackageParserException e) {
12686            returnCode = e.error;
12687            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12688            Slog.w(TAG, msg, e);
12689        }
12690
12691        public void setError(String msg, PackageManagerException e) {
12692            returnCode = e.error;
12693            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12694            Slog.w(TAG, msg, e);
12695        }
12696
12697        // In some error cases we want to convey more info back to the observer
12698        String origPackage;
12699        String origPermission;
12700    }
12701
12702    /*
12703     * Install a non-existing package.
12704     */
12705    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12706            UserHandle user, String installerPackageName, String volumeUuid,
12707            PackageInstalledInfo res) {
12708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12709
12710        // Remember this for later, in case we need to rollback this install
12711        String pkgName = pkg.packageName;
12712
12713        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12714        // TODO: b/23350563
12715        final boolean dataDirExists = Environment
12716                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12717
12718        synchronized(mPackages) {
12719            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12720                // A package with the same name is already installed, though
12721                // it has been renamed to an older name.  The package we
12722                // are trying to install should be installed as an update to
12723                // the existing one, but that has not been requested, so bail.
12724                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12725                        + " without first uninstalling package running as "
12726                        + mSettings.mRenamedPackages.get(pkgName));
12727                return;
12728            }
12729            if (mPackages.containsKey(pkgName)) {
12730                // Don't allow installation over an existing package with the same name.
12731                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12732                        + " without first uninstalling.");
12733                return;
12734            }
12735        }
12736
12737        try {
12738            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12739                    System.currentTimeMillis(), user);
12740
12741            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
12742            prepareAppDataAfterInstall(newPackage);
12743
12744            // delete the partially installed application. the data directory will have to be
12745            // restored if it was already existing
12746            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12747                // remove package from internal structures.  Note that we want deletePackageX to
12748                // delete the package data and cache directories that it created in
12749                // scanPackageLocked, unless those directories existed before we even tried to
12750                // install.
12751                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12752                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12753                                res.removedInfo, true, null);
12754            }
12755
12756        } catch (PackageManagerException e) {
12757            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12758        }
12759
12760        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12761    }
12762
12763    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12764        // Can't rotate keys during boot or if sharedUser.
12765        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12766                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12767            return false;
12768        }
12769        // app is using upgradeKeySets; make sure all are valid
12770        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12771        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12772        for (int i = 0; i < upgradeKeySets.length; i++) {
12773            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12774                Slog.wtf(TAG, "Package "
12775                         + (oldPs.name != null ? oldPs.name : "<null>")
12776                         + " contains upgrade-key-set reference to unknown key-set: "
12777                         + upgradeKeySets[i]
12778                         + " reverting to signatures check.");
12779                return false;
12780            }
12781        }
12782        return true;
12783    }
12784
12785    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12786        // Upgrade keysets are being used.  Determine if new package has a superset of the
12787        // required keys.
12788        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12789        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12790        for (int i = 0; i < upgradeKeySets.length; i++) {
12791            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12792            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12793                return true;
12794            }
12795        }
12796        return false;
12797    }
12798
12799    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12800            UserHandle user, String installerPackageName, String volumeUuid,
12801            PackageInstalledInfo res) {
12802        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12803
12804        final PackageParser.Package oldPackage;
12805        final String pkgName = pkg.packageName;
12806        final int[] allUsers;
12807        final boolean[] perUserInstalled;
12808
12809        // First find the old package info and check signatures
12810        synchronized(mPackages) {
12811            oldPackage = mPackages.get(pkgName);
12812            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12813            if (isEphemeral && !oldIsEphemeral) {
12814                // can't downgrade from full to ephemeral
12815                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12816                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12817                return;
12818            }
12819            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12820            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12821            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12822                if (!checkUpgradeKeySetLP(ps, pkg)) {
12823                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12824                            "New package not signed by keys specified by upgrade-keysets: "
12825                                    + pkgName);
12826                    return;
12827                }
12828            } else {
12829                // default to original signature matching
12830                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12831                        != PackageManager.SIGNATURE_MATCH) {
12832                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12833                            "New package has a different signature: " + pkgName);
12834                    return;
12835                }
12836            }
12837
12838            // In case of rollback, remember per-user/profile install state
12839            allUsers = sUserManager.getUserIds();
12840            perUserInstalled = new boolean[allUsers.length];
12841            for (int i = 0; i < allUsers.length; i++) {
12842                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12843            }
12844        }
12845
12846        boolean sysPkg = (isSystemApp(oldPackage));
12847        if (sysPkg) {
12848            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12849                    user, allUsers, perUserInstalled, installerPackageName, res);
12850        } else {
12851            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12852                    user, allUsers, perUserInstalled, installerPackageName, res);
12853        }
12854    }
12855
12856    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12857            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12858            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12859            PackageInstalledInfo res) {
12860        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12861                + deletedPackage);
12862
12863        String pkgName = deletedPackage.packageName;
12864        boolean deletedPkg = true;
12865        boolean addedPkg = false;
12866
12867        final long origUpdateTime = (pkg.mExtras != null)
12868                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
12869
12870        // First delete the existing package while retaining the data directory
12871        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12872                res.removedInfo, true, pkg)) {
12873            // If the existing package wasn't successfully deleted
12874            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12875            deletedPkg = false;
12876        } else {
12877            // Successfully deleted the old package; proceed with replace.
12878
12879            // If deleted package lived in a container, give users a chance to
12880            // relinquish resources before killing.
12881            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12882                if (DEBUG_INSTALL) {
12883                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12884                }
12885                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12886                final ArrayList<String> pkgList = new ArrayList<String>(1);
12887                pkgList.add(deletedPackage.applicationInfo.packageName);
12888                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12889            }
12890
12891            deleteCodeCacheDirsLI(pkg);
12892
12893            try {
12894                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12895                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12896                updateSettingsLI(newPackage, installerPackageName, allUsers,
12897                        perUserInstalled, res, user);
12898                prepareAppDataAfterInstall(newPackage);
12899                addedPkg = true;
12900            } catch (PackageManagerException e) {
12901                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12902            }
12903        }
12904
12905        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12906            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12907
12908            // Revert all internal state mutations and added folders for the failed install
12909            if (addedPkg) {
12910                deletePackageLI(pkgName, null, true, allUsers, perUserInstalled,
12911                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12912            }
12913
12914            // Restore the old package
12915            if (deletedPkg) {
12916                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12917                File restoreFile = new File(deletedPackage.codePath);
12918                // Parse old package
12919                boolean oldExternal = isExternal(deletedPackage);
12920                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12921                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12922                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12923                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12924                try {
12925                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12926                            null);
12927                } catch (PackageManagerException e) {
12928                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12929                            + e.getMessage());
12930                    return;
12931                }
12932
12933                synchronized (mPackages) {
12934                    // Ensure the installer package name up to date
12935                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
12936
12937                    // Update permissions for restored package
12938                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
12939
12940                    mSettings.writeLPr();
12941                }
12942
12943                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12944            }
12945        }
12946    }
12947
12948    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12949            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12950            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12951            PackageInstalledInfo res) {
12952        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12953                + ", old=" + deletedPackage);
12954
12955        final boolean disabledSystem;
12956
12957        // Set the system/privileged flags as needed
12958        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12959        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12960                != 0) {
12961            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12962        }
12963
12964        // Kill package processes including services, providers, etc.
12965        killPackage(deletedPackage, "replace sys pkg");
12966
12967        // Report the result for the parent package only
12968        res.removedInfo.uid = deletedPackage.applicationInfo.uid;
12969        res.removedInfo.removedPackage = deletedPackage.packageName;
12970
12971        // Remove existing system package
12972        removePackageSettingLI(deletedPackage, true);
12973
12974        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
12975        if (!disabledSystem) {
12976            // We didn't need to disable the .apk as a current system package,
12977            // which means we are replacing another update that is already
12978            // installed.  We need to make sure to delete the older one's .apk.
12979            res.removedInfo.args = createInstallArgsForExisting(0,
12980                    deletedPackage.applicationInfo.getCodePath(),
12981                    deletedPackage.applicationInfo.getResourcePath(),
12982                    getAppDexInstructionSets(deletedPackage.applicationInfo));
12983        } else {
12984            res.removedInfo.args = null;
12985        }
12986
12987        // Successfully disabled the old package. Now proceed with re-installation
12988        deleteCodeCacheDirsLI(pkg);
12989
12990        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12991        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
12992                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
12993
12994        PackageParser.Package newPackage = null;
12995        try {
12996            // Add the package to the internal data structures
12997            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12998
12999            // Set the update and install times
13000            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13001            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13002                    System.currentTimeMillis());
13003
13004            // Check for shared user id changes
13005            String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage);
13006            if (invalidPackageName != null) {
13007                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13008                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13009                                + " to " + invalidPackageName);
13010            }
13011
13012            // Update the package dynamic state if succeeded
13013            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13014                // Now that the install succeeded make sure we remove data
13015                // directories for any child package the update removed.
13016                final int deletedChildCount = (deletedPackage.childPackages != null)
13017                        ? deletedPackage.childPackages.size() : 0;
13018                final int newChildCount = (newPackage.childPackages != null)
13019                        ? newPackage.childPackages.size() : 0;
13020                for (int i = 0; i < deletedChildCount; i++) {
13021                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13022                    boolean childPackageDeleted = true;
13023                    for (int j = 0; j < newChildCount; j++) {
13024                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13025                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13026                            childPackageDeleted = false;
13027                            break;
13028                        }
13029                    }
13030                    if (childPackageDeleted) {
13031                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13032                                deletedChildPkg.packageName);
13033                        if (ps != null) {
13034                            removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false);
13035                        }
13036                    }
13037                }
13038
13039                updateSettingsLI(newPackage, installerPackageName, allUsers,
13040                        perUserInstalled, res, user);
13041                prepareAppDataAfterInstall(newPackage);
13042            }
13043        } catch (PackageManagerException e) {
13044            res.returnCode = INSTALL_FAILED_INTERNAL_ERROR;
13045            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13046        }
13047
13048        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13049            // Re installation failed. Restore old information
13050            // Remove new pkg information
13051            if (newPackage != null) {
13052                removeInstalledPackageLI(newPackage, true);
13053            }
13054            // Add back the old system package
13055            try {
13056                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13057            } catch (PackageManagerException e) {
13058                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13059            }
13060
13061            synchronized (mPackages) {
13062                if (disabledSystem) {
13063                    enableSystemPackageLPw(deletedPackage);
13064                }
13065
13066                // Ensure the installer package name up to date
13067                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13068
13069                // Update permissions for restored package
13070                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13071
13072                mSettings.writeLPr();
13073            }
13074
13075            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13076                    + " after failed upgrade");
13077        }
13078    }
13079
13080    /**
13081     * Checks whether the parent or any of the child packages have a change shared
13082     * user. For a package to be a valid update the shred users of the parent and
13083     * the children should match. We may later support changing child shared users.
13084     * @param oldPkg The updated package.
13085     * @param newPkg The update package.
13086     * @return The shared user that change between the versions.
13087     */
13088    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13089            PackageParser.Package newPkg) {
13090        // Check parent shared user
13091        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13092            return newPkg.packageName;
13093        }
13094        // Check child shared users
13095        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13096        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13097        for (int i = 0; i < newChildCount; i++) {
13098            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13099            // If this child was present, did it have the same shared user?
13100            for (int j = 0; j < oldChildCount; j++) {
13101                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13102                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13103                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13104                    return newChildPkg.packageName;
13105                }
13106            }
13107        }
13108        return null;
13109    }
13110
13111    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13112        // Remove the lib path for the parent package
13113        PackageSetting ps = (PackageSetting) pkg.mExtras;
13114        if (ps != null) {
13115            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13116        }
13117        // Remove the lib path for the child packages
13118        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13119        for (int i = 0; i < childCount; i++) {
13120            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13121            if (ps != null) {
13122                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13123            }
13124        }
13125    }
13126
13127    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13128        // Enable the parent package
13129        mSettings.enableSystemPackageLPw(pkg.packageName);
13130        // Enable the child packages
13131        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13132        for (int i = 0; i < childCount; i++) {
13133            PackageParser.Package childPkg = pkg.childPackages.get(i);
13134            mSettings.enableSystemPackageLPw(childPkg.packageName);
13135        }
13136    }
13137
13138    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13139            PackageParser.Package newPkg) {
13140        // Disable the parent package (parent always replaced)
13141        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13142        // Disable the child packages
13143        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13144        for (int i = 0; i < childCount; i++) {
13145            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13146            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13147            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13148        }
13149        return disabled;
13150    }
13151
13152    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13153            String installerPackageName) {
13154        // Enable the parent package
13155        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13156        // Enable the child packages
13157        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13158        for (int i = 0; i < childCount; i++) {
13159            PackageParser.Package childPkg = pkg.childPackages.get(i);
13160            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13161        }
13162    }
13163
13164    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13165        // Collect all used permissions in the UID
13166        ArraySet<String> usedPermissions = new ArraySet<>();
13167        final int packageCount = su.packages.size();
13168        for (int i = 0; i < packageCount; i++) {
13169            PackageSetting ps = su.packages.valueAt(i);
13170            if (ps.pkg == null) {
13171                continue;
13172            }
13173            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13174            for (int j = 0; j < requestedPermCount; j++) {
13175                String permission = ps.pkg.requestedPermissions.get(j);
13176                BasePermission bp = mSettings.mPermissions.get(permission);
13177                if (bp != null) {
13178                    usedPermissions.add(permission);
13179                }
13180            }
13181        }
13182
13183        PermissionsState permissionsState = su.getPermissionsState();
13184        // Prune install permissions
13185        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13186        final int installPermCount = installPermStates.size();
13187        for (int i = installPermCount - 1; i >= 0;  i--) {
13188            PermissionState permissionState = installPermStates.get(i);
13189            if (!usedPermissions.contains(permissionState.getName())) {
13190                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13191                if (bp != null) {
13192                    permissionsState.revokeInstallPermission(bp);
13193                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13194                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13195                }
13196            }
13197        }
13198
13199        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13200
13201        // Prune runtime permissions
13202        for (int userId : allUserIds) {
13203            List<PermissionState> runtimePermStates = permissionsState
13204                    .getRuntimePermissionStates(userId);
13205            final int runtimePermCount = runtimePermStates.size();
13206            for (int i = runtimePermCount - 1; i >= 0; i--) {
13207                PermissionState permissionState = runtimePermStates.get(i);
13208                if (!usedPermissions.contains(permissionState.getName())) {
13209                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13210                    if (bp != null) {
13211                        permissionsState.revokeRuntimePermission(bp, userId);
13212                        permissionsState.updatePermissionFlags(bp, userId,
13213                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13214                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13215                                runtimePermissionChangedUserIds, userId);
13216                    }
13217                }
13218            }
13219        }
13220
13221        return runtimePermissionChangedUserIds;
13222    }
13223
13224    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13225            int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) {
13226        // Update the parent package setting
13227        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled,
13228                res, user);
13229        // Update the child packages setting
13230        final int childCount = (newPackage.childPackages != null)
13231                ? newPackage.childPackages.size() : 0;
13232        for (int i = 0; i < childCount; i++) {
13233            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13234            updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled,
13235                    res, user);
13236        }
13237    }
13238
13239    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13240            String installerPackageName, int[] allUsers, boolean[] perUserInstalled,
13241            PackageInstalledInfo res, UserHandle user) {
13242        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13243
13244        String pkgName = newPackage.packageName;
13245        synchronized (mPackages) {
13246            //write settings. the installStatus will be incomplete at this stage.
13247            //note that the new package setting would have already been
13248            //added to mPackages. It hasn't been persisted yet.
13249            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13250            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13251            mSettings.writeLPr();
13252            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13253        }
13254
13255        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13256        synchronized (mPackages) {
13257            updatePermissionsLPw(newPackage.packageName, newPackage,
13258                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13259                            ? UPDATE_PERMISSIONS_ALL : 0));
13260            // For system-bundled packages, we assume that installing an upgraded version
13261            // of the package implies that the user actually wants to run that new code,
13262            // so we enable the package.
13263            PackageSetting ps = mSettings.mPackages.get(pkgName);
13264            if (ps != null) {
13265                if (isSystemApp(newPackage)) {
13266                    // NB: implicit assumption that system package upgrades apply to all users
13267                    if (DEBUG_INSTALL) {
13268                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13269                    }
13270                    if (res.origUsers != null) {
13271                        for (int userHandle : res.origUsers) {
13272                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13273                                    userHandle, installerPackageName);
13274                        }
13275                    }
13276                    // Also convey the prior install/uninstall state
13277                    if (allUsers != null && perUserInstalled != null) {
13278                        for (int i = 0; i < allUsers.length; i++) {
13279                            if (DEBUG_INSTALL) {
13280                                Slog.d(TAG, "    user " + allUsers[i]
13281                                        + " => " + perUserInstalled[i]);
13282                            }
13283                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
13284                        }
13285                        // these install state changes will be persisted in the
13286                        // upcoming call to mSettings.writeLPr().
13287                    }
13288                }
13289                // It's implied that when a user requests installation, they want the app to be
13290                // installed and enabled.
13291                int userId = user.getIdentifier();
13292                if (userId != UserHandle.USER_ALL) {
13293                    ps.setInstalled(true, userId);
13294                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13295                }
13296            }
13297            res.name = pkgName;
13298            res.uid = newPackage.applicationInfo.uid;
13299            res.pkg = newPackage;
13300            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13301            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13302            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13303            //to update install status
13304            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13305            mSettings.writeLPr();
13306            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13307        }
13308
13309        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13310    }
13311
13312    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13313        try {
13314            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13315            installPackageLI(args, res);
13316        } finally {
13317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13318        }
13319    }
13320
13321    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13322        final int installFlags = args.installFlags;
13323        final String installerPackageName = args.installerPackageName;
13324        final String volumeUuid = args.volumeUuid;
13325        final File tmpPackageFile = new File(args.getCodePath());
13326        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13327        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13328                || (args.volumeUuid != null));
13329        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13330        boolean replace = false;
13331        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13332        if (args.move != null) {
13333            // moving a complete application; perfom an initial scan on the new install location
13334            scanFlags |= SCAN_INITIAL;
13335        }
13336        // Result object to be returned
13337        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13338
13339        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13340
13341        // Sanity check
13342        if (ephemeral && (forwardLocked || onExternal)) {
13343            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13344                    + " external=" + onExternal);
13345            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
13346            return;
13347        }
13348
13349        // Retrieve PackageSettings and parse package
13350        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13351                | PackageParser.PARSE_ENFORCE_CODE
13352                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13353                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13354                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13355        PackageParser pp = new PackageParser();
13356        pp.setSeparateProcesses(mSeparateProcesses);
13357        pp.setDisplayMetrics(mMetrics);
13358
13359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13360        final PackageParser.Package pkg;
13361        try {
13362            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13363        } catch (PackageParserException e) {
13364            res.setError("Failed parse during installPackageLI", e);
13365            return;
13366        } finally {
13367            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13368        }
13369
13370        // If package doesn't declare API override, mark that we have an install
13371        // time CPU ABI override.
13372        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13373            pkg.cpuAbiOverride = args.abiOverride;
13374        }
13375
13376        String pkgName = res.name = pkg.packageName;
13377        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13378            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13379                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13380                return;
13381            }
13382        }
13383
13384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13385        try {
13386            PackageParser.collectCertificates(pkg, parseFlags);
13387        } catch (PackageParserException e) {
13388            res.setError("Failed collect during installPackageLI", e);
13389            return;
13390        } finally {
13391            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13392        }
13393
13394        // Get rid of all references to package scan path via parser.
13395        pp = null;
13396        String oldCodePath = null;
13397        boolean systemApp = false;
13398        synchronized (mPackages) {
13399            // Check if installing already existing package
13400            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13401                String oldName = mSettings.mRenamedPackages.get(pkgName);
13402                if (pkg.mOriginalPackages != null
13403                        && pkg.mOriginalPackages.contains(oldName)
13404                        && mPackages.containsKey(oldName)) {
13405                    // This package is derived from an original package,
13406                    // and this device has been updating from that original
13407                    // name.  We must continue using the original name, so
13408                    // rename the new package here.
13409                    pkg.setPackageName(oldName);
13410                    pkgName = pkg.packageName;
13411                    replace = true;
13412                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13413                            + oldName + " pkgName=" + pkgName);
13414                } else if (mPackages.containsKey(pkgName)) {
13415                    // This package, under its official name, already exists
13416                    // on the device; we should replace it.
13417                    replace = true;
13418                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13419                }
13420
13421                // Child packages are installed through the parent package
13422                if (pkg.parentPackage != null) {
13423                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13424                            "Package " + pkg.packageName + " is child of package "
13425                                    + pkg.parentPackage.parentPackage + ". Child packages "
13426                                    + "can be updated only through the parent package.");
13427                    return;
13428                }
13429
13430                if (replace) {
13431                    // Prevent apps opting out from runtime permissions
13432                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13433                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13434                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13435                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13436                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13437                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13438                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13439                                        + " doesn't support runtime permissions but the old"
13440                                        + " target SDK " + oldTargetSdk + " does.");
13441                        return;
13442                    }
13443
13444                    // Prevent installing of child packages
13445                    if (oldPackage.parentPackage != null) {
13446                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13447                                "Package " + pkg.packageName + " is child of package "
13448                                        + oldPackage.parentPackage + ". Child packages "
13449                                        + "can be updated only through the parent package.");
13450                        return;
13451                    }
13452                }
13453            }
13454
13455            PackageSetting ps = mSettings.mPackages.get(pkgName);
13456            if (ps != null) {
13457                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13458
13459                // Quick sanity check that we're signed correctly if updating;
13460                // we'll check this again later when scanning, but we want to
13461                // bail early here before tripping over redefined permissions.
13462                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13463                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13464                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13465                                + pkg.packageName + " upgrade keys do not match the "
13466                                + "previously installed version");
13467                        return;
13468                    }
13469                } else {
13470                    try {
13471                        verifySignaturesLP(ps, pkg);
13472                    } catch (PackageManagerException e) {
13473                        res.setError(e.error, e.getMessage());
13474                        return;
13475                    }
13476                }
13477
13478                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13479                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13480                    systemApp = (ps.pkg.applicationInfo.flags &
13481                            ApplicationInfo.FLAG_SYSTEM) != 0;
13482                }
13483                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13484            }
13485
13486            // Check whether the newly-scanned package wants to define an already-defined perm
13487            int N = pkg.permissions.size();
13488            for (int i = N-1; i >= 0; i--) {
13489                PackageParser.Permission perm = pkg.permissions.get(i);
13490                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13491                if (bp != null) {
13492                    // If the defining package is signed with our cert, it's okay.  This
13493                    // also includes the "updating the same package" case, of course.
13494                    // "updating same package" could also involve key-rotation.
13495                    final boolean sigsOk;
13496                    if (bp.sourcePackage.equals(pkg.packageName)
13497                            && (bp.packageSetting instanceof PackageSetting)
13498                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13499                                    scanFlags))) {
13500                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13501                    } else {
13502                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13503                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13504                    }
13505                    if (!sigsOk) {
13506                        // If the owning package is the system itself, we log but allow
13507                        // install to proceed; we fail the install on all other permission
13508                        // redefinitions.
13509                        if (!bp.sourcePackage.equals("android")) {
13510                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13511                                    + pkg.packageName + " attempting to redeclare permission "
13512                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13513                            res.origPermission = perm.info.name;
13514                            res.origPackage = bp.sourcePackage;
13515                            return;
13516                        } else {
13517                            Slog.w(TAG, "Package " + pkg.packageName
13518                                    + " attempting to redeclare system permission "
13519                                    + perm.info.name + "; ignoring new declaration");
13520                            pkg.permissions.remove(i);
13521                        }
13522                    }
13523                }
13524            }
13525        }
13526
13527        if (systemApp) {
13528            if (onExternal) {
13529                // Abort update; system app can't be replaced with app on sdcard
13530                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13531                        "Cannot install updates to system apps on sdcard");
13532                return;
13533            } else if (ephemeral) {
13534                // Abort update; system app can't be replaced with an ephemeral app
13535                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13536                        "Cannot update a system app with an ephemeral app");
13537                return;
13538            }
13539        }
13540
13541        if (args.move != null) {
13542            // We did an in-place move, so dex is ready to roll
13543            scanFlags |= SCAN_NO_DEX;
13544            scanFlags |= SCAN_MOVE;
13545
13546            synchronized (mPackages) {
13547                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13548                if (ps == null) {
13549                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13550                            "Missing settings for moved package " + pkgName);
13551                }
13552
13553                // We moved the entire application as-is, so bring over the
13554                // previously derived ABI information.
13555                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13556                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13557            }
13558
13559        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13560            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13561            scanFlags |= SCAN_NO_DEX;
13562
13563            try {
13564                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13565                    args.abiOverride : pkg.cpuAbiOverride);
13566                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13567                        true /* extract libs */);
13568            } catch (PackageManagerException pme) {
13569                Slog.e(TAG, "Error deriving application ABI", pme);
13570                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13571                return;
13572            }
13573
13574            // Extract package to save the VM unzipping the APK in memory during
13575            // launch. Only do this if profile-guided compilation is enabled because
13576            // otherwise BackgroundDexOptService will not dexopt the package later.
13577            if (mUseJitProfiles) {
13578                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13579                // Do not run PackageDexOptimizer through the local performDexOpt
13580                // method because `pkg` is not in `mPackages` yet.
13581                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13582                        false /* useProfiles */, true /* extractOnly */);
13583                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13584                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13585                    String msg = "Extracking package failed for " + pkgName;
13586                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13587                    return;
13588                }
13589            }
13590        }
13591
13592        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13593            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13594            return;
13595        }
13596
13597        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13598
13599        if (replace) {
13600            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13601                    installerPackageName, volumeUuid, res);
13602        } else {
13603            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13604                    args.user, installerPackageName, volumeUuid, res);
13605        }
13606        synchronized (mPackages) {
13607            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13608            if (ps != null) {
13609                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13610            }
13611        }
13612    }
13613
13614    private void startIntentFilterVerifications(int userId, boolean replacing,
13615            PackageParser.Package pkg) {
13616        if (mIntentFilterVerifierComponent == null) {
13617            Slog.w(TAG, "No IntentFilter verification will not be done as "
13618                    + "there is no IntentFilterVerifier available!");
13619            return;
13620        }
13621
13622        final int verifierUid = getPackageUid(
13623                mIntentFilterVerifierComponent.getPackageName(),
13624                MATCH_DEBUG_TRIAGED_MISSING,
13625                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13626
13627        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13628        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13629        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13630        mHandler.sendMessage(msg);
13631    }
13632
13633    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13634            PackageParser.Package pkg) {
13635        int size = pkg.activities.size();
13636        if (size == 0) {
13637            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13638                    "No activity, so no need to verify any IntentFilter!");
13639            return;
13640        }
13641
13642        final boolean hasDomainURLs = hasDomainURLs(pkg);
13643        if (!hasDomainURLs) {
13644            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13645                    "No domain URLs, so no need to verify any IntentFilter!");
13646            return;
13647        }
13648
13649        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13650                + " if any IntentFilter from the " + size
13651                + " Activities needs verification ...");
13652
13653        int count = 0;
13654        final String packageName = pkg.packageName;
13655
13656        synchronized (mPackages) {
13657            // If this is a new install and we see that we've already run verification for this
13658            // package, we have nothing to do: it means the state was restored from backup.
13659            if (!replacing) {
13660                IntentFilterVerificationInfo ivi =
13661                        mSettings.getIntentFilterVerificationLPr(packageName);
13662                if (ivi != null) {
13663                    if (DEBUG_DOMAIN_VERIFICATION) {
13664                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13665                                + ivi.getStatusString());
13666                    }
13667                    return;
13668                }
13669            }
13670
13671            // If any filters need to be verified, then all need to be.
13672            boolean needToVerify = false;
13673            for (PackageParser.Activity a : pkg.activities) {
13674                for (ActivityIntentInfo filter : a.intents) {
13675                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13676                        if (DEBUG_DOMAIN_VERIFICATION) {
13677                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13678                        }
13679                        needToVerify = true;
13680                        break;
13681                    }
13682                }
13683            }
13684
13685            if (needToVerify) {
13686                final int verificationId = mIntentFilterVerificationToken++;
13687                for (PackageParser.Activity a : pkg.activities) {
13688                    for (ActivityIntentInfo filter : a.intents) {
13689                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13690                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13691                                    "Verification needed for IntentFilter:" + filter.toString());
13692                            mIntentFilterVerifier.addOneIntentFilterVerification(
13693                                    verifierUid, userId, verificationId, filter, packageName);
13694                            count++;
13695                        }
13696                    }
13697                }
13698            }
13699        }
13700
13701        if (count > 0) {
13702            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13703                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13704                    +  " for userId:" + userId);
13705            mIntentFilterVerifier.startVerifications(userId);
13706        } else {
13707            if (DEBUG_DOMAIN_VERIFICATION) {
13708                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13709            }
13710        }
13711    }
13712
13713    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13714        final ComponentName cn  = filter.activity.getComponentName();
13715        final String packageName = cn.getPackageName();
13716
13717        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13718                packageName);
13719        if (ivi == null) {
13720            return true;
13721        }
13722        int status = ivi.getStatus();
13723        switch (status) {
13724            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13725            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13726                return true;
13727
13728            default:
13729                // Nothing to do
13730                return false;
13731        }
13732    }
13733
13734    private static boolean isMultiArch(ApplicationInfo info) {
13735        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13736    }
13737
13738    private static boolean isExternal(PackageParser.Package pkg) {
13739        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13740    }
13741
13742    private static boolean isExternal(PackageSetting ps) {
13743        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13744    }
13745
13746    private static boolean isEphemeral(PackageParser.Package pkg) {
13747        return pkg.applicationInfo.isEphemeralApp();
13748    }
13749
13750    private static boolean isEphemeral(PackageSetting ps) {
13751        return ps.pkg != null && isEphemeral(ps.pkg);
13752    }
13753
13754    private static boolean isSystemApp(PackageParser.Package pkg) {
13755        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13756    }
13757
13758    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13759        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13760    }
13761
13762    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13763        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13764    }
13765
13766    private static boolean isSystemApp(PackageSetting ps) {
13767        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13768    }
13769
13770    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13771        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13772    }
13773
13774    private int packageFlagsToInstallFlags(PackageSetting ps) {
13775        int installFlags = 0;
13776        if (isEphemeral(ps)) {
13777            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13778        }
13779        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13780            // This existing package was an external ASEC install when we have
13781            // the external flag without a UUID
13782            installFlags |= PackageManager.INSTALL_EXTERNAL;
13783        }
13784        if (ps.isForwardLocked()) {
13785            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13786        }
13787        return installFlags;
13788    }
13789
13790    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13791        if (isExternal(pkg)) {
13792            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13793                return StorageManager.UUID_PRIMARY_PHYSICAL;
13794            } else {
13795                return pkg.volumeUuid;
13796            }
13797        } else {
13798            return StorageManager.UUID_PRIVATE_INTERNAL;
13799        }
13800    }
13801
13802    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13803        if (isExternal(pkg)) {
13804            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13805                return mSettings.getExternalVersion();
13806            } else {
13807                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13808            }
13809        } else {
13810            return mSettings.getInternalVersion();
13811        }
13812    }
13813
13814    private void deleteTempPackageFiles() {
13815        final FilenameFilter filter = new FilenameFilter() {
13816            public boolean accept(File dir, String name) {
13817                return name.startsWith("vmdl") && name.endsWith(".tmp");
13818            }
13819        };
13820        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13821            file.delete();
13822        }
13823    }
13824
13825    @Override
13826    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13827            int flags) {
13828        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13829                flags);
13830    }
13831
13832    @Override
13833    public void deletePackage(final String packageName,
13834            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13835        mContext.enforceCallingOrSelfPermission(
13836                android.Manifest.permission.DELETE_PACKAGES, null);
13837        Preconditions.checkNotNull(packageName);
13838        Preconditions.checkNotNull(observer);
13839        final int uid = Binder.getCallingUid();
13840        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13841        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13842        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13843            mContext.enforceCallingOrSelfPermission(
13844                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13845                    "deletePackage for user " + userId);
13846        }
13847
13848        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13849            try {
13850                observer.onPackageDeleted(packageName,
13851                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13852            } catch (RemoteException re) {
13853            }
13854            return;
13855        }
13856
13857        for (int currentUserId : users) {
13858            if (getBlockUninstallForUser(packageName, currentUserId)) {
13859                try {
13860                    observer.onPackageDeleted(packageName,
13861                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13862                } catch (RemoteException re) {
13863                }
13864                return;
13865            }
13866        }
13867
13868        if (DEBUG_REMOVE) {
13869            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13870        }
13871        // Queue up an async operation since the package deletion may take a little while.
13872        mHandler.post(new Runnable() {
13873            public void run() {
13874                mHandler.removeCallbacks(this);
13875                final int returnCode = deletePackageX(packageName, userId, flags);
13876                try {
13877                    observer.onPackageDeleted(packageName, returnCode, null);
13878                } catch (RemoteException e) {
13879                    Log.i(TAG, "Observer no longer exists.");
13880                } //end catch
13881            } //end run
13882        });
13883    }
13884
13885    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13886        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13887                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13888        try {
13889            if (dpm != null) {
13890                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13891                        /* callingUserOnly =*/ false);
13892                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13893                        : deviceOwnerComponentName.getPackageName();
13894                // Does the package contains the device owner?
13895                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13896                // this check is probably not needed, since DO should be registered as a device
13897                // admin on some user too. (Original bug for this: b/17657954)
13898                if (packageName.equals(deviceOwnerPackageName)) {
13899                    return true;
13900                }
13901                // Does it contain a device admin for any user?
13902                int[] users;
13903                if (userId == UserHandle.USER_ALL) {
13904                    users = sUserManager.getUserIds();
13905                } else {
13906                    users = new int[]{userId};
13907                }
13908                for (int i = 0; i < users.length; ++i) {
13909                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13910                        return true;
13911                    }
13912                }
13913            }
13914        } catch (RemoteException e) {
13915        }
13916        return false;
13917    }
13918
13919    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13920        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13921    }
13922
13923    /**
13924     *  This method is an internal method that could be get invoked either
13925     *  to delete an installed package or to clean up a failed installation.
13926     *  After deleting an installed package, a broadcast is sent to notify any
13927     *  listeners that the package has been installed. For cleaning up a failed
13928     *  installation, the broadcast is not necessary since the package's
13929     *  installation wouldn't have sent the initial broadcast either
13930     *  The key steps in deleting a package are
13931     *  deleting the package information in internal structures like mPackages,
13932     *  deleting the packages base directories through installd
13933     *  updating mSettings to reflect current status
13934     *  persisting settings for later use
13935     *  sending a broadcast if necessary
13936     */
13937    private int deletePackageX(String packageName, int userId, int flags) {
13938        final PackageRemovedInfo info = new PackageRemovedInfo();
13939        final boolean res;
13940
13941        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13942                ? UserHandle.ALL : new UserHandle(userId);
13943
13944        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13945            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13946            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13947        }
13948
13949        boolean removedForAllUsers = false;
13950        boolean systemUpdate = false;
13951
13952        PackageParser.Package uninstalledPkg;
13953
13954        // for the uninstall-updates case and restricted profiles, remember the per-
13955        // userhandle installed state
13956        int[] allUsers;
13957        boolean[] perUserInstalled;
13958        synchronized (mPackages) {
13959            uninstalledPkg = mPackages.get(packageName);
13960            PackageSetting ps = mSettings.mPackages.get(packageName);
13961            allUsers = sUserManager.getUserIds();
13962            perUserInstalled = new boolean[allUsers.length];
13963            for (int i = 0; i < allUsers.length; i++) {
13964                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13965            }
13966        }
13967
13968        synchronized (mInstallLock) {
13969            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13970            res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled,
13971                    flags | REMOVE_CHATTY, info, true, null);
13972            systemUpdate = info.isRemovedPackageSystemUpdate;
13973            synchronized (mPackages) {
13974                if (res) {
13975                    if (!systemUpdate && mPackages.get(packageName) == null) {
13976                        removedForAllUsers = true;
13977                    }
13978                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13979                }
13980            }
13981            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13982                    + " removedForAllUsers=" + removedForAllUsers);
13983        }
13984
13985        if (res) {
13986            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13987
13988            // If the removed package was a system update, the old system package
13989            // was re-enabled; we need to broadcast this information
13990            if (systemUpdate) {
13991                Bundle extras = new Bundle(1);
13992                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13993                        ? info.removedAppId : info.uid);
13994                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13995
13996                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13997                        extras, 0, null, null, null);
13998                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13999                        extras, 0, null, null, null);
14000                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14001                        null, 0, packageName, null, null);
14002            }
14003        }
14004        // Force a gc here.
14005        Runtime.getRuntime().gc();
14006        // Delete the resources here after sending the broadcast to let
14007        // other processes clean up before deleting resources.
14008        if (info.args != null) {
14009            synchronized (mInstallLock) {
14010                info.args.doPostDeleteLI(true);
14011            }
14012        }
14013
14014        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14015    }
14016
14017    class PackageRemovedInfo {
14018        String removedPackage;
14019        int uid = -1;
14020        int removedAppId = -1;
14021        int[] removedUsers = null;
14022        boolean isRemovedPackageSystemUpdate = false;
14023        // Clean up resources deleted packages.
14024        InstallArgs args = null;
14025
14026        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
14027            Bundle extras = new Bundle(1);
14028            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14029            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
14030            if (replacing) {
14031                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14032            }
14033            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14034            if (removedPackage != null) {
14035                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14036                        extras, 0, null, null, removedUsers);
14037                if (fullRemove && !replacing) {
14038                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
14039                            extras, 0, null, null, removedUsers);
14040                }
14041            }
14042            if (removedAppId >= 0) {
14043                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14044                        removedUsers);
14045            }
14046        }
14047    }
14048
14049    /*
14050     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14051     * flag is not set, the data directory is removed as well.
14052     * make sure this flag is set for partially installed apps. If not its meaningless to
14053     * delete a partially installed application.
14054     */
14055    private void removePackageDataLI(PackageSetting ps,
14056            int[] allUserHandles, boolean[] perUserInstalled,
14057            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14058        String packageName = ps.name;
14059        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14060        removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0);
14061        // Retrieve object to delete permissions for shared user later on
14062        final PackageSetting deletedPs;
14063        // reader
14064        synchronized (mPackages) {
14065            deletedPs = mSettings.mPackages.get(packageName);
14066            if (outInfo != null) {
14067                outInfo.removedPackage = packageName;
14068                outInfo.removedUsers = deletedPs != null
14069                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14070                        : null;
14071            }
14072        }
14073        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14074            removeDataDirsLI(ps.volumeUuid, packageName);
14075            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14076        }
14077        // writer
14078        synchronized (mPackages) {
14079            if (deletedPs != null) {
14080                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14081                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14082                    clearDefaultBrowserIfNeeded(packageName);
14083                    if (outInfo != null) {
14084                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14085                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14086                    }
14087                    updatePermissionsLPw(deletedPs.name, null, 0);
14088                    if (deletedPs.sharedUser != null) {
14089                        // Remove permissions associated with package. Since runtime
14090                        // permissions are per user we have to kill the removed package
14091                        // or packages running under the shared user of the removed
14092                        // package if revoking the permissions requested only by the removed
14093                        // package is successful and this causes a change in gids.
14094                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14095                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14096                                    userId);
14097                            if (userIdToKill == UserHandle.USER_ALL
14098                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14099                                // If gids changed for this user, kill all affected packages.
14100                                mHandler.post(new Runnable() {
14101                                    @Override
14102                                    public void run() {
14103                                        // This has to happen with no lock held.
14104                                        killApplication(deletedPs.name, deletedPs.appId,
14105                                                KILL_APP_REASON_GIDS_CHANGED);
14106                                    }
14107                                });
14108                                break;
14109                            }
14110                        }
14111                    }
14112                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14113                }
14114                // make sure to preserve per-user disabled state if this removal was just
14115                // a downgrade of a system app to the factory package
14116                if (allUserHandles != null && perUserInstalled != null) {
14117                    if (DEBUG_REMOVE) {
14118                        Slog.d(TAG, "Propagating install state across downgrade");
14119                    }
14120                    for (int i = 0; i < allUserHandles.length; i++) {
14121                        if (DEBUG_REMOVE) {
14122                            Slog.d(TAG, "    user " + allUserHandles[i]
14123                                    + " => " + perUserInstalled[i]);
14124                        }
14125                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14126                    }
14127                }
14128            }
14129            // can downgrade to reader
14130            if (writeSettings) {
14131                // Save settings now
14132                mSettings.writeLPr();
14133            }
14134        }
14135        if (outInfo != null) {
14136            // A user ID was deleted here. Go through all users and remove it
14137            // from KeyStore.
14138            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14139        }
14140    }
14141
14142    static boolean locationIsPrivileged(File path) {
14143        try {
14144            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14145                    .getCanonicalPath();
14146            return path.getCanonicalPath().startsWith(privilegedAppDir);
14147        } catch (IOException e) {
14148            Slog.e(TAG, "Unable to access code path " + path);
14149        }
14150        return false;
14151    }
14152
14153    /*
14154     * Tries to delete system package.
14155     */
14156    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14157            PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled,
14158            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14159            PackageParser.Package replacingPackage) {
14160        if (deletedPkg.parentPackage != null) {
14161            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14162            return false;
14163        }
14164
14165        final boolean applyUserRestrictions
14166                = (allUserHandles != null) && (perUserInstalled != null);
14167        final PackageSetting disabledPs;
14168        // Confirm if the system package has been updated
14169        // An updated system app can be deleted. This will also have to restore
14170        // the system pkg from system partition
14171        // reader
14172        synchronized (mPackages) {
14173            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14174        }
14175
14176        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14177                + " disabledPs=" + disabledPs);
14178
14179        if (disabledPs == null) {
14180            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14181            return false;
14182        } else if (DEBUG_REMOVE) {
14183            Slog.d(TAG, "Deleting system pkg from data partition");
14184        }
14185
14186        if (DEBUG_REMOVE) {
14187            if (applyUserRestrictions) {
14188                Slog.d(TAG, "Remembering install states:");
14189                for (int i = 0; i < allUserHandles.length; i++) {
14190                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
14191                }
14192            }
14193        }
14194
14195        // Delete the updated package
14196        outInfo.isRemovedPackageSystemUpdate = true;
14197        if (disabledPs.versionCode < deletedPs.versionCode) {
14198            // Delete data for downgrades
14199            flags &= ~PackageManager.DELETE_KEEP_DATA;
14200        } else {
14201            // Preserve data by setting flag
14202            flags |= PackageManager.DELETE_KEEP_DATA;
14203        }
14204        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14205                perUserInstalled, outInfo, writeSettings, replacingPackage);
14206        if (!ret) {
14207            return false;
14208        }
14209
14210        // writer
14211        synchronized (mPackages) {
14212            // Reinstate the old system package
14213            enableSystemPackageLPw(disabledPs.pkg);
14214            // Remove any native libraries from the upgraded package.
14215            removeNativeBinariesLI(deletedPkg);
14216        }
14217
14218        // Install the system package
14219        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14220        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14221        if (locationIsPrivileged(disabledPs.codePath)) {
14222            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14223        }
14224
14225        final PackageParser.Package newPkg;
14226        try {
14227            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14228        } catch (PackageManagerException e) {
14229            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14230                    + e.getMessage());
14231            return false;
14232        }
14233
14234        prepareAppDataAfterInstall(newPkg);
14235
14236        // writer
14237        synchronized (mPackages) {
14238            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14239
14240            // Propagate the permissions state as we do not want to drop on the floor
14241            // runtime permissions. The update permissions method below will take
14242            // care of removing obsolete permissions and grant install permissions.
14243            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14244            updatePermissionsLPw(newPkg.packageName, newPkg,
14245                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14246
14247            if (applyUserRestrictions) {
14248                if (DEBUG_REMOVE) {
14249                    Slog.d(TAG, "Propagating install state across reinstall");
14250                }
14251                for (int i = 0; i < allUserHandles.length; i++) {
14252                    if (DEBUG_REMOVE) {
14253                        Slog.d(TAG, "    user " + allUserHandles[i]
14254                                + " => " + perUserInstalled[i]);
14255                    }
14256                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14257
14258                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
14259                }
14260                // Regardless of writeSettings we need to ensure that this restriction
14261                // state propagation is persisted
14262                mSettings.writeAllUsersPackageRestrictionsLPr();
14263            }
14264            // can downgrade to reader here
14265            if (writeSettings) {
14266                mSettings.writeLPr();
14267            }
14268        }
14269        return true;
14270    }
14271
14272    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14273            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14274            boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings,
14275            PackageParser.Package replacingPackage) {
14276        PackageSetting ps = null;
14277
14278        synchronized (mPackages) {
14279            pkg = mPackages.get(pkg.packageName);
14280            if (pkg == null) {
14281                return false;
14282            }
14283
14284            ps = mSettings.mPackages.get(pkg.packageName);
14285            if (ps == null) {
14286                return false;
14287            }
14288
14289            if (outInfo != null) {
14290                outInfo.uid = ps.appId;
14291            }
14292        }
14293
14294        // Delete package data from internal structures and also remove data if flag is set
14295        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags,
14296                    writeSettings);
14297
14298        // Delete the child packages data
14299        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14300        for (int i = 0; i < childCount; i++) {
14301            PackageSetting childPs;
14302            synchronized (mPackages) {
14303                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14304            }
14305            if (childPs != null) {
14306                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14307                        && (replacingPackage != null
14308                        && !replacingPackage.hasChildPackage(childPs.name))
14309                        ? flags & ~DELETE_KEEP_DATA : flags;
14310                removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo,
14311                        deleteFlags, writeSettings);
14312            }
14313        }
14314
14315        // Delete application code and resources only for parent packages
14316        if (ps.pkg.parentPackage == null) {
14317                if (deleteCodeAndResources && (outInfo != null)) {
14318                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14319                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14320                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14321            }
14322        }
14323
14324        return true;
14325    }
14326
14327    @Override
14328    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14329            int userId) {
14330        mContext.enforceCallingOrSelfPermission(
14331                android.Manifest.permission.DELETE_PACKAGES, null);
14332        synchronized (mPackages) {
14333            PackageSetting ps = mSettings.mPackages.get(packageName);
14334            if (ps == null) {
14335                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14336                return false;
14337            }
14338            if (!ps.getInstalled(userId)) {
14339                // Can't block uninstall for an app that is not installed or enabled.
14340                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14341                return false;
14342            }
14343            ps.setBlockUninstall(blockUninstall, userId);
14344            mSettings.writePackageRestrictionsLPr(userId);
14345        }
14346        return true;
14347    }
14348
14349    @Override
14350    public boolean getBlockUninstallForUser(String packageName, int userId) {
14351        synchronized (mPackages) {
14352            PackageSetting ps = mSettings.mPackages.get(packageName);
14353            if (ps == null) {
14354                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14355                return false;
14356            }
14357            return ps.getBlockUninstall(userId);
14358        }
14359    }
14360
14361    @Override
14362    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14363        int callingUid = Binder.getCallingUid();
14364        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14365            throw new SecurityException(
14366                    "setRequiredForSystemUser can only be run by the system or root");
14367        }
14368        synchronized (mPackages) {
14369            PackageSetting ps = mSettings.mPackages.get(packageName);
14370            if (ps == null) {
14371                Log.w(TAG, "Package doesn't exist: " + packageName);
14372                return false;
14373            }
14374            if (systemUserApp) {
14375                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14376            } else {
14377                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14378            }
14379            mSettings.writeLPr();
14380        }
14381        return true;
14382    }
14383
14384    /*
14385     * This method handles package deletion in general
14386     */
14387    private boolean deletePackageLI(String packageName, UserHandle user,
14388            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
14389            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14390            PackageParser.Package replacingPackage) {
14391        if (packageName == null) {
14392            Slog.w(TAG, "Attempt to delete null packageName.");
14393            return false;
14394        }
14395
14396        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14397
14398        PackageSetting ps;
14399        int removeUser = -1;
14400
14401        synchronized (mPackages) {
14402            ps = mSettings.mPackages.get(packageName);
14403            if (ps == null) {
14404                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14405                return false;
14406            }
14407
14408            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14409                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14410                if (DEBUG_REMOVE) {
14411                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14412                            + ((user == null) ? UserHandle.USER_ALL : user));
14413                }
14414                if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14415                    return false;
14416                }
14417                markPackageUninstalledForUserLPw(ps, user);
14418                scheduleWritePackageRestrictionsLocked(user);
14419                return true;
14420            }
14421        }
14422
14423        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14424                && user.getIdentifier() != UserHandle.USER_ALL)) {
14425            // The caller is asking that the package only be deleted for a single
14426            // user.  To do this, we just mark its uninstalled state and delete
14427            // its data. If this is a system app, we only allow this to happen if
14428            // they have set the special DELETE_SYSTEM_APP which requests different
14429            // semantics than normal for uninstalling system apps.
14430            markPackageUninstalledForUserLPw(ps, user);
14431
14432            if (!isSystemApp(ps)) {
14433                // Do not uninstall the APK if an app should be cached
14434                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14435                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14436                    // Other user still have this package installed, so all
14437                    // we need to do is clear this user's data and save that
14438                // it is uninstalled.
14439                if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14440                    if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14441                        return false;
14442                    }
14443                    scheduleWritePackageRestrictionsLocked(user);
14444                    return true;
14445                } else {
14446                    // We need to set it back to 'installed' so the uninstall
14447                    // broadcasts will be sent correctly.
14448                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14449                    ps.setInstalled(true, user.getIdentifier());
14450                }
14451            } else {
14452                // This is a system app, so we assume that the
14453                // other users still have this package installed, so all
14454                // we need to do is clear this user's data and save that
14455                // it is uninstalled.
14456                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14457                if (!clearPackageStateForUser(ps, removeUser, outInfo)) {
14458                    return false;
14459                }
14460                scheduleWritePackageRestrictionsLocked(user);
14461                return true;
14462            }
14463        }
14464
14465        boolean ret = false;
14466        if (isSystemApp(ps)) {
14467            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14468            // When an updated system application is deleted we delete the existing resources as well and
14469            // fall back to existing code in system partition
14470            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled,
14471                    flags, outInfo, writeSettings, replacingPackage);
14472        } else {
14473            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14474            // Kill application pre-emptively especially for apps on sd.
14475            killApplication(packageName, ps.appId, "uninstall pkg");
14476            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14477                    perUserInstalled, outInfo, writeSettings, replacingPackage);
14478        }
14479
14480        return ret;
14481    }
14482
14483    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14484        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14485                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14486        for (int nextUserId : userIds) {
14487            if (DEBUG_REMOVE) {
14488                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14489            }
14490            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14491                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14492                    false /*hidden*/, false /*suspended*/, null, null, null,
14493                    false /*blockUninstall*/,
14494                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14495        }
14496    }
14497
14498    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14499            PackageRemovedInfo outInfo) {
14500        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14501                : new int[] {userId};
14502        for (int nextUserId : userIds) {
14503            if (DEBUG_REMOVE) {
14504                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14505                        + nextUserId);
14506            }
14507            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14508            try {
14509                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14510            } catch (InstallerException e) {
14511                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14512                return false;
14513            }
14514            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14515            schedulePackageCleaning(ps.name, nextUserId, false);
14516            synchronized (mPackages) {
14517                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14518                    scheduleWritePackageRestrictionsLocked(nextUserId);
14519                }
14520                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14521            }
14522        }
14523
14524        if (outInfo != null) {
14525            outInfo.removedPackage = ps.name;
14526            outInfo.removedAppId = ps.appId;
14527            outInfo.removedUsers = userIds;
14528        }
14529
14530        return true;
14531    }
14532
14533    private final class ClearStorageConnection implements ServiceConnection {
14534        IMediaContainerService mContainerService;
14535
14536        @Override
14537        public void onServiceConnected(ComponentName name, IBinder service) {
14538            synchronized (this) {
14539                mContainerService = IMediaContainerService.Stub.asInterface(service);
14540                notifyAll();
14541            }
14542        }
14543
14544        @Override
14545        public void onServiceDisconnected(ComponentName name) {
14546        }
14547    }
14548
14549    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14550        final boolean mounted;
14551        if (Environment.isExternalStorageEmulated()) {
14552            mounted = true;
14553        } else {
14554            final String status = Environment.getExternalStorageState();
14555
14556            mounted = status.equals(Environment.MEDIA_MOUNTED)
14557                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14558        }
14559
14560        if (!mounted) {
14561            return;
14562        }
14563
14564        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14565        int[] users;
14566        if (userId == UserHandle.USER_ALL) {
14567            users = sUserManager.getUserIds();
14568        } else {
14569            users = new int[] { userId };
14570        }
14571        final ClearStorageConnection conn = new ClearStorageConnection();
14572        if (mContext.bindServiceAsUser(
14573                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14574            try {
14575                for (int curUser : users) {
14576                    long timeout = SystemClock.uptimeMillis() + 5000;
14577                    synchronized (conn) {
14578                        long now = SystemClock.uptimeMillis();
14579                        while (conn.mContainerService == null && now < timeout) {
14580                            try {
14581                                conn.wait(timeout - now);
14582                            } catch (InterruptedException e) {
14583                            }
14584                        }
14585                    }
14586                    if (conn.mContainerService == null) {
14587                        return;
14588                    }
14589
14590                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14591                    clearDirectory(conn.mContainerService,
14592                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14593                    if (allData) {
14594                        clearDirectory(conn.mContainerService,
14595                                userEnv.buildExternalStorageAppDataDirs(packageName));
14596                        clearDirectory(conn.mContainerService,
14597                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14598                    }
14599                }
14600            } finally {
14601                mContext.unbindService(conn);
14602            }
14603        }
14604    }
14605
14606    @Override
14607    public void clearApplicationUserData(final String packageName,
14608            final IPackageDataObserver observer, final int userId) {
14609        mContext.enforceCallingOrSelfPermission(
14610                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14611        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14612        // Queue up an async operation since the package deletion may take a little while.
14613        mHandler.post(new Runnable() {
14614            public void run() {
14615                mHandler.removeCallbacks(this);
14616                final boolean succeeded;
14617                synchronized (mInstallLock) {
14618                    succeeded = clearApplicationUserDataLI(packageName, userId);
14619                }
14620                clearExternalStorageDataSync(packageName, userId, true);
14621                if (succeeded) {
14622                    // invoke DeviceStorageMonitor's update method to clear any notifications
14623                    DeviceStorageMonitorInternal
14624                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14625                    if (dsm != null) {
14626                        dsm.checkMemory();
14627                    }
14628                }
14629                if(observer != null) {
14630                    try {
14631                        observer.onRemoveCompleted(packageName, succeeded);
14632                    } catch (RemoteException e) {
14633                        Log.i(TAG, "Observer no longer exists.");
14634                    }
14635                } //end if observer
14636            } //end run
14637        });
14638    }
14639
14640    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14641        if (packageName == null) {
14642            Slog.w(TAG, "Attempt to delete null packageName.");
14643            return false;
14644        }
14645
14646        // Try finding details about the requested package
14647        PackageParser.Package pkg;
14648        synchronized (mPackages) {
14649            pkg = mPackages.get(packageName);
14650            if (pkg == null) {
14651                final PackageSetting ps = mSettings.mPackages.get(packageName);
14652                if (ps != null) {
14653                    pkg = ps.pkg;
14654                }
14655            }
14656
14657            if (pkg == null) {
14658                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14659                return false;
14660            }
14661
14662            PackageSetting ps = (PackageSetting) pkg.mExtras;
14663            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14664        }
14665
14666        // Always delete data directories for package, even if we found no other
14667        // record of app. This helps users recover from UID mismatches without
14668        // resorting to a full data wipe.
14669        // TODO: triage flags as part of 26466827
14670        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14671        try {
14672            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14673        } catch (InstallerException e) {
14674            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14675            return false;
14676        }
14677
14678        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14679        removeKeystoreDataIfNeeded(userId, appId);
14680
14681        // Create a native library symlink only if we have native libraries
14682        // and if the native libraries are 32 bit libraries. We do not provide
14683        // this symlink for 64 bit libraries.
14684        if (pkg.applicationInfo.primaryCpuAbi != null &&
14685                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14686            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14687            try {
14688                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14689                        nativeLibPath, userId);
14690            } catch (InstallerException e) {
14691                Slog.w(TAG, "Failed linking native library dir", e);
14692                return false;
14693            }
14694        }
14695
14696        return true;
14697    }
14698
14699    /**
14700     * Reverts user permission state changes (permissions and flags) in
14701     * all packages for a given user.
14702     *
14703     * @param userId The device user for which to do a reset.
14704     */
14705    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14706        final int packageCount = mPackages.size();
14707        for (int i = 0; i < packageCount; i++) {
14708            PackageParser.Package pkg = mPackages.valueAt(i);
14709            PackageSetting ps = (PackageSetting) pkg.mExtras;
14710            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14711        }
14712    }
14713
14714    /**
14715     * Reverts user permission state changes (permissions and flags).
14716     *
14717     * @param ps The package for which to reset.
14718     * @param userId The device user for which to do a reset.
14719     */
14720    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14721            final PackageSetting ps, final int userId) {
14722        if (ps.pkg == null) {
14723            return;
14724        }
14725
14726        // These are flags that can change base on user actions.
14727        final int userSettableMask = FLAG_PERMISSION_USER_SET
14728                | FLAG_PERMISSION_USER_FIXED
14729                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14730                | FLAG_PERMISSION_REVIEW_REQUIRED;
14731
14732        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14733                | FLAG_PERMISSION_POLICY_FIXED;
14734
14735        boolean writeInstallPermissions = false;
14736        boolean writeRuntimePermissions = false;
14737
14738        final int permissionCount = ps.pkg.requestedPermissions.size();
14739        for (int i = 0; i < permissionCount; i++) {
14740            String permission = ps.pkg.requestedPermissions.get(i);
14741
14742            BasePermission bp = mSettings.mPermissions.get(permission);
14743            if (bp == null) {
14744                continue;
14745            }
14746
14747            // If shared user we just reset the state to which only this app contributed.
14748            if (ps.sharedUser != null) {
14749                boolean used = false;
14750                final int packageCount = ps.sharedUser.packages.size();
14751                for (int j = 0; j < packageCount; j++) {
14752                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14753                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14754                            && pkg.pkg.requestedPermissions.contains(permission)) {
14755                        used = true;
14756                        break;
14757                    }
14758                }
14759                if (used) {
14760                    continue;
14761                }
14762            }
14763
14764            PermissionsState permissionsState = ps.getPermissionsState();
14765
14766            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14767
14768            // Always clear the user settable flags.
14769            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14770                    bp.name) != null;
14771            // If permission review is enabled and this is a legacy app, mark the
14772            // permission as requiring a review as this is the initial state.
14773            int flags = 0;
14774            if (Build.PERMISSIONS_REVIEW_REQUIRED
14775                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14776                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14777            }
14778            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14779                if (hasInstallState) {
14780                    writeInstallPermissions = true;
14781                } else {
14782                    writeRuntimePermissions = true;
14783                }
14784            }
14785
14786            // Below is only runtime permission handling.
14787            if (!bp.isRuntime()) {
14788                continue;
14789            }
14790
14791            // Never clobber system or policy.
14792            if ((oldFlags & policyOrSystemFlags) != 0) {
14793                continue;
14794            }
14795
14796            // If this permission was granted by default, make sure it is.
14797            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14798                if (permissionsState.grantRuntimePermission(bp, userId)
14799                        != PERMISSION_OPERATION_FAILURE) {
14800                    writeRuntimePermissions = true;
14801                }
14802            // If permission review is enabled the permissions for a legacy apps
14803            // are represented as constantly granted runtime ones, so don't revoke.
14804            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14805                // Otherwise, reset the permission.
14806                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14807                switch (revokeResult) {
14808                    case PERMISSION_OPERATION_SUCCESS: {
14809                        writeRuntimePermissions = true;
14810                    } break;
14811
14812                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14813                        writeRuntimePermissions = true;
14814                        final int appId = ps.appId;
14815                        mHandler.post(new Runnable() {
14816                            @Override
14817                            public void run() {
14818                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14819                            }
14820                        });
14821                    } break;
14822                }
14823            }
14824        }
14825
14826        // Synchronously write as we are taking permissions away.
14827        if (writeRuntimePermissions) {
14828            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14829        }
14830
14831        // Synchronously write as we are taking permissions away.
14832        if (writeInstallPermissions) {
14833            mSettings.writeLPr();
14834        }
14835    }
14836
14837    /**
14838     * Remove entries from the keystore daemon. Will only remove it if the
14839     * {@code appId} is valid.
14840     */
14841    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14842        if (appId < 0) {
14843            return;
14844        }
14845
14846        final KeyStore keyStore = KeyStore.getInstance();
14847        if (keyStore != null) {
14848            if (userId == UserHandle.USER_ALL) {
14849                for (final int individual : sUserManager.getUserIds()) {
14850                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14851                }
14852            } else {
14853                keyStore.clearUid(UserHandle.getUid(userId, appId));
14854            }
14855        } else {
14856            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14857        }
14858    }
14859
14860    @Override
14861    public void deleteApplicationCacheFiles(final String packageName,
14862            final IPackageDataObserver observer) {
14863        mContext.enforceCallingOrSelfPermission(
14864                android.Manifest.permission.DELETE_CACHE_FILES, null);
14865        // Queue up an async operation since the package deletion may take a little while.
14866        final int userId = UserHandle.getCallingUserId();
14867        mHandler.post(new Runnable() {
14868            public void run() {
14869                mHandler.removeCallbacks(this);
14870                final boolean succeded;
14871                synchronized (mInstallLock) {
14872                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14873                }
14874                clearExternalStorageDataSync(packageName, userId, false);
14875                if (observer != null) {
14876                    try {
14877                        observer.onRemoveCompleted(packageName, succeded);
14878                    } catch (RemoteException e) {
14879                        Log.i(TAG, "Observer no longer exists.");
14880                    }
14881                } //end if observer
14882            } //end run
14883        });
14884    }
14885
14886    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14887        if (packageName == null) {
14888            Slog.w(TAG, "Attempt to delete null packageName.");
14889            return false;
14890        }
14891        PackageParser.Package p;
14892        synchronized (mPackages) {
14893            p = mPackages.get(packageName);
14894        }
14895        if (p == null) {
14896            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14897            return false;
14898        }
14899        final ApplicationInfo applicationInfo = p.applicationInfo;
14900        if (applicationInfo == null) {
14901            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14902            return false;
14903        }
14904        // TODO: triage flags as part of 26466827
14905        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14906        try {
14907            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14908                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14909        } catch (InstallerException e) {
14910            Slog.w(TAG, "Couldn't remove cache files for package "
14911                    + packageName + " u" + userId, e);
14912            return false;
14913        }
14914        return true;
14915    }
14916
14917    @Override
14918    public void getPackageSizeInfo(final String packageName, int userHandle,
14919            final IPackageStatsObserver observer) {
14920        mContext.enforceCallingOrSelfPermission(
14921                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14922        if (packageName == null) {
14923            throw new IllegalArgumentException("Attempt to get size of null packageName");
14924        }
14925
14926        PackageStats stats = new PackageStats(packageName, userHandle);
14927
14928        /*
14929         * Queue up an async operation since the package measurement may take a
14930         * little while.
14931         */
14932        Message msg = mHandler.obtainMessage(INIT_COPY);
14933        msg.obj = new MeasureParams(stats, observer);
14934        mHandler.sendMessage(msg);
14935    }
14936
14937    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14938            PackageStats pStats) {
14939        if (packageName == null) {
14940            Slog.w(TAG, "Attempt to get size of null packageName.");
14941            return false;
14942        }
14943        PackageParser.Package p;
14944        boolean dataOnly = false;
14945        String libDirRoot = null;
14946        String asecPath = null;
14947        PackageSetting ps = null;
14948        synchronized (mPackages) {
14949            p = mPackages.get(packageName);
14950            ps = mSettings.mPackages.get(packageName);
14951            if(p == null) {
14952                dataOnly = true;
14953                if((ps == null) || (ps.pkg == null)) {
14954                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14955                    return false;
14956                }
14957                p = ps.pkg;
14958            }
14959            if (ps != null) {
14960                libDirRoot = ps.legacyNativeLibraryPathString;
14961            }
14962            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14963                final long token = Binder.clearCallingIdentity();
14964                try {
14965                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14966                    if (secureContainerId != null) {
14967                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14968                    }
14969                } finally {
14970                    Binder.restoreCallingIdentity(token);
14971                }
14972            }
14973        }
14974        String publicSrcDir = null;
14975        if(!dataOnly) {
14976            final ApplicationInfo applicationInfo = p.applicationInfo;
14977            if (applicationInfo == null) {
14978                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14979                return false;
14980            }
14981            if (p.isForwardLocked()) {
14982                publicSrcDir = applicationInfo.getBaseResourcePath();
14983            }
14984        }
14985        // TODO: extend to measure size of split APKs
14986        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14987        // not just the first level.
14988        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14989        // just the primary.
14990        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14991
14992        String apkPath;
14993        File packageDir = new File(p.codePath);
14994
14995        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14996            apkPath = packageDir.getAbsolutePath();
14997            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14998            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14999                libDirRoot = null;
15000            }
15001        } else {
15002            apkPath = p.baseCodePath;
15003        }
15004
15005        // TODO: triage flags as part of 26466827
15006        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15007        try {
15008            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15009                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15010        } catch (InstallerException e) {
15011            return false;
15012        }
15013
15014        // Fix-up for forward-locked applications in ASEC containers.
15015        if (!isExternal(p)) {
15016            pStats.codeSize += pStats.externalCodeSize;
15017            pStats.externalCodeSize = 0L;
15018        }
15019
15020        return true;
15021    }
15022
15023
15024    @Override
15025    public void addPackageToPreferred(String packageName) {
15026        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15027    }
15028
15029    @Override
15030    public void removePackageFromPreferred(String packageName) {
15031        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15032    }
15033
15034    @Override
15035    public List<PackageInfo> getPreferredPackages(int flags) {
15036        return new ArrayList<PackageInfo>();
15037    }
15038
15039    private int getUidTargetSdkVersionLockedLPr(int uid) {
15040        Object obj = mSettings.getUserIdLPr(uid);
15041        if (obj instanceof SharedUserSetting) {
15042            final SharedUserSetting sus = (SharedUserSetting) obj;
15043            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15044            final Iterator<PackageSetting> it = sus.packages.iterator();
15045            while (it.hasNext()) {
15046                final PackageSetting ps = it.next();
15047                if (ps.pkg != null) {
15048                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15049                    if (v < vers) vers = v;
15050                }
15051            }
15052            return vers;
15053        } else if (obj instanceof PackageSetting) {
15054            final PackageSetting ps = (PackageSetting) obj;
15055            if (ps.pkg != null) {
15056                return ps.pkg.applicationInfo.targetSdkVersion;
15057            }
15058        }
15059        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15060    }
15061
15062    @Override
15063    public void addPreferredActivity(IntentFilter filter, int match,
15064            ComponentName[] set, ComponentName activity, int userId) {
15065        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15066                "Adding preferred");
15067    }
15068
15069    private void addPreferredActivityInternal(IntentFilter filter, int match,
15070            ComponentName[] set, ComponentName activity, boolean always, int userId,
15071            String opname) {
15072        // writer
15073        int callingUid = Binder.getCallingUid();
15074        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15075        if (filter.countActions() == 0) {
15076            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15077            return;
15078        }
15079        synchronized (mPackages) {
15080            if (mContext.checkCallingOrSelfPermission(
15081                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15082                    != PackageManager.PERMISSION_GRANTED) {
15083                if (getUidTargetSdkVersionLockedLPr(callingUid)
15084                        < Build.VERSION_CODES.FROYO) {
15085                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15086                            + callingUid);
15087                    return;
15088                }
15089                mContext.enforceCallingOrSelfPermission(
15090                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15091            }
15092
15093            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15094            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15095                    + userId + ":");
15096            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15097            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15098            scheduleWritePackageRestrictionsLocked(userId);
15099        }
15100    }
15101
15102    @Override
15103    public void replacePreferredActivity(IntentFilter filter, int match,
15104            ComponentName[] set, ComponentName activity, int userId) {
15105        if (filter.countActions() != 1) {
15106            throw new IllegalArgumentException(
15107                    "replacePreferredActivity expects filter to have only 1 action.");
15108        }
15109        if (filter.countDataAuthorities() != 0
15110                || filter.countDataPaths() != 0
15111                || filter.countDataSchemes() > 1
15112                || filter.countDataTypes() != 0) {
15113            throw new IllegalArgumentException(
15114                    "replacePreferredActivity expects filter to have no data authorities, " +
15115                    "paths, or types; and at most one scheme.");
15116        }
15117
15118        final int callingUid = Binder.getCallingUid();
15119        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15120        synchronized (mPackages) {
15121            if (mContext.checkCallingOrSelfPermission(
15122                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15123                    != PackageManager.PERMISSION_GRANTED) {
15124                if (getUidTargetSdkVersionLockedLPr(callingUid)
15125                        < Build.VERSION_CODES.FROYO) {
15126                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15127                            + Binder.getCallingUid());
15128                    return;
15129                }
15130                mContext.enforceCallingOrSelfPermission(
15131                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15132            }
15133
15134            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15135            if (pir != null) {
15136                // Get all of the existing entries that exactly match this filter.
15137                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15138                if (existing != null && existing.size() == 1) {
15139                    PreferredActivity cur = existing.get(0);
15140                    if (DEBUG_PREFERRED) {
15141                        Slog.i(TAG, "Checking replace of preferred:");
15142                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15143                        if (!cur.mPref.mAlways) {
15144                            Slog.i(TAG, "  -- CUR; not mAlways!");
15145                        } else {
15146                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15147                            Slog.i(TAG, "  -- CUR: mSet="
15148                                    + Arrays.toString(cur.mPref.mSetComponents));
15149                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15150                            Slog.i(TAG, "  -- NEW: mMatch="
15151                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15152                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15153                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15154                        }
15155                    }
15156                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15157                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15158                            && cur.mPref.sameSet(set)) {
15159                        // Setting the preferred activity to what it happens to be already
15160                        if (DEBUG_PREFERRED) {
15161                            Slog.i(TAG, "Replacing with same preferred activity "
15162                                    + cur.mPref.mShortComponent + " for user "
15163                                    + userId + ":");
15164                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15165                        }
15166                        return;
15167                    }
15168                }
15169
15170                if (existing != null) {
15171                    if (DEBUG_PREFERRED) {
15172                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15173                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15174                    }
15175                    for (int i = 0; i < existing.size(); i++) {
15176                        PreferredActivity pa = existing.get(i);
15177                        if (DEBUG_PREFERRED) {
15178                            Slog.i(TAG, "Removing existing preferred activity "
15179                                    + pa.mPref.mComponent + ":");
15180                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15181                        }
15182                        pir.removeFilter(pa);
15183                    }
15184                }
15185            }
15186            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15187                    "Replacing preferred");
15188        }
15189    }
15190
15191    @Override
15192    public void clearPackagePreferredActivities(String packageName) {
15193        final int uid = Binder.getCallingUid();
15194        // writer
15195        synchronized (mPackages) {
15196            PackageParser.Package pkg = mPackages.get(packageName);
15197            if (pkg == null || pkg.applicationInfo.uid != uid) {
15198                if (mContext.checkCallingOrSelfPermission(
15199                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15200                        != PackageManager.PERMISSION_GRANTED) {
15201                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15202                            < Build.VERSION_CODES.FROYO) {
15203                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15204                                + Binder.getCallingUid());
15205                        return;
15206                    }
15207                    mContext.enforceCallingOrSelfPermission(
15208                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15209                }
15210            }
15211
15212            int user = UserHandle.getCallingUserId();
15213            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15214                scheduleWritePackageRestrictionsLocked(user);
15215            }
15216        }
15217    }
15218
15219    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15220    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15221        ArrayList<PreferredActivity> removed = null;
15222        boolean changed = false;
15223        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15224            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15225            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15226            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15227                continue;
15228            }
15229            Iterator<PreferredActivity> it = pir.filterIterator();
15230            while (it.hasNext()) {
15231                PreferredActivity pa = it.next();
15232                // Mark entry for removal only if it matches the package name
15233                // and the entry is of type "always".
15234                if (packageName == null ||
15235                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15236                                && pa.mPref.mAlways)) {
15237                    if (removed == null) {
15238                        removed = new ArrayList<PreferredActivity>();
15239                    }
15240                    removed.add(pa);
15241                }
15242            }
15243            if (removed != null) {
15244                for (int j=0; j<removed.size(); j++) {
15245                    PreferredActivity pa = removed.get(j);
15246                    pir.removeFilter(pa);
15247                }
15248                changed = true;
15249            }
15250        }
15251        return changed;
15252    }
15253
15254    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15255    private void clearIntentFilterVerificationsLPw(int userId) {
15256        final int packageCount = mPackages.size();
15257        for (int i = 0; i < packageCount; i++) {
15258            PackageParser.Package pkg = mPackages.valueAt(i);
15259            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15260        }
15261    }
15262
15263    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15264    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15265        if (userId == UserHandle.USER_ALL) {
15266            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15267                    sUserManager.getUserIds())) {
15268                for (int oneUserId : sUserManager.getUserIds()) {
15269                    scheduleWritePackageRestrictionsLocked(oneUserId);
15270                }
15271            }
15272        } else {
15273            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15274                scheduleWritePackageRestrictionsLocked(userId);
15275            }
15276        }
15277    }
15278
15279    void clearDefaultBrowserIfNeeded(String packageName) {
15280        for (int oneUserId : sUserManager.getUserIds()) {
15281            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15282            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15283            if (packageName.equals(defaultBrowserPackageName)) {
15284                setDefaultBrowserPackageName(null, oneUserId);
15285            }
15286        }
15287    }
15288
15289    @Override
15290    public void resetApplicationPreferences(int userId) {
15291        mContext.enforceCallingOrSelfPermission(
15292                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15293        // writer
15294        synchronized (mPackages) {
15295            final long identity = Binder.clearCallingIdentity();
15296            try {
15297                clearPackagePreferredActivitiesLPw(null, userId);
15298                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15299                // TODO: We have to reset the default SMS and Phone. This requires
15300                // significant refactoring to keep all default apps in the package
15301                // manager (cleaner but more work) or have the services provide
15302                // callbacks to the package manager to request a default app reset.
15303                applyFactoryDefaultBrowserLPw(userId);
15304                clearIntentFilterVerificationsLPw(userId);
15305                primeDomainVerificationsLPw(userId);
15306                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15307                scheduleWritePackageRestrictionsLocked(userId);
15308            } finally {
15309                Binder.restoreCallingIdentity(identity);
15310            }
15311        }
15312    }
15313
15314    @Override
15315    public int getPreferredActivities(List<IntentFilter> outFilters,
15316            List<ComponentName> outActivities, String packageName) {
15317
15318        int num = 0;
15319        final int userId = UserHandle.getCallingUserId();
15320        // reader
15321        synchronized (mPackages) {
15322            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15323            if (pir != null) {
15324                final Iterator<PreferredActivity> it = pir.filterIterator();
15325                while (it.hasNext()) {
15326                    final PreferredActivity pa = it.next();
15327                    if (packageName == null
15328                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15329                                    && pa.mPref.mAlways)) {
15330                        if (outFilters != null) {
15331                            outFilters.add(new IntentFilter(pa));
15332                        }
15333                        if (outActivities != null) {
15334                            outActivities.add(pa.mPref.mComponent);
15335                        }
15336                    }
15337                }
15338            }
15339        }
15340
15341        return num;
15342    }
15343
15344    @Override
15345    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15346            int userId) {
15347        int callingUid = Binder.getCallingUid();
15348        if (callingUid != Process.SYSTEM_UID) {
15349            throw new SecurityException(
15350                    "addPersistentPreferredActivity can only be run by the system");
15351        }
15352        if (filter.countActions() == 0) {
15353            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15354            return;
15355        }
15356        synchronized (mPackages) {
15357            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15358                    ":");
15359            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15360            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15361                    new PersistentPreferredActivity(filter, activity));
15362            scheduleWritePackageRestrictionsLocked(userId);
15363        }
15364    }
15365
15366    @Override
15367    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15368        int callingUid = Binder.getCallingUid();
15369        if (callingUid != Process.SYSTEM_UID) {
15370            throw new SecurityException(
15371                    "clearPackagePersistentPreferredActivities can only be run by the system");
15372        }
15373        ArrayList<PersistentPreferredActivity> removed = null;
15374        boolean changed = false;
15375        synchronized (mPackages) {
15376            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15377                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15378                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15379                        .valueAt(i);
15380                if (userId != thisUserId) {
15381                    continue;
15382                }
15383                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15384                while (it.hasNext()) {
15385                    PersistentPreferredActivity ppa = it.next();
15386                    // Mark entry for removal only if it matches the package name.
15387                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15388                        if (removed == null) {
15389                            removed = new ArrayList<PersistentPreferredActivity>();
15390                        }
15391                        removed.add(ppa);
15392                    }
15393                }
15394                if (removed != null) {
15395                    for (int j=0; j<removed.size(); j++) {
15396                        PersistentPreferredActivity ppa = removed.get(j);
15397                        ppir.removeFilter(ppa);
15398                    }
15399                    changed = true;
15400                }
15401            }
15402
15403            if (changed) {
15404                scheduleWritePackageRestrictionsLocked(userId);
15405            }
15406        }
15407    }
15408
15409    /**
15410     * Common machinery for picking apart a restored XML blob and passing
15411     * it to a caller-supplied functor to be applied to the running system.
15412     */
15413    private void restoreFromXml(XmlPullParser parser, int userId,
15414            String expectedStartTag, BlobXmlRestorer functor)
15415            throws IOException, XmlPullParserException {
15416        int type;
15417        while ((type = parser.next()) != XmlPullParser.START_TAG
15418                && type != XmlPullParser.END_DOCUMENT) {
15419        }
15420        if (type != XmlPullParser.START_TAG) {
15421            // oops didn't find a start tag?!
15422            if (DEBUG_BACKUP) {
15423                Slog.e(TAG, "Didn't find start tag during restore");
15424            }
15425            return;
15426        }
15427Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15428        // this is supposed to be TAG_PREFERRED_BACKUP
15429        if (!expectedStartTag.equals(parser.getName())) {
15430            if (DEBUG_BACKUP) {
15431                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15432            }
15433            return;
15434        }
15435
15436        // skip interfering stuff, then we're aligned with the backing implementation
15437        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15438Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15439        functor.apply(parser, userId);
15440    }
15441
15442    private interface BlobXmlRestorer {
15443        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15444    }
15445
15446    /**
15447     * Non-Binder method, support for the backup/restore mechanism: write the
15448     * full set of preferred activities in its canonical XML format.  Returns the
15449     * XML output as a byte array, or null if there is none.
15450     */
15451    @Override
15452    public byte[] getPreferredActivityBackup(int userId) {
15453        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15454            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15455        }
15456
15457        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15458        try {
15459            final XmlSerializer serializer = new FastXmlSerializer();
15460            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15461            serializer.startDocument(null, true);
15462            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15463
15464            synchronized (mPackages) {
15465                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15466            }
15467
15468            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15469            serializer.endDocument();
15470            serializer.flush();
15471        } catch (Exception e) {
15472            if (DEBUG_BACKUP) {
15473                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15474            }
15475            return null;
15476        }
15477
15478        return dataStream.toByteArray();
15479    }
15480
15481    @Override
15482    public void restorePreferredActivities(byte[] backup, int userId) {
15483        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15484            throw new SecurityException("Only the system may call restorePreferredActivities()");
15485        }
15486
15487        try {
15488            final XmlPullParser parser = Xml.newPullParser();
15489            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15490            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15491                    new BlobXmlRestorer() {
15492                        @Override
15493                        public void apply(XmlPullParser parser, int userId)
15494                                throws XmlPullParserException, IOException {
15495                            synchronized (mPackages) {
15496                                mSettings.readPreferredActivitiesLPw(parser, userId);
15497                            }
15498                        }
15499                    } );
15500        } catch (Exception e) {
15501            if (DEBUG_BACKUP) {
15502                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15503            }
15504        }
15505    }
15506
15507    /**
15508     * Non-Binder method, support for the backup/restore mechanism: write the
15509     * default browser (etc) settings in its canonical XML format.  Returns the default
15510     * browser XML representation as a byte array, or null if there is none.
15511     */
15512    @Override
15513    public byte[] getDefaultAppsBackup(int userId) {
15514        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15515            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15516        }
15517
15518        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15519        try {
15520            final XmlSerializer serializer = new FastXmlSerializer();
15521            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15522            serializer.startDocument(null, true);
15523            serializer.startTag(null, TAG_DEFAULT_APPS);
15524
15525            synchronized (mPackages) {
15526                mSettings.writeDefaultAppsLPr(serializer, userId);
15527            }
15528
15529            serializer.endTag(null, TAG_DEFAULT_APPS);
15530            serializer.endDocument();
15531            serializer.flush();
15532        } catch (Exception e) {
15533            if (DEBUG_BACKUP) {
15534                Slog.e(TAG, "Unable to write default apps for backup", e);
15535            }
15536            return null;
15537        }
15538
15539        return dataStream.toByteArray();
15540    }
15541
15542    @Override
15543    public void restoreDefaultApps(byte[] backup, int userId) {
15544        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15545            throw new SecurityException("Only the system may call restoreDefaultApps()");
15546        }
15547
15548        try {
15549            final XmlPullParser parser = Xml.newPullParser();
15550            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15551            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15552                    new BlobXmlRestorer() {
15553                        @Override
15554                        public void apply(XmlPullParser parser, int userId)
15555                                throws XmlPullParserException, IOException {
15556                            synchronized (mPackages) {
15557                                mSettings.readDefaultAppsLPw(parser, userId);
15558                            }
15559                        }
15560                    } );
15561        } catch (Exception e) {
15562            if (DEBUG_BACKUP) {
15563                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15564            }
15565        }
15566    }
15567
15568    @Override
15569    public byte[] getIntentFilterVerificationBackup(int userId) {
15570        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15571            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15572        }
15573
15574        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15575        try {
15576            final XmlSerializer serializer = new FastXmlSerializer();
15577            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15578            serializer.startDocument(null, true);
15579            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15580
15581            synchronized (mPackages) {
15582                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15583            }
15584
15585            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15586            serializer.endDocument();
15587            serializer.flush();
15588        } catch (Exception e) {
15589            if (DEBUG_BACKUP) {
15590                Slog.e(TAG, "Unable to write default apps for backup", e);
15591            }
15592            return null;
15593        }
15594
15595        return dataStream.toByteArray();
15596    }
15597
15598    @Override
15599    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15600        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15601            throw new SecurityException("Only the system may call restorePreferredActivities()");
15602        }
15603
15604        try {
15605            final XmlPullParser parser = Xml.newPullParser();
15606            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15607            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15608                    new BlobXmlRestorer() {
15609                        @Override
15610                        public void apply(XmlPullParser parser, int userId)
15611                                throws XmlPullParserException, IOException {
15612                            synchronized (mPackages) {
15613                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15614                                mSettings.writeLPr();
15615                            }
15616                        }
15617                    } );
15618        } catch (Exception e) {
15619            if (DEBUG_BACKUP) {
15620                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15621            }
15622        }
15623    }
15624
15625    @Override
15626    public byte[] getPermissionGrantBackup(int userId) {
15627        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15628            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15629        }
15630
15631        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15632        try {
15633            final XmlSerializer serializer = new FastXmlSerializer();
15634            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15635            serializer.startDocument(null, true);
15636            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15637
15638            synchronized (mPackages) {
15639                serializeRuntimePermissionGrantsLPr(serializer, userId);
15640            }
15641
15642            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15643            serializer.endDocument();
15644            serializer.flush();
15645        } catch (Exception e) {
15646            if (DEBUG_BACKUP) {
15647                Slog.e(TAG, "Unable to write default apps for backup", e);
15648            }
15649            return null;
15650        }
15651
15652        return dataStream.toByteArray();
15653    }
15654
15655    @Override
15656    public void restorePermissionGrants(byte[] backup, int userId) {
15657        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15658            throw new SecurityException("Only the system may call restorePermissionGrants()");
15659        }
15660
15661        try {
15662            final XmlPullParser parser = Xml.newPullParser();
15663            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15664            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15665                    new BlobXmlRestorer() {
15666                        @Override
15667                        public void apply(XmlPullParser parser, int userId)
15668                                throws XmlPullParserException, IOException {
15669                            synchronized (mPackages) {
15670                                processRestoredPermissionGrantsLPr(parser, userId);
15671                            }
15672                        }
15673                    } );
15674        } catch (Exception e) {
15675            if (DEBUG_BACKUP) {
15676                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15677            }
15678        }
15679    }
15680
15681    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15682            throws IOException {
15683        serializer.startTag(null, TAG_ALL_GRANTS);
15684
15685        final int N = mSettings.mPackages.size();
15686        for (int i = 0; i < N; i++) {
15687            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15688            boolean pkgGrantsKnown = false;
15689
15690            PermissionsState packagePerms = ps.getPermissionsState();
15691
15692            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15693                final int grantFlags = state.getFlags();
15694                // only look at grants that are not system/policy fixed
15695                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15696                    final boolean isGranted = state.isGranted();
15697                    // And only back up the user-twiddled state bits
15698                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15699                        final String packageName = mSettings.mPackages.keyAt(i);
15700                        if (!pkgGrantsKnown) {
15701                            serializer.startTag(null, TAG_GRANT);
15702                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15703                            pkgGrantsKnown = true;
15704                        }
15705
15706                        final boolean userSet =
15707                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15708                        final boolean userFixed =
15709                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15710                        final boolean revoke =
15711                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15712
15713                        serializer.startTag(null, TAG_PERMISSION);
15714                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15715                        if (isGranted) {
15716                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15717                        }
15718                        if (userSet) {
15719                            serializer.attribute(null, ATTR_USER_SET, "true");
15720                        }
15721                        if (userFixed) {
15722                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15723                        }
15724                        if (revoke) {
15725                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15726                        }
15727                        serializer.endTag(null, TAG_PERMISSION);
15728                    }
15729                }
15730            }
15731
15732            if (pkgGrantsKnown) {
15733                serializer.endTag(null, TAG_GRANT);
15734            }
15735        }
15736
15737        serializer.endTag(null, TAG_ALL_GRANTS);
15738    }
15739
15740    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15741            throws XmlPullParserException, IOException {
15742        String pkgName = null;
15743        int outerDepth = parser.getDepth();
15744        int type;
15745        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15746                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15747            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15748                continue;
15749            }
15750
15751            final String tagName = parser.getName();
15752            if (tagName.equals(TAG_GRANT)) {
15753                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15754                if (DEBUG_BACKUP) {
15755                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15756                }
15757            } else if (tagName.equals(TAG_PERMISSION)) {
15758
15759                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15760                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15761
15762                int newFlagSet = 0;
15763                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15764                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15765                }
15766                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15767                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15768                }
15769                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15770                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15771                }
15772                if (DEBUG_BACKUP) {
15773                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15774                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15775                }
15776                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15777                if (ps != null) {
15778                    // Already installed so we apply the grant immediately
15779                    if (DEBUG_BACKUP) {
15780                        Slog.v(TAG, "        + already installed; applying");
15781                    }
15782                    PermissionsState perms = ps.getPermissionsState();
15783                    BasePermission bp = mSettings.mPermissions.get(permName);
15784                    if (bp != null) {
15785                        if (isGranted) {
15786                            perms.grantRuntimePermission(bp, userId);
15787                        }
15788                        if (newFlagSet != 0) {
15789                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15790                        }
15791                    }
15792                } else {
15793                    // Need to wait for post-restore install to apply the grant
15794                    if (DEBUG_BACKUP) {
15795                        Slog.v(TAG, "        - not yet installed; saving for later");
15796                    }
15797                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15798                            isGranted, newFlagSet, userId);
15799                }
15800            } else {
15801                PackageManagerService.reportSettingsProblem(Log.WARN,
15802                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15803                XmlUtils.skipCurrentTag(parser);
15804            }
15805        }
15806
15807        scheduleWriteSettingsLocked();
15808        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15809    }
15810
15811    @Override
15812    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15813            int sourceUserId, int targetUserId, int flags) {
15814        mContext.enforceCallingOrSelfPermission(
15815                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15816        int callingUid = Binder.getCallingUid();
15817        enforceOwnerRights(ownerPackage, callingUid);
15818        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15819        if (intentFilter.countActions() == 0) {
15820            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15821            return;
15822        }
15823        synchronized (mPackages) {
15824            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15825                    ownerPackage, targetUserId, flags);
15826            CrossProfileIntentResolver resolver =
15827                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15828            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15829            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15830            if (existing != null) {
15831                int size = existing.size();
15832                for (int i = 0; i < size; i++) {
15833                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15834                        return;
15835                    }
15836                }
15837            }
15838            resolver.addFilter(newFilter);
15839            scheduleWritePackageRestrictionsLocked(sourceUserId);
15840        }
15841    }
15842
15843    @Override
15844    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15845        mContext.enforceCallingOrSelfPermission(
15846                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15847        int callingUid = Binder.getCallingUid();
15848        enforceOwnerRights(ownerPackage, callingUid);
15849        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15850        synchronized (mPackages) {
15851            CrossProfileIntentResolver resolver =
15852                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15853            ArraySet<CrossProfileIntentFilter> set =
15854                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15855            for (CrossProfileIntentFilter filter : set) {
15856                if (filter.getOwnerPackage().equals(ownerPackage)) {
15857                    resolver.removeFilter(filter);
15858                }
15859            }
15860            scheduleWritePackageRestrictionsLocked(sourceUserId);
15861        }
15862    }
15863
15864    // Enforcing that callingUid is owning pkg on userId
15865    private void enforceOwnerRights(String pkg, int callingUid) {
15866        // The system owns everything.
15867        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15868            return;
15869        }
15870        int callingUserId = UserHandle.getUserId(callingUid);
15871        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15872        if (pi == null) {
15873            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15874                    + callingUserId);
15875        }
15876        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15877            throw new SecurityException("Calling uid " + callingUid
15878                    + " does not own package " + pkg);
15879        }
15880    }
15881
15882    @Override
15883    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15884        Intent intent = new Intent(Intent.ACTION_MAIN);
15885        intent.addCategory(Intent.CATEGORY_HOME);
15886
15887        final int callingUserId = UserHandle.getCallingUserId();
15888        List<ResolveInfo> list = queryIntentActivities(intent, null,
15889                PackageManager.GET_META_DATA, callingUserId);
15890        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15891                true, false, false, callingUserId);
15892
15893        allHomeCandidates.clear();
15894        if (list != null) {
15895            for (ResolveInfo ri : list) {
15896                allHomeCandidates.add(ri);
15897            }
15898        }
15899        return (preferred == null || preferred.activityInfo == null)
15900                ? null
15901                : new ComponentName(preferred.activityInfo.packageName,
15902                        preferred.activityInfo.name);
15903    }
15904
15905    @Override
15906    public void setApplicationEnabledSetting(String appPackageName,
15907            int newState, int flags, int userId, String callingPackage) {
15908        if (!sUserManager.exists(userId)) return;
15909        if (callingPackage == null) {
15910            callingPackage = Integer.toString(Binder.getCallingUid());
15911        }
15912        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15913    }
15914
15915    @Override
15916    public void setComponentEnabledSetting(ComponentName componentName,
15917            int newState, int flags, int userId) {
15918        if (!sUserManager.exists(userId)) return;
15919        setEnabledSetting(componentName.getPackageName(),
15920                componentName.getClassName(), newState, flags, userId, null);
15921    }
15922
15923    private void setEnabledSetting(final String packageName, String className, int newState,
15924            final int flags, int userId, String callingPackage) {
15925        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15926              || newState == COMPONENT_ENABLED_STATE_ENABLED
15927              || newState == COMPONENT_ENABLED_STATE_DISABLED
15928              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15929              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15930            throw new IllegalArgumentException("Invalid new component state: "
15931                    + newState);
15932        }
15933        PackageSetting pkgSetting;
15934        final int uid = Binder.getCallingUid();
15935        final int permission = mContext.checkCallingOrSelfPermission(
15936                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15937        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15938        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15939        boolean sendNow = false;
15940        boolean isApp = (className == null);
15941        String componentName = isApp ? packageName : className;
15942        int packageUid = -1;
15943        ArrayList<String> components;
15944
15945        // writer
15946        synchronized (mPackages) {
15947            pkgSetting = mSettings.mPackages.get(packageName);
15948            if (pkgSetting == null) {
15949                if (className == null) {
15950                    throw new IllegalArgumentException("Unknown package: " + packageName);
15951                }
15952                throw new IllegalArgumentException(
15953                        "Unknown component: " + packageName + "/" + className);
15954            }
15955            // Allow root and verify that userId is not being specified by a different user
15956            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15957                throw new SecurityException(
15958                        "Permission Denial: attempt to change component state from pid="
15959                        + Binder.getCallingPid()
15960                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15961            }
15962            if (className == null) {
15963                // We're dealing with an application/package level state change
15964                if (pkgSetting.getEnabled(userId) == newState) {
15965                    // Nothing to do
15966                    return;
15967                }
15968                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15969                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15970                    // Don't care about who enables an app.
15971                    callingPackage = null;
15972                }
15973                pkgSetting.setEnabled(newState, userId, callingPackage);
15974                // pkgSetting.pkg.mSetEnabled = newState;
15975            } else {
15976                // We're dealing with a component level state change
15977                // First, verify that this is a valid class name.
15978                PackageParser.Package pkg = pkgSetting.pkg;
15979                if (pkg == null || !pkg.hasComponentClassName(className)) {
15980                    if (pkg != null &&
15981                            pkg.applicationInfo.targetSdkVersion >=
15982                                    Build.VERSION_CODES.JELLY_BEAN) {
15983                        throw new IllegalArgumentException("Component class " + className
15984                                + " does not exist in " + packageName);
15985                    } else {
15986                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15987                                + className + " does not exist in " + packageName);
15988                    }
15989                }
15990                switch (newState) {
15991                case COMPONENT_ENABLED_STATE_ENABLED:
15992                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15993                        return;
15994                    }
15995                    break;
15996                case COMPONENT_ENABLED_STATE_DISABLED:
15997                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15998                        return;
15999                    }
16000                    break;
16001                case COMPONENT_ENABLED_STATE_DEFAULT:
16002                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16003                        return;
16004                    }
16005                    break;
16006                default:
16007                    Slog.e(TAG, "Invalid new component state: " + newState);
16008                    return;
16009                }
16010            }
16011            scheduleWritePackageRestrictionsLocked(userId);
16012            components = mPendingBroadcasts.get(userId, packageName);
16013            final boolean newPackage = components == null;
16014            if (newPackage) {
16015                components = new ArrayList<String>();
16016            }
16017            if (!components.contains(componentName)) {
16018                components.add(componentName);
16019            }
16020            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16021                sendNow = true;
16022                // Purge entry from pending broadcast list if another one exists already
16023                // since we are sending one right away.
16024                mPendingBroadcasts.remove(userId, packageName);
16025            } else {
16026                if (newPackage) {
16027                    mPendingBroadcasts.put(userId, packageName, components);
16028                }
16029                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16030                    // Schedule a message
16031                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16032                }
16033            }
16034        }
16035
16036        long callingId = Binder.clearCallingIdentity();
16037        try {
16038            if (sendNow) {
16039                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16040                sendPackageChangedBroadcast(packageName,
16041                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16042            }
16043        } finally {
16044            Binder.restoreCallingIdentity(callingId);
16045        }
16046    }
16047
16048    private void sendPackageChangedBroadcast(String packageName,
16049            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16050        if (DEBUG_INSTALL)
16051            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16052                    + componentNames);
16053        Bundle extras = new Bundle(4);
16054        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16055        String nameList[] = new String[componentNames.size()];
16056        componentNames.toArray(nameList);
16057        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16058        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16059        extras.putInt(Intent.EXTRA_UID, packageUid);
16060        // If this is not reporting a change of the overall package, then only send it
16061        // to registered receivers.  We don't want to launch a swath of apps for every
16062        // little component state change.
16063        final int flags = !componentNames.contains(packageName)
16064                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16065        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16066                new int[] {UserHandle.getUserId(packageUid)});
16067    }
16068
16069    @Override
16070    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16071        if (!sUserManager.exists(userId)) return;
16072        final int uid = Binder.getCallingUid();
16073        final int permission = mContext.checkCallingOrSelfPermission(
16074                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16075        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16076        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16077        // writer
16078        synchronized (mPackages) {
16079            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16080                    allowedByPermission, uid, userId)) {
16081                scheduleWritePackageRestrictionsLocked(userId);
16082            }
16083        }
16084    }
16085
16086    @Override
16087    public String getInstallerPackageName(String packageName) {
16088        // reader
16089        synchronized (mPackages) {
16090            return mSettings.getInstallerPackageNameLPr(packageName);
16091        }
16092    }
16093
16094    @Override
16095    public int getApplicationEnabledSetting(String packageName, int userId) {
16096        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16097        int uid = Binder.getCallingUid();
16098        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16099        // reader
16100        synchronized (mPackages) {
16101            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16102        }
16103    }
16104
16105    @Override
16106    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16107        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16108        int uid = Binder.getCallingUid();
16109        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16110        // reader
16111        synchronized (mPackages) {
16112            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16113        }
16114    }
16115
16116    @Override
16117    public void enterSafeMode() {
16118        enforceSystemOrRoot("Only the system can request entering safe mode");
16119
16120        if (!mSystemReady) {
16121            mSafeMode = true;
16122        }
16123    }
16124
16125    @Override
16126    public void systemReady() {
16127        mSystemReady = true;
16128
16129        // Read the compatibilty setting when the system is ready.
16130        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16131                mContext.getContentResolver(),
16132                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16133        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16134        if (DEBUG_SETTINGS) {
16135            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16136        }
16137
16138        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16139
16140        synchronized (mPackages) {
16141            // Verify that all of the preferred activity components actually
16142            // exist.  It is possible for applications to be updated and at
16143            // that point remove a previously declared activity component that
16144            // had been set as a preferred activity.  We try to clean this up
16145            // the next time we encounter that preferred activity, but it is
16146            // possible for the user flow to never be able to return to that
16147            // situation so here we do a sanity check to make sure we haven't
16148            // left any junk around.
16149            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16150            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16151                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16152                removed.clear();
16153                for (PreferredActivity pa : pir.filterSet()) {
16154                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16155                        removed.add(pa);
16156                    }
16157                }
16158                if (removed.size() > 0) {
16159                    for (int r=0; r<removed.size(); r++) {
16160                        PreferredActivity pa = removed.get(r);
16161                        Slog.w(TAG, "Removing dangling preferred activity: "
16162                                + pa.mPref.mComponent);
16163                        pir.removeFilter(pa);
16164                    }
16165                    mSettings.writePackageRestrictionsLPr(
16166                            mSettings.mPreferredActivities.keyAt(i));
16167                }
16168            }
16169
16170            for (int userId : UserManagerService.getInstance().getUserIds()) {
16171                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16172                    grantPermissionsUserIds = ArrayUtils.appendInt(
16173                            grantPermissionsUserIds, userId);
16174                }
16175            }
16176        }
16177        sUserManager.systemReady();
16178
16179        // If we upgraded grant all default permissions before kicking off.
16180        for (int userId : grantPermissionsUserIds) {
16181            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16182        }
16183
16184        // Kick off any messages waiting for system ready
16185        if (mPostSystemReadyMessages != null) {
16186            for (Message msg : mPostSystemReadyMessages) {
16187                msg.sendToTarget();
16188            }
16189            mPostSystemReadyMessages = null;
16190        }
16191
16192        // Watch for external volumes that come and go over time
16193        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16194        storage.registerListener(mStorageListener);
16195
16196        mInstallerService.systemReady();
16197        mPackageDexOptimizer.systemReady();
16198
16199        MountServiceInternal mountServiceInternal = LocalServices.getService(
16200                MountServiceInternal.class);
16201        mountServiceInternal.addExternalStoragePolicy(
16202                new MountServiceInternal.ExternalStorageMountPolicy() {
16203            @Override
16204            public int getMountMode(int uid, String packageName) {
16205                if (Process.isIsolated(uid)) {
16206                    return Zygote.MOUNT_EXTERNAL_NONE;
16207                }
16208                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16209                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16210                }
16211                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16212                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16213                }
16214                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16215                    return Zygote.MOUNT_EXTERNAL_READ;
16216                }
16217                return Zygote.MOUNT_EXTERNAL_WRITE;
16218            }
16219
16220            @Override
16221            public boolean hasExternalStorage(int uid, String packageName) {
16222                return true;
16223            }
16224        });
16225    }
16226
16227    @Override
16228    public boolean isSafeMode() {
16229        return mSafeMode;
16230    }
16231
16232    @Override
16233    public boolean hasSystemUidErrors() {
16234        return mHasSystemUidErrors;
16235    }
16236
16237    static String arrayToString(int[] array) {
16238        StringBuffer buf = new StringBuffer(128);
16239        buf.append('[');
16240        if (array != null) {
16241            for (int i=0; i<array.length; i++) {
16242                if (i > 0) buf.append(", ");
16243                buf.append(array[i]);
16244            }
16245        }
16246        buf.append(']');
16247        return buf.toString();
16248    }
16249
16250    static class DumpState {
16251        public static final int DUMP_LIBS = 1 << 0;
16252        public static final int DUMP_FEATURES = 1 << 1;
16253        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16254        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16255        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16256        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16257        public static final int DUMP_PERMISSIONS = 1 << 6;
16258        public static final int DUMP_PACKAGES = 1 << 7;
16259        public static final int DUMP_SHARED_USERS = 1 << 8;
16260        public static final int DUMP_MESSAGES = 1 << 9;
16261        public static final int DUMP_PROVIDERS = 1 << 10;
16262        public static final int DUMP_VERIFIERS = 1 << 11;
16263        public static final int DUMP_PREFERRED = 1 << 12;
16264        public static final int DUMP_PREFERRED_XML = 1 << 13;
16265        public static final int DUMP_KEYSETS = 1 << 14;
16266        public static final int DUMP_VERSION = 1 << 15;
16267        public static final int DUMP_INSTALLS = 1 << 16;
16268        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16269        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16270
16271        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16272
16273        private int mTypes;
16274
16275        private int mOptions;
16276
16277        private boolean mTitlePrinted;
16278
16279        private SharedUserSetting mSharedUser;
16280
16281        public boolean isDumping(int type) {
16282            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16283                return true;
16284            }
16285
16286            return (mTypes & type) != 0;
16287        }
16288
16289        public void setDump(int type) {
16290            mTypes |= type;
16291        }
16292
16293        public boolean isOptionEnabled(int option) {
16294            return (mOptions & option) != 0;
16295        }
16296
16297        public void setOptionEnabled(int option) {
16298            mOptions |= option;
16299        }
16300
16301        public boolean onTitlePrinted() {
16302            final boolean printed = mTitlePrinted;
16303            mTitlePrinted = true;
16304            return printed;
16305        }
16306
16307        public boolean getTitlePrinted() {
16308            return mTitlePrinted;
16309        }
16310
16311        public void setTitlePrinted(boolean enabled) {
16312            mTitlePrinted = enabled;
16313        }
16314
16315        public SharedUserSetting getSharedUser() {
16316            return mSharedUser;
16317        }
16318
16319        public void setSharedUser(SharedUserSetting user) {
16320            mSharedUser = user;
16321        }
16322    }
16323
16324    @Override
16325    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16326            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16327        (new PackageManagerShellCommand(this)).exec(
16328                this, in, out, err, args, resultReceiver);
16329    }
16330
16331    @Override
16332    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16333        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16334                != PackageManager.PERMISSION_GRANTED) {
16335            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16336                    + Binder.getCallingPid()
16337                    + ", uid=" + Binder.getCallingUid()
16338                    + " without permission "
16339                    + android.Manifest.permission.DUMP);
16340            return;
16341        }
16342
16343        DumpState dumpState = new DumpState();
16344        boolean fullPreferred = false;
16345        boolean checkin = false;
16346
16347        String packageName = null;
16348        ArraySet<String> permissionNames = null;
16349
16350        int opti = 0;
16351        while (opti < args.length) {
16352            String opt = args[opti];
16353            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16354                break;
16355            }
16356            opti++;
16357
16358            if ("-a".equals(opt)) {
16359                // Right now we only know how to print all.
16360            } else if ("-h".equals(opt)) {
16361                pw.println("Package manager dump options:");
16362                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16363                pw.println("    --checkin: dump for a checkin");
16364                pw.println("    -f: print details of intent filters");
16365                pw.println("    -h: print this help");
16366                pw.println("  cmd may be one of:");
16367                pw.println("    l[ibraries]: list known shared libraries");
16368                pw.println("    f[eatures]: list device features");
16369                pw.println("    k[eysets]: print known keysets");
16370                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16371                pw.println("    perm[issions]: dump permissions");
16372                pw.println("    permission [name ...]: dump declaration and use of given permission");
16373                pw.println("    pref[erred]: print preferred package settings");
16374                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16375                pw.println("    prov[iders]: dump content providers");
16376                pw.println("    p[ackages]: dump installed packages");
16377                pw.println("    s[hared-users]: dump shared user IDs");
16378                pw.println("    m[essages]: print collected runtime messages");
16379                pw.println("    v[erifiers]: print package verifier info");
16380                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16381                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16382                pw.println("    version: print database version info");
16383                pw.println("    write: write current settings now");
16384                pw.println("    installs: details about install sessions");
16385                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16386                pw.println("    <package.name>: info about given package");
16387                return;
16388            } else if ("--checkin".equals(opt)) {
16389                checkin = true;
16390            } else if ("-f".equals(opt)) {
16391                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16392            } else {
16393                pw.println("Unknown argument: " + opt + "; use -h for help");
16394            }
16395        }
16396
16397        // Is the caller requesting to dump a particular piece of data?
16398        if (opti < args.length) {
16399            String cmd = args[opti];
16400            opti++;
16401            // Is this a package name?
16402            if ("android".equals(cmd) || cmd.contains(".")) {
16403                packageName = cmd;
16404                // When dumping a single package, we always dump all of its
16405                // filter information since the amount of data will be reasonable.
16406                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16407            } else if ("check-permission".equals(cmd)) {
16408                if (opti >= args.length) {
16409                    pw.println("Error: check-permission missing permission argument");
16410                    return;
16411                }
16412                String perm = args[opti];
16413                opti++;
16414                if (opti >= args.length) {
16415                    pw.println("Error: check-permission missing package argument");
16416                    return;
16417                }
16418                String pkg = args[opti];
16419                opti++;
16420                int user = UserHandle.getUserId(Binder.getCallingUid());
16421                if (opti < args.length) {
16422                    try {
16423                        user = Integer.parseInt(args[opti]);
16424                    } catch (NumberFormatException e) {
16425                        pw.println("Error: check-permission user argument is not a number: "
16426                                + args[opti]);
16427                        return;
16428                    }
16429                }
16430                pw.println(checkPermission(perm, pkg, user));
16431                return;
16432            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16433                dumpState.setDump(DumpState.DUMP_LIBS);
16434            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16435                dumpState.setDump(DumpState.DUMP_FEATURES);
16436            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16437                if (opti >= args.length) {
16438                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16439                            | DumpState.DUMP_SERVICE_RESOLVERS
16440                            | DumpState.DUMP_RECEIVER_RESOLVERS
16441                            | DumpState.DUMP_CONTENT_RESOLVERS);
16442                } else {
16443                    while (opti < args.length) {
16444                        String name = args[opti];
16445                        if ("a".equals(name) || "activity".equals(name)) {
16446                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16447                        } else if ("s".equals(name) || "service".equals(name)) {
16448                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16449                        } else if ("r".equals(name) || "receiver".equals(name)) {
16450                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16451                        } else if ("c".equals(name) || "content".equals(name)) {
16452                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16453                        } else {
16454                            pw.println("Error: unknown resolver table type: " + name);
16455                            return;
16456                        }
16457                        opti++;
16458                    }
16459                }
16460            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16461                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16462            } else if ("permission".equals(cmd)) {
16463                if (opti >= args.length) {
16464                    pw.println("Error: permission requires permission name");
16465                    return;
16466                }
16467                permissionNames = new ArraySet<>();
16468                while (opti < args.length) {
16469                    permissionNames.add(args[opti]);
16470                    opti++;
16471                }
16472                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16473                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16474            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16475                dumpState.setDump(DumpState.DUMP_PREFERRED);
16476            } else if ("preferred-xml".equals(cmd)) {
16477                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16478                if (opti < args.length && "--full".equals(args[opti])) {
16479                    fullPreferred = true;
16480                    opti++;
16481                }
16482            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16483                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16484            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16485                dumpState.setDump(DumpState.DUMP_PACKAGES);
16486            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16487                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16488            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16489                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16490            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16491                dumpState.setDump(DumpState.DUMP_MESSAGES);
16492            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16493                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16494            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16495                    || "intent-filter-verifiers".equals(cmd)) {
16496                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16497            } else if ("version".equals(cmd)) {
16498                dumpState.setDump(DumpState.DUMP_VERSION);
16499            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16500                dumpState.setDump(DumpState.DUMP_KEYSETS);
16501            } else if ("installs".equals(cmd)) {
16502                dumpState.setDump(DumpState.DUMP_INSTALLS);
16503            } else if ("write".equals(cmd)) {
16504                synchronized (mPackages) {
16505                    mSettings.writeLPr();
16506                    pw.println("Settings written.");
16507                    return;
16508                }
16509            }
16510        }
16511
16512        if (checkin) {
16513            pw.println("vers,1");
16514        }
16515
16516        // reader
16517        synchronized (mPackages) {
16518            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16519                if (!checkin) {
16520                    if (dumpState.onTitlePrinted())
16521                        pw.println();
16522                    pw.println("Database versions:");
16523                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16524                }
16525            }
16526
16527            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16528                if (!checkin) {
16529                    if (dumpState.onTitlePrinted())
16530                        pw.println();
16531                    pw.println("Verifiers:");
16532                    pw.print("  Required: ");
16533                    pw.print(mRequiredVerifierPackage);
16534                    pw.print(" (uid=");
16535                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16536                            UserHandle.USER_SYSTEM));
16537                    pw.println(")");
16538                } else if (mRequiredVerifierPackage != null) {
16539                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16540                    pw.print(",");
16541                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16542                            UserHandle.USER_SYSTEM));
16543                }
16544            }
16545
16546            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16547                    packageName == null) {
16548                if (mIntentFilterVerifierComponent != null) {
16549                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16550                    if (!checkin) {
16551                        if (dumpState.onTitlePrinted())
16552                            pw.println();
16553                        pw.println("Intent Filter Verifier:");
16554                        pw.print("  Using: ");
16555                        pw.print(verifierPackageName);
16556                        pw.print(" (uid=");
16557                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16558                                UserHandle.USER_SYSTEM));
16559                        pw.println(")");
16560                    } else if (verifierPackageName != null) {
16561                        pw.print("ifv,"); pw.print(verifierPackageName);
16562                        pw.print(",");
16563                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16564                                UserHandle.USER_SYSTEM));
16565                    }
16566                } else {
16567                    pw.println();
16568                    pw.println("No Intent Filter Verifier available!");
16569                }
16570            }
16571
16572            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16573                boolean printedHeader = false;
16574                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16575                while (it.hasNext()) {
16576                    String name = it.next();
16577                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16578                    if (!checkin) {
16579                        if (!printedHeader) {
16580                            if (dumpState.onTitlePrinted())
16581                                pw.println();
16582                            pw.println("Libraries:");
16583                            printedHeader = true;
16584                        }
16585                        pw.print("  ");
16586                    } else {
16587                        pw.print("lib,");
16588                    }
16589                    pw.print(name);
16590                    if (!checkin) {
16591                        pw.print(" -> ");
16592                    }
16593                    if (ent.path != null) {
16594                        if (!checkin) {
16595                            pw.print("(jar) ");
16596                            pw.print(ent.path);
16597                        } else {
16598                            pw.print(",jar,");
16599                            pw.print(ent.path);
16600                        }
16601                    } else {
16602                        if (!checkin) {
16603                            pw.print("(apk) ");
16604                            pw.print(ent.apk);
16605                        } else {
16606                            pw.print(",apk,");
16607                            pw.print(ent.apk);
16608                        }
16609                    }
16610                    pw.println();
16611                }
16612            }
16613
16614            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16615                if (dumpState.onTitlePrinted())
16616                    pw.println();
16617                if (!checkin) {
16618                    pw.println("Features:");
16619                }
16620                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16621                while (it.hasNext()) {
16622                    String name = it.next();
16623                    if (!checkin) {
16624                        pw.print("  ");
16625                    } else {
16626                        pw.print("feat,");
16627                    }
16628                    pw.println(name);
16629                }
16630            }
16631
16632            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16633                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16634                        : "Activity Resolver Table:", "  ", packageName,
16635                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16636                    dumpState.setTitlePrinted(true);
16637                }
16638            }
16639            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16640                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16641                        : "Receiver Resolver Table:", "  ", packageName,
16642                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16643                    dumpState.setTitlePrinted(true);
16644                }
16645            }
16646            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16647                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16648                        : "Service Resolver Table:", "  ", packageName,
16649                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16650                    dumpState.setTitlePrinted(true);
16651                }
16652            }
16653            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16654                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16655                        : "Provider Resolver Table:", "  ", packageName,
16656                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16657                    dumpState.setTitlePrinted(true);
16658                }
16659            }
16660
16661            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16662                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16663                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16664                    int user = mSettings.mPreferredActivities.keyAt(i);
16665                    if (pir.dump(pw,
16666                            dumpState.getTitlePrinted()
16667                                ? "\nPreferred Activities User " + user + ":"
16668                                : "Preferred Activities User " + user + ":", "  ",
16669                            packageName, true, false)) {
16670                        dumpState.setTitlePrinted(true);
16671                    }
16672                }
16673            }
16674
16675            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16676                pw.flush();
16677                FileOutputStream fout = new FileOutputStream(fd);
16678                BufferedOutputStream str = new BufferedOutputStream(fout);
16679                XmlSerializer serializer = new FastXmlSerializer();
16680                try {
16681                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16682                    serializer.startDocument(null, true);
16683                    serializer.setFeature(
16684                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16685                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16686                    serializer.endDocument();
16687                    serializer.flush();
16688                } catch (IllegalArgumentException e) {
16689                    pw.println("Failed writing: " + e);
16690                } catch (IllegalStateException e) {
16691                    pw.println("Failed writing: " + e);
16692                } catch (IOException e) {
16693                    pw.println("Failed writing: " + e);
16694                }
16695            }
16696
16697            if (!checkin
16698                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16699                    && packageName == null) {
16700                pw.println();
16701                int count = mSettings.mPackages.size();
16702                if (count == 0) {
16703                    pw.println("No applications!");
16704                    pw.println();
16705                } else {
16706                    final String prefix = "  ";
16707                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16708                    if (allPackageSettings.size() == 0) {
16709                        pw.println("No domain preferred apps!");
16710                        pw.println();
16711                    } else {
16712                        pw.println("App verification status:");
16713                        pw.println();
16714                        count = 0;
16715                        for (PackageSetting ps : allPackageSettings) {
16716                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16717                            if (ivi == null || ivi.getPackageName() == null) continue;
16718                            pw.println(prefix + "Package: " + ivi.getPackageName());
16719                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16720                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16721                            pw.println();
16722                            count++;
16723                        }
16724                        if (count == 0) {
16725                            pw.println(prefix + "No app verification established.");
16726                            pw.println();
16727                        }
16728                        for (int userId : sUserManager.getUserIds()) {
16729                            pw.println("App linkages for user " + userId + ":");
16730                            pw.println();
16731                            count = 0;
16732                            for (PackageSetting ps : allPackageSettings) {
16733                                final long status = ps.getDomainVerificationStatusForUser(userId);
16734                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16735                                    continue;
16736                                }
16737                                pw.println(prefix + "Package: " + ps.name);
16738                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16739                                String statusStr = IntentFilterVerificationInfo.
16740                                        getStatusStringFromValue(status);
16741                                pw.println(prefix + "Status:  " + statusStr);
16742                                pw.println();
16743                                count++;
16744                            }
16745                            if (count == 0) {
16746                                pw.println(prefix + "No configured app linkages.");
16747                                pw.println();
16748                            }
16749                        }
16750                    }
16751                }
16752            }
16753
16754            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16755                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16756                if (packageName == null && permissionNames == null) {
16757                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16758                        if (iperm == 0) {
16759                            if (dumpState.onTitlePrinted())
16760                                pw.println();
16761                            pw.println("AppOp Permissions:");
16762                        }
16763                        pw.print("  AppOp Permission ");
16764                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16765                        pw.println(":");
16766                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16767                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16768                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16769                        }
16770                    }
16771                }
16772            }
16773
16774            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16775                boolean printedSomething = false;
16776                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16777                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16778                        continue;
16779                    }
16780                    if (!printedSomething) {
16781                        if (dumpState.onTitlePrinted())
16782                            pw.println();
16783                        pw.println("Registered ContentProviders:");
16784                        printedSomething = true;
16785                    }
16786                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16787                    pw.print("    "); pw.println(p.toString());
16788                }
16789                printedSomething = false;
16790                for (Map.Entry<String, PackageParser.Provider> entry :
16791                        mProvidersByAuthority.entrySet()) {
16792                    PackageParser.Provider p = entry.getValue();
16793                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16794                        continue;
16795                    }
16796                    if (!printedSomething) {
16797                        if (dumpState.onTitlePrinted())
16798                            pw.println();
16799                        pw.println("ContentProvider Authorities:");
16800                        printedSomething = true;
16801                    }
16802                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16803                    pw.print("    "); pw.println(p.toString());
16804                    if (p.info != null && p.info.applicationInfo != null) {
16805                        final String appInfo = p.info.applicationInfo.toString();
16806                        pw.print("      applicationInfo="); pw.println(appInfo);
16807                    }
16808                }
16809            }
16810
16811            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16812                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16813            }
16814
16815            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16816                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16817            }
16818
16819            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16820                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16821            }
16822
16823            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16824                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16825            }
16826
16827            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16828                // XXX should handle packageName != null by dumping only install data that
16829                // the given package is involved with.
16830                if (dumpState.onTitlePrinted()) pw.println();
16831                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16832            }
16833
16834            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16835                if (dumpState.onTitlePrinted()) pw.println();
16836                mSettings.dumpReadMessagesLPr(pw, dumpState);
16837
16838                pw.println();
16839                pw.println("Package warning messages:");
16840                BufferedReader in = null;
16841                String line = null;
16842                try {
16843                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16844                    while ((line = in.readLine()) != null) {
16845                        if (line.contains("ignored: updated version")) continue;
16846                        pw.println(line);
16847                    }
16848                } catch (IOException ignored) {
16849                } finally {
16850                    IoUtils.closeQuietly(in);
16851                }
16852            }
16853
16854            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16855                BufferedReader in = null;
16856                String line = null;
16857                try {
16858                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16859                    while ((line = in.readLine()) != null) {
16860                        if (line.contains("ignored: updated version")) continue;
16861                        pw.print("msg,");
16862                        pw.println(line);
16863                    }
16864                } catch (IOException ignored) {
16865                } finally {
16866                    IoUtils.closeQuietly(in);
16867                }
16868            }
16869        }
16870    }
16871
16872    private String dumpDomainString(String packageName) {
16873        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16874        List<IntentFilter> filters = getAllIntentFilters(packageName);
16875
16876        ArraySet<String> result = new ArraySet<>();
16877        if (iviList.size() > 0) {
16878            for (IntentFilterVerificationInfo ivi : iviList) {
16879                for (String host : ivi.getDomains()) {
16880                    result.add(host);
16881                }
16882            }
16883        }
16884        if (filters != null && filters.size() > 0) {
16885            for (IntentFilter filter : filters) {
16886                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16887                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16888                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16889                    result.addAll(filter.getHostsList());
16890                }
16891            }
16892        }
16893
16894        StringBuilder sb = new StringBuilder(result.size() * 16);
16895        for (String domain : result) {
16896            if (sb.length() > 0) sb.append(" ");
16897            sb.append(domain);
16898        }
16899        return sb.toString();
16900    }
16901
16902    // ------- apps on sdcard specific code -------
16903    static final boolean DEBUG_SD_INSTALL = false;
16904
16905    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16906
16907    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16908
16909    private boolean mMediaMounted = false;
16910
16911    static String getEncryptKey() {
16912        try {
16913            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16914                    SD_ENCRYPTION_KEYSTORE_NAME);
16915            if (sdEncKey == null) {
16916                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16917                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16918                if (sdEncKey == null) {
16919                    Slog.e(TAG, "Failed to create encryption keys");
16920                    return null;
16921                }
16922            }
16923            return sdEncKey;
16924        } catch (NoSuchAlgorithmException nsae) {
16925            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16926            return null;
16927        } catch (IOException ioe) {
16928            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16929            return null;
16930        }
16931    }
16932
16933    /*
16934     * Update media status on PackageManager.
16935     */
16936    @Override
16937    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16938        int callingUid = Binder.getCallingUid();
16939        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16940            throw new SecurityException("Media status can only be updated by the system");
16941        }
16942        // reader; this apparently protects mMediaMounted, but should probably
16943        // be a different lock in that case.
16944        synchronized (mPackages) {
16945            Log.i(TAG, "Updating external media status from "
16946                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16947                    + (mediaStatus ? "mounted" : "unmounted"));
16948            if (DEBUG_SD_INSTALL)
16949                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16950                        + ", mMediaMounted=" + mMediaMounted);
16951            if (mediaStatus == mMediaMounted) {
16952                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16953                        : 0, -1);
16954                mHandler.sendMessage(msg);
16955                return;
16956            }
16957            mMediaMounted = mediaStatus;
16958        }
16959        // Queue up an async operation since the package installation may take a
16960        // little while.
16961        mHandler.post(new Runnable() {
16962            public void run() {
16963                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16964            }
16965        });
16966    }
16967
16968    /**
16969     * Called by MountService when the initial ASECs to scan are available.
16970     * Should block until all the ASEC containers are finished being scanned.
16971     */
16972    public void scanAvailableAsecs() {
16973        updateExternalMediaStatusInner(true, false, false);
16974    }
16975
16976    /*
16977     * Collect information of applications on external media, map them against
16978     * existing containers and update information based on current mount status.
16979     * Please note that we always have to report status if reportStatus has been
16980     * set to true especially when unloading packages.
16981     */
16982    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16983            boolean externalStorage) {
16984        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16985        int[] uidArr = EmptyArray.INT;
16986
16987        final String[] list = PackageHelper.getSecureContainerList();
16988        if (ArrayUtils.isEmpty(list)) {
16989            Log.i(TAG, "No secure containers found");
16990        } else {
16991            // Process list of secure containers and categorize them
16992            // as active or stale based on their package internal state.
16993
16994            // reader
16995            synchronized (mPackages) {
16996                for (String cid : list) {
16997                    // Leave stages untouched for now; installer service owns them
16998                    if (PackageInstallerService.isStageName(cid)) continue;
16999
17000                    if (DEBUG_SD_INSTALL)
17001                        Log.i(TAG, "Processing container " + cid);
17002                    String pkgName = getAsecPackageName(cid);
17003                    if (pkgName == null) {
17004                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17005                        continue;
17006                    }
17007                    if (DEBUG_SD_INSTALL)
17008                        Log.i(TAG, "Looking for pkg : " + pkgName);
17009
17010                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17011                    if (ps == null) {
17012                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17013                        continue;
17014                    }
17015
17016                    /*
17017                     * Skip packages that are not external if we're unmounting
17018                     * external storage.
17019                     */
17020                    if (externalStorage && !isMounted && !isExternal(ps)) {
17021                        continue;
17022                    }
17023
17024                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17025                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17026                    // The package status is changed only if the code path
17027                    // matches between settings and the container id.
17028                    if (ps.codePathString != null
17029                            && ps.codePathString.startsWith(args.getCodePath())) {
17030                        if (DEBUG_SD_INSTALL) {
17031                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17032                                    + " at code path: " + ps.codePathString);
17033                        }
17034
17035                        // We do have a valid package installed on sdcard
17036                        processCids.put(args, ps.codePathString);
17037                        final int uid = ps.appId;
17038                        if (uid != -1) {
17039                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17040                        }
17041                    } else {
17042                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17043                                + ps.codePathString);
17044                    }
17045                }
17046            }
17047
17048            Arrays.sort(uidArr);
17049        }
17050
17051        // Process packages with valid entries.
17052        if (isMounted) {
17053            if (DEBUG_SD_INSTALL)
17054                Log.i(TAG, "Loading packages");
17055            loadMediaPackages(processCids, uidArr, externalStorage);
17056            startCleaningPackages();
17057            mInstallerService.onSecureContainersAvailable();
17058        } else {
17059            if (DEBUG_SD_INSTALL)
17060                Log.i(TAG, "Unloading packages");
17061            unloadMediaPackages(processCids, uidArr, reportStatus);
17062        }
17063    }
17064
17065    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17066            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17067        final int size = infos.size();
17068        final String[] packageNames = new String[size];
17069        final int[] packageUids = new int[size];
17070        for (int i = 0; i < size; i++) {
17071            final ApplicationInfo info = infos.get(i);
17072            packageNames[i] = info.packageName;
17073            packageUids[i] = info.uid;
17074        }
17075        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17076                finishedReceiver);
17077    }
17078
17079    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17080            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17081        sendResourcesChangedBroadcast(mediaStatus, replacing,
17082                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17083    }
17084
17085    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17086            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17087        int size = pkgList.length;
17088        if (size > 0) {
17089            // Send broadcasts here
17090            Bundle extras = new Bundle();
17091            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17092            if (uidArr != null) {
17093                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17094            }
17095            if (replacing) {
17096                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17097            }
17098            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17099                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17100            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17101        }
17102    }
17103
17104   /*
17105     * Look at potentially valid container ids from processCids If package
17106     * information doesn't match the one on record or package scanning fails,
17107     * the cid is added to list of removeCids. We currently don't delete stale
17108     * containers.
17109     */
17110    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17111            boolean externalStorage) {
17112        ArrayList<String> pkgList = new ArrayList<String>();
17113        Set<AsecInstallArgs> keys = processCids.keySet();
17114
17115        for (AsecInstallArgs args : keys) {
17116            String codePath = processCids.get(args);
17117            if (DEBUG_SD_INSTALL)
17118                Log.i(TAG, "Loading container : " + args.cid);
17119            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17120            try {
17121                // Make sure there are no container errors first.
17122                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17123                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17124                            + " when installing from sdcard");
17125                    continue;
17126                }
17127                // Check code path here.
17128                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17129                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17130                            + " does not match one in settings " + codePath);
17131                    continue;
17132                }
17133                // Parse package
17134                int parseFlags = mDefParseFlags;
17135                if (args.isExternalAsec()) {
17136                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17137                }
17138                if (args.isFwdLocked()) {
17139                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17140                }
17141
17142                synchronized (mInstallLock) {
17143                    PackageParser.Package pkg = null;
17144                    try {
17145                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17146                    } catch (PackageManagerException e) {
17147                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17148                    }
17149                    // Scan the package
17150                    if (pkg != null) {
17151                        /*
17152                         * TODO why is the lock being held? doPostInstall is
17153                         * called in other places without the lock. This needs
17154                         * to be straightened out.
17155                         */
17156                        // writer
17157                        synchronized (mPackages) {
17158                            retCode = PackageManager.INSTALL_SUCCEEDED;
17159                            pkgList.add(pkg.packageName);
17160                            // Post process args
17161                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17162                                    pkg.applicationInfo.uid);
17163                        }
17164                    } else {
17165                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17166                    }
17167                }
17168
17169            } finally {
17170                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17171                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17172                }
17173            }
17174        }
17175        // writer
17176        synchronized (mPackages) {
17177            // If the platform SDK has changed since the last time we booted,
17178            // we need to re-grant app permission to catch any new ones that
17179            // appear. This is really a hack, and means that apps can in some
17180            // cases get permissions that the user didn't initially explicitly
17181            // allow... it would be nice to have some better way to handle
17182            // this situation.
17183            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17184                    : mSettings.getInternalVersion();
17185            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17186                    : StorageManager.UUID_PRIVATE_INTERNAL;
17187
17188            int updateFlags = UPDATE_PERMISSIONS_ALL;
17189            if (ver.sdkVersion != mSdkVersion) {
17190                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17191                        + mSdkVersion + "; regranting permissions for external");
17192                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17193            }
17194            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17195
17196            // Yay, everything is now upgraded
17197            ver.forceCurrent();
17198
17199            // can downgrade to reader
17200            // Persist settings
17201            mSettings.writeLPr();
17202        }
17203        // Send a broadcast to let everyone know we are done processing
17204        if (pkgList.size() > 0) {
17205            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17206        }
17207    }
17208
17209   /*
17210     * Utility method to unload a list of specified containers
17211     */
17212    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17213        // Just unmount all valid containers.
17214        for (AsecInstallArgs arg : cidArgs) {
17215            synchronized (mInstallLock) {
17216                arg.doPostDeleteLI(false);
17217           }
17218       }
17219   }
17220
17221    /*
17222     * Unload packages mounted on external media. This involves deleting package
17223     * data from internal structures, sending broadcasts about disabled packages,
17224     * gc'ing to free up references, unmounting all secure containers
17225     * corresponding to packages on external media, and posting a
17226     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17227     * that we always have to post this message if status has been requested no
17228     * matter what.
17229     */
17230    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17231            final boolean reportStatus) {
17232        if (DEBUG_SD_INSTALL)
17233            Log.i(TAG, "unloading media packages");
17234        ArrayList<String> pkgList = new ArrayList<String>();
17235        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17236        final Set<AsecInstallArgs> keys = processCids.keySet();
17237        for (AsecInstallArgs args : keys) {
17238            String pkgName = args.getPackageName();
17239            if (DEBUG_SD_INSTALL)
17240                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17241            // Delete package internally
17242            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17243            synchronized (mInstallLock) {
17244                boolean res = deletePackageLI(pkgName, null, false, null, null,
17245                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17246                if (res) {
17247                    pkgList.add(pkgName);
17248                } else {
17249                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17250                    failedList.add(args);
17251                }
17252            }
17253        }
17254
17255        // reader
17256        synchronized (mPackages) {
17257            // We didn't update the settings after removing each package;
17258            // write them now for all packages.
17259            mSettings.writeLPr();
17260        }
17261
17262        // We have to absolutely send UPDATED_MEDIA_STATUS only
17263        // after confirming that all the receivers processed the ordered
17264        // broadcast when packages get disabled, force a gc to clean things up.
17265        // and unload all the containers.
17266        if (pkgList.size() > 0) {
17267            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17268                    new IIntentReceiver.Stub() {
17269                public void performReceive(Intent intent, int resultCode, String data,
17270                        Bundle extras, boolean ordered, boolean sticky,
17271                        int sendingUser) throws RemoteException {
17272                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17273                            reportStatus ? 1 : 0, 1, keys);
17274                    mHandler.sendMessage(msg);
17275                }
17276            });
17277        } else {
17278            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17279                    keys);
17280            mHandler.sendMessage(msg);
17281        }
17282    }
17283
17284    private void loadPrivatePackages(final VolumeInfo vol) {
17285        mHandler.post(new Runnable() {
17286            @Override
17287            public void run() {
17288                loadPrivatePackagesInner(vol);
17289            }
17290        });
17291    }
17292
17293    private void loadPrivatePackagesInner(VolumeInfo vol) {
17294        final String volumeUuid = vol.fsUuid;
17295        if (TextUtils.isEmpty(volumeUuid)) {
17296            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17297            return;
17298        }
17299
17300        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17301        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17302
17303        final VersionInfo ver;
17304        final List<PackageSetting> packages;
17305        synchronized (mPackages) {
17306            ver = mSettings.findOrCreateVersion(volumeUuid);
17307            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17308        }
17309
17310        // TODO: introduce a new concept similar to "frozen" to prevent these
17311        // apps from being launched until after data has been fully reconciled
17312        for (PackageSetting ps : packages) {
17313            synchronized (mInstallLock) {
17314                final PackageParser.Package pkg;
17315                try {
17316                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17317                    loaded.add(pkg.applicationInfo);
17318
17319                } catch (PackageManagerException e) {
17320                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17321                }
17322
17323                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17324                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17325                }
17326            }
17327        }
17328
17329        // Reconcile app data for all started/unlocked users
17330        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17331        final UserManager um = mContext.getSystemService(UserManager.class);
17332        for (UserInfo user : um.getUsers()) {
17333            final int flags;
17334            if (um.isUserUnlocked(user.id)) {
17335                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17336            } else if (um.isUserRunning(user.id)) {
17337                flags = StorageManager.FLAG_STORAGE_DE;
17338            } else {
17339                continue;
17340            }
17341
17342            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17343            reconcileAppsData(volumeUuid, user.id, flags);
17344        }
17345
17346        synchronized (mPackages) {
17347            int updateFlags = UPDATE_PERMISSIONS_ALL;
17348            if (ver.sdkVersion != mSdkVersion) {
17349                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17350                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17351                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17352            }
17353            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17354
17355            // Yay, everything is now upgraded
17356            ver.forceCurrent();
17357
17358            mSettings.writeLPr();
17359        }
17360
17361        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17362        sendResourcesChangedBroadcast(true, false, loaded, null);
17363    }
17364
17365    private void unloadPrivatePackages(final VolumeInfo vol) {
17366        mHandler.post(new Runnable() {
17367            @Override
17368            public void run() {
17369                unloadPrivatePackagesInner(vol);
17370            }
17371        });
17372    }
17373
17374    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17375        final String volumeUuid = vol.fsUuid;
17376        if (TextUtils.isEmpty(volumeUuid)) {
17377            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17378            return;
17379        }
17380
17381        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17382        synchronized (mInstallLock) {
17383        synchronized (mPackages) {
17384            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17385            for (PackageSetting ps : packages) {
17386                if (ps.pkg == null) continue;
17387
17388                final ApplicationInfo info = ps.pkg.applicationInfo;
17389                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17390                if (deletePackageLI(ps.name, null, false, null, null,
17391                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17392                    unloaded.add(info);
17393                } else {
17394                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17395                }
17396            }
17397
17398            mSettings.writeLPr();
17399        }
17400        }
17401
17402        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17403        sendResourcesChangedBroadcast(false, false, unloaded, null);
17404    }
17405
17406    /**
17407     * Examine all users present on given mounted volume, and destroy data
17408     * belonging to users that are no longer valid, or whose user ID has been
17409     * recycled.
17410     */
17411    private void reconcileUsers(String volumeUuid) {
17412        final File[] files = FileUtils
17413                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
17414        for (File file : files) {
17415            if (!file.isDirectory()) continue;
17416
17417            final int userId;
17418            final UserInfo info;
17419            try {
17420                userId = Integer.parseInt(file.getName());
17421                info = sUserManager.getUserInfo(userId);
17422            } catch (NumberFormatException e) {
17423                Slog.w(TAG, "Invalid user directory " + file);
17424                continue;
17425            }
17426
17427            boolean destroyUser = false;
17428            if (info == null) {
17429                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17430                        + " because no matching user was found");
17431                destroyUser = true;
17432            } else {
17433                try {
17434                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17435                } catch (IOException e) {
17436                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17437                            + " because we failed to enforce serial number: " + e);
17438                    destroyUser = true;
17439                }
17440            }
17441
17442            if (destroyUser) {
17443                synchronized (mInstallLock) {
17444                    try {
17445                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17446                    } catch (InstallerException e) {
17447                        Slog.w(TAG, "Failed to clean up user dirs", e);
17448                    }
17449                }
17450            }
17451        }
17452    }
17453
17454    private void assertPackageKnown(String volumeUuid, String packageName)
17455            throws PackageManagerException {
17456        synchronized (mPackages) {
17457            final PackageSetting ps = mSettings.mPackages.get(packageName);
17458            if (ps == null) {
17459                throw new PackageManagerException("Package " + packageName + " is unknown");
17460            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17461                throw new PackageManagerException(
17462                        "Package " + packageName + " found on unknown volume " + volumeUuid
17463                                + "; expected volume " + ps.volumeUuid);
17464            }
17465        }
17466    }
17467
17468    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17469            throws PackageManagerException {
17470        synchronized (mPackages) {
17471            final PackageSetting ps = mSettings.mPackages.get(packageName);
17472            if (ps == null) {
17473                throw new PackageManagerException("Package " + packageName + " is unknown");
17474            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17475                throw new PackageManagerException(
17476                        "Package " + packageName + " found on unknown volume " + volumeUuid
17477                                + "; expected volume " + ps.volumeUuid);
17478            } else if (!ps.getInstalled(userId)) {
17479                throw new PackageManagerException(
17480                        "Package " + packageName + " not installed for user " + userId);
17481            }
17482        }
17483    }
17484
17485    /**
17486     * Examine all apps present on given mounted volume, and destroy apps that
17487     * aren't expected, either due to uninstallation or reinstallation on
17488     * another volume.
17489     */
17490    private void reconcileApps(String volumeUuid) {
17491        final File[] files = FileUtils
17492                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17493        for (File file : files) {
17494            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17495                    && !PackageInstallerService.isStageName(file.getName());
17496            if (!isPackage) {
17497                // Ignore entries which are not packages
17498                continue;
17499            }
17500
17501            try {
17502                final PackageLite pkg = PackageParser.parsePackageLite(file,
17503                        PackageParser.PARSE_MUST_BE_APK);
17504                assertPackageKnown(volumeUuid, pkg.packageName);
17505
17506            } catch (PackageParserException | PackageManagerException e) {
17507                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17508                synchronized (mInstallLock) {
17509                    removeCodePathLI(file);
17510                }
17511            }
17512        }
17513    }
17514
17515    /**
17516     * Reconcile all app data for the given user.
17517     * <p>
17518     * Verifies that directories exist and that ownership and labeling is
17519     * correct for all installed apps on all mounted volumes.
17520     */
17521    void reconcileAppsData(int userId, int flags) {
17522        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17523        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17524            final String volumeUuid = vol.getFsUuid();
17525            reconcileAppsData(volumeUuid, userId, flags);
17526        }
17527    }
17528
17529    /**
17530     * Reconcile all app data on given mounted volume.
17531     * <p>
17532     * Destroys app data that isn't expected, either due to uninstallation or
17533     * reinstallation on another volume.
17534     * <p>
17535     * Verifies that directories exist and that ownership and labeling is
17536     * correct for all installed apps.
17537     */
17538    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17539        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17540                + Integer.toHexString(flags));
17541
17542        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17543        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17544
17545        boolean restoreconNeeded = false;
17546
17547        // First look for stale data that doesn't belong, and check if things
17548        // have changed since we did our last restorecon
17549        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17550            if (!isUserKeyUnlocked(userId)) {
17551                throw new RuntimeException(
17552                        "Yikes, someone asked us to reconcile CE storage while " + userId
17553                                + " was still locked; this would have caused massive data loss!");
17554            }
17555
17556            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17557
17558            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17559            for (File file : files) {
17560                final String packageName = file.getName();
17561                try {
17562                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17563                } catch (PackageManagerException e) {
17564                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17565                    synchronized (mInstallLock) {
17566                        destroyAppDataLI(volumeUuid, packageName, userId,
17567                                StorageManager.FLAG_STORAGE_CE);
17568                    }
17569                }
17570            }
17571        }
17572        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17573            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17574
17575            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17576            for (File file : files) {
17577                final String packageName = file.getName();
17578                try {
17579                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17580                } catch (PackageManagerException e) {
17581                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17582                    synchronized (mInstallLock) {
17583                        destroyAppDataLI(volumeUuid, packageName, userId,
17584                                StorageManager.FLAG_STORAGE_DE);
17585                    }
17586                }
17587            }
17588        }
17589
17590        // Ensure that data directories are ready to roll for all packages
17591        // installed for this volume and user
17592        final List<PackageSetting> packages;
17593        synchronized (mPackages) {
17594            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17595        }
17596        int preparedCount = 0;
17597        for (PackageSetting ps : packages) {
17598            final String packageName = ps.name;
17599            if (ps.pkg == null) {
17600                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17601                // TODO: might be due to legacy ASEC apps; we should circle back
17602                // and reconcile again once they're scanned
17603                continue;
17604            }
17605
17606            if (ps.getInstalled(userId)) {
17607                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17608                preparedCount++;
17609            }
17610        }
17611
17612        if (restoreconNeeded) {
17613            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17614                SELinuxMMAC.setRestoreconDone(ceDir);
17615            }
17616            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17617                SELinuxMMAC.setRestoreconDone(deDir);
17618            }
17619        }
17620
17621        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17622                + " packages; restoreconNeeded was " + restoreconNeeded);
17623    }
17624
17625    /**
17626     * Prepare app data for the given app just after it was installed or
17627     * upgraded. This method carefully only touches users that it's installed
17628     * for, and it forces a restorecon to handle any seinfo changes.
17629     * <p>
17630     * Verifies that directories exist and that ownership and labeling is
17631     * correct for all installed apps. If there is an ownership mismatch, it
17632     * will try recovering system apps by wiping data; third-party app data is
17633     * left intact.
17634     */
17635    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17636        prepareAppDataAfterInstallInternal(pkg);
17637        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17638        for (int i = 0; i < childCount; i++) {
17639            PackageParser.Package childPackage = pkg.childPackages.get(i);
17640            prepareAppDataAfterInstallInternal(childPackage);
17641        }
17642    }
17643
17644    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17645        final PackageSetting ps;
17646        synchronized (mPackages) {
17647            ps = mSettings.mPackages.get(pkg.packageName);
17648        }
17649
17650        final UserManager um = mContext.getSystemService(UserManager.class);
17651        for (UserInfo user : um.getUsers()) {
17652            final int flags;
17653            if (um.isUserUnlocked(user.id)) {
17654                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17655            } else if (um.isUserRunning(user.id)) {
17656                flags = StorageManager.FLAG_STORAGE_DE;
17657            } else {
17658                continue;
17659            }
17660
17661            if (ps.getInstalled(user.id)) {
17662                // Whenever an app changes, force a restorecon of its data
17663                // TODO: when user data is locked, mark that we're still dirty
17664                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17665            }
17666        }
17667    }
17668
17669    /**
17670     * Prepare app data for the given app.
17671     * <p>
17672     * Verifies that directories exist and that ownership and labeling is
17673     * correct for all installed apps. If there is an ownership mismatch, this
17674     * will try recovering system apps by wiping data; third-party app data is
17675     * left intact.
17676     */
17677    private void prepareAppData(String volumeUuid, int userId, int flags,
17678            PackageParser.Package pkg, boolean restoreconNeeded) {
17679        if (DEBUG_APP_DATA) {
17680            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17681                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17682        }
17683
17684        final String packageName = pkg.packageName;
17685        final ApplicationInfo app = pkg.applicationInfo;
17686        final int appId = UserHandle.getAppId(app.uid);
17687
17688        Preconditions.checkNotNull(app.seinfo);
17689
17690        synchronized (mInstallLock) {
17691            try {
17692                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17693                        appId, app.seinfo, app.targetSdkVersion);
17694            } catch (InstallerException e) {
17695                if (app.isSystemApp()) {
17696                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17697                            + ", but trying to recover: " + e);
17698                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17699                    try {
17700                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17701                                appId, app.seinfo, app.targetSdkVersion);
17702                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17703                    } catch (InstallerException e2) {
17704                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17705                    }
17706                } else {
17707                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17708                }
17709            }
17710
17711            if (restoreconNeeded) {
17712                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17713            }
17714
17715            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17716                // Create a native library symlink only if we have native libraries
17717                // and if the native libraries are 32 bit libraries. We do not provide
17718                // this symlink for 64 bit libraries.
17719                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17720                    final String nativeLibPath = app.nativeLibraryDir;
17721                    try {
17722                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17723                                nativeLibPath, userId);
17724                    } catch (InstallerException e) {
17725                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17726                    }
17727                }
17728            }
17729        }
17730    }
17731
17732    private void unfreezePackage(String packageName) {
17733        synchronized (mPackages) {
17734            final PackageSetting ps = mSettings.mPackages.get(packageName);
17735            if (ps != null) {
17736                ps.frozen = false;
17737            }
17738        }
17739    }
17740
17741    @Override
17742    public int movePackage(final String packageName, final String volumeUuid) {
17743        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17744
17745        final int moveId = mNextMoveId.getAndIncrement();
17746        mHandler.post(new Runnable() {
17747            @Override
17748            public void run() {
17749                try {
17750                    movePackageInternal(packageName, volumeUuid, moveId);
17751                } catch (PackageManagerException e) {
17752                    Slog.w(TAG, "Failed to move " + packageName, e);
17753                    mMoveCallbacks.notifyStatusChanged(moveId,
17754                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17755                }
17756            }
17757        });
17758        return moveId;
17759    }
17760
17761    private void movePackageInternal(final String packageName, final String volumeUuid,
17762            final int moveId) throws PackageManagerException {
17763        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17764        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17765        final PackageManager pm = mContext.getPackageManager();
17766
17767        final boolean currentAsec;
17768        final String currentVolumeUuid;
17769        final File codeFile;
17770        final String installerPackageName;
17771        final String packageAbiOverride;
17772        final int appId;
17773        final String seinfo;
17774        final String label;
17775        final int targetSdkVersion;
17776
17777        // reader
17778        synchronized (mPackages) {
17779            final PackageParser.Package pkg = mPackages.get(packageName);
17780            final PackageSetting ps = mSettings.mPackages.get(packageName);
17781            if (pkg == null || ps == null) {
17782                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17783            }
17784
17785            if (pkg.applicationInfo.isSystemApp()) {
17786                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17787                        "Cannot move system application");
17788            }
17789
17790            if (pkg.applicationInfo.isExternalAsec()) {
17791                currentAsec = true;
17792                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17793            } else if (pkg.applicationInfo.isForwardLocked()) {
17794                currentAsec = true;
17795                currentVolumeUuid = "forward_locked";
17796            } else {
17797                currentAsec = false;
17798                currentVolumeUuid = ps.volumeUuid;
17799
17800                final File probe = new File(pkg.codePath);
17801                final File probeOat = new File(probe, "oat");
17802                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17803                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17804                            "Move only supported for modern cluster style installs");
17805                }
17806            }
17807
17808            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17809                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17810                        "Package already moved to " + volumeUuid);
17811            }
17812
17813            if (ps.frozen) {
17814                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17815                        "Failed to move already frozen package");
17816            }
17817            ps.frozen = true;
17818
17819            codeFile = new File(pkg.codePath);
17820            installerPackageName = ps.installerPackageName;
17821            packageAbiOverride = ps.cpuAbiOverrideString;
17822            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17823            seinfo = pkg.applicationInfo.seinfo;
17824            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17825            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17826        }
17827
17828        // Now that we're guarded by frozen state, kill app during move
17829        final long token = Binder.clearCallingIdentity();
17830        try {
17831            killApplication(packageName, appId, "move pkg");
17832        } finally {
17833            Binder.restoreCallingIdentity(token);
17834        }
17835
17836        final Bundle extras = new Bundle();
17837        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17838        extras.putString(Intent.EXTRA_TITLE, label);
17839        mMoveCallbacks.notifyCreated(moveId, extras);
17840
17841        int installFlags;
17842        final boolean moveCompleteApp;
17843        final File measurePath;
17844
17845        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17846            installFlags = INSTALL_INTERNAL;
17847            moveCompleteApp = !currentAsec;
17848            measurePath = Environment.getDataAppDirectory(volumeUuid);
17849        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17850            installFlags = INSTALL_EXTERNAL;
17851            moveCompleteApp = false;
17852            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17853        } else {
17854            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17855            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17856                    || !volume.isMountedWritable()) {
17857                unfreezePackage(packageName);
17858                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17859                        "Move location not mounted private volume");
17860            }
17861
17862            Preconditions.checkState(!currentAsec);
17863
17864            installFlags = INSTALL_INTERNAL;
17865            moveCompleteApp = true;
17866            measurePath = Environment.getDataAppDirectory(volumeUuid);
17867        }
17868
17869        final PackageStats stats = new PackageStats(null, -1);
17870        synchronized (mInstaller) {
17871            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17872                unfreezePackage(packageName);
17873                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17874                        "Failed to measure package size");
17875            }
17876        }
17877
17878        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17879                + stats.dataSize);
17880
17881        final long startFreeBytes = measurePath.getFreeSpace();
17882        final long sizeBytes;
17883        if (moveCompleteApp) {
17884            sizeBytes = stats.codeSize + stats.dataSize;
17885        } else {
17886            sizeBytes = stats.codeSize;
17887        }
17888
17889        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17890            unfreezePackage(packageName);
17891            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17892                    "Not enough free space to move");
17893        }
17894
17895        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17896
17897        final CountDownLatch installedLatch = new CountDownLatch(1);
17898        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17899            @Override
17900            public void onUserActionRequired(Intent intent) throws RemoteException {
17901                throw new IllegalStateException();
17902            }
17903
17904            @Override
17905            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17906                    Bundle extras) throws RemoteException {
17907                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17908                        + PackageManager.installStatusToString(returnCode, msg));
17909
17910                installedLatch.countDown();
17911
17912                // Regardless of success or failure of the move operation,
17913                // always unfreeze the package
17914                unfreezePackage(packageName);
17915
17916                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17917                switch (status) {
17918                    case PackageInstaller.STATUS_SUCCESS:
17919                        mMoveCallbacks.notifyStatusChanged(moveId,
17920                                PackageManager.MOVE_SUCCEEDED);
17921                        break;
17922                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17923                        mMoveCallbacks.notifyStatusChanged(moveId,
17924                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17925                        break;
17926                    default:
17927                        mMoveCallbacks.notifyStatusChanged(moveId,
17928                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17929                        break;
17930                }
17931            }
17932        };
17933
17934        final MoveInfo move;
17935        if (moveCompleteApp) {
17936            // Kick off a thread to report progress estimates
17937            new Thread() {
17938                @Override
17939                public void run() {
17940                    while (true) {
17941                        try {
17942                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17943                                break;
17944                            }
17945                        } catch (InterruptedException ignored) {
17946                        }
17947
17948                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17949                        final int progress = 10 + (int) MathUtils.constrain(
17950                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17951                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17952                    }
17953                }
17954            }.start();
17955
17956            final String dataAppName = codeFile.getName();
17957            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17958                    dataAppName, appId, seinfo, targetSdkVersion);
17959        } else {
17960            move = null;
17961        }
17962
17963        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17964
17965        final Message msg = mHandler.obtainMessage(INIT_COPY);
17966        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17967        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17968                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17969        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17970        msg.obj = params;
17971
17972        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17973                System.identityHashCode(msg.obj));
17974        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17975                System.identityHashCode(msg.obj));
17976
17977        mHandler.sendMessage(msg);
17978    }
17979
17980    @Override
17981    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17982        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17983
17984        final int realMoveId = mNextMoveId.getAndIncrement();
17985        final Bundle extras = new Bundle();
17986        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17987        mMoveCallbacks.notifyCreated(realMoveId, extras);
17988
17989        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17990            @Override
17991            public void onCreated(int moveId, Bundle extras) {
17992                // Ignored
17993            }
17994
17995            @Override
17996            public void onStatusChanged(int moveId, int status, long estMillis) {
17997                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17998            }
17999        };
18000
18001        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18002        storage.setPrimaryStorageUuid(volumeUuid, callback);
18003        return realMoveId;
18004    }
18005
18006    @Override
18007    public int getMoveStatus(int moveId) {
18008        mContext.enforceCallingOrSelfPermission(
18009                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18010        return mMoveCallbacks.mLastStatus.get(moveId);
18011    }
18012
18013    @Override
18014    public void registerMoveCallback(IPackageMoveObserver callback) {
18015        mContext.enforceCallingOrSelfPermission(
18016                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18017        mMoveCallbacks.register(callback);
18018    }
18019
18020    @Override
18021    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18022        mContext.enforceCallingOrSelfPermission(
18023                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18024        mMoveCallbacks.unregister(callback);
18025    }
18026
18027    @Override
18028    public boolean setInstallLocation(int loc) {
18029        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18030                null);
18031        if (getInstallLocation() == loc) {
18032            return true;
18033        }
18034        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18035                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18036            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18037                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18038            return true;
18039        }
18040        return false;
18041   }
18042
18043    @Override
18044    public int getInstallLocation() {
18045        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18046                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18047                PackageHelper.APP_INSTALL_AUTO);
18048    }
18049
18050    /** Called by UserManagerService */
18051    void cleanUpUser(UserManagerService userManager, int userHandle) {
18052        synchronized (mPackages) {
18053            mDirtyUsers.remove(userHandle);
18054            mUserNeedsBadging.delete(userHandle);
18055            mSettings.removeUserLPw(userHandle);
18056            mPendingBroadcasts.remove(userHandle);
18057            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18058        }
18059        synchronized (mInstallLock) {
18060            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18061            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18062                final String volumeUuid = vol.getFsUuid();
18063                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18064                try {
18065                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18066                } catch (InstallerException e) {
18067                    Slog.w(TAG, "Failed to remove user data", e);
18068                }
18069            }
18070            synchronized (mPackages) {
18071                removeUnusedPackagesLILPw(userManager, userHandle);
18072            }
18073        }
18074    }
18075
18076    /**
18077     * We're removing userHandle and would like to remove any downloaded packages
18078     * that are no longer in use by any other user.
18079     * @param userHandle the user being removed
18080     */
18081    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18082        final boolean DEBUG_CLEAN_APKS = false;
18083        int [] users = userManager.getUserIds();
18084        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18085        while (psit.hasNext()) {
18086            PackageSetting ps = psit.next();
18087            if (ps.pkg == null) {
18088                continue;
18089            }
18090            final String packageName = ps.pkg.packageName;
18091            // Skip over if system app
18092            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18093                continue;
18094            }
18095            if (DEBUG_CLEAN_APKS) {
18096                Slog.i(TAG, "Checking package " + packageName);
18097            }
18098            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18099            if (keep) {
18100                if (DEBUG_CLEAN_APKS) {
18101                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18102                }
18103            } else {
18104                for (int i = 0; i < users.length; i++) {
18105                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18106                        keep = true;
18107                        if (DEBUG_CLEAN_APKS) {
18108                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18109                                    + users[i]);
18110                        }
18111                        break;
18112                    }
18113                }
18114            }
18115            if (!keep) {
18116                if (DEBUG_CLEAN_APKS) {
18117                    Slog.i(TAG, "  Removing package " + packageName);
18118                }
18119                mHandler.post(new Runnable() {
18120                    public void run() {
18121                        deletePackageX(packageName, userHandle, 0);
18122                    } //end run
18123                });
18124            }
18125        }
18126    }
18127
18128    /** Called by UserManagerService */
18129    void createNewUser(int userHandle) {
18130        synchronized (mInstallLock) {
18131            try {
18132                mInstaller.createUserConfig(userHandle);
18133            } catch (InstallerException e) {
18134                Slog.w(TAG, "Failed to create user config", e);
18135            }
18136            mSettings.createNewUserLI(this, mInstaller, userHandle);
18137        }
18138        synchronized (mPackages) {
18139            applyFactoryDefaultBrowserLPw(userHandle);
18140            primeDomainVerificationsLPw(userHandle);
18141        }
18142    }
18143
18144    void newUserCreated(final int userHandle) {
18145        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18146        // If permission review for legacy apps is required, we represent
18147        // dagerous permissions for such apps as always granted runtime
18148        // permissions to keep per user flag state whether review is needed.
18149        // Hence, if a new user is added we have to propagate dangerous
18150        // permission grants for these legacy apps.
18151        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18152            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18153                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18154        }
18155    }
18156
18157    @Override
18158    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18159        mContext.enforceCallingOrSelfPermission(
18160                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18161                "Only package verification agents can read the verifier device identity");
18162
18163        synchronized (mPackages) {
18164            return mSettings.getVerifierDeviceIdentityLPw();
18165        }
18166    }
18167
18168    @Override
18169    public void setPermissionEnforced(String permission, boolean enforced) {
18170        // TODO: Now that we no longer change GID for storage, this should to away.
18171        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18172                "setPermissionEnforced");
18173        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18174            synchronized (mPackages) {
18175                if (mSettings.mReadExternalStorageEnforced == null
18176                        || mSettings.mReadExternalStorageEnforced != enforced) {
18177                    mSettings.mReadExternalStorageEnforced = enforced;
18178                    mSettings.writeLPr();
18179                }
18180            }
18181            // kill any non-foreground processes so we restart them and
18182            // grant/revoke the GID.
18183            final IActivityManager am = ActivityManagerNative.getDefault();
18184            if (am != null) {
18185                final long token = Binder.clearCallingIdentity();
18186                try {
18187                    am.killProcessesBelowForeground("setPermissionEnforcement");
18188                } catch (RemoteException e) {
18189                } finally {
18190                    Binder.restoreCallingIdentity(token);
18191                }
18192            }
18193        } else {
18194            throw new IllegalArgumentException("No selective enforcement for " + permission);
18195        }
18196    }
18197
18198    @Override
18199    @Deprecated
18200    public boolean isPermissionEnforced(String permission) {
18201        return true;
18202    }
18203
18204    @Override
18205    public boolean isStorageLow() {
18206        final long token = Binder.clearCallingIdentity();
18207        try {
18208            final DeviceStorageMonitorInternal
18209                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18210            if (dsm != null) {
18211                return dsm.isMemoryLow();
18212            } else {
18213                return false;
18214            }
18215        } finally {
18216            Binder.restoreCallingIdentity(token);
18217        }
18218    }
18219
18220    @Override
18221    public IPackageInstaller getPackageInstaller() {
18222        return mInstallerService;
18223    }
18224
18225    private boolean userNeedsBadging(int userId) {
18226        int index = mUserNeedsBadging.indexOfKey(userId);
18227        if (index < 0) {
18228            final UserInfo userInfo;
18229            final long token = Binder.clearCallingIdentity();
18230            try {
18231                userInfo = sUserManager.getUserInfo(userId);
18232            } finally {
18233                Binder.restoreCallingIdentity(token);
18234            }
18235            final boolean b;
18236            if (userInfo != null && userInfo.isManagedProfile()) {
18237                b = true;
18238            } else {
18239                b = false;
18240            }
18241            mUserNeedsBadging.put(userId, b);
18242            return b;
18243        }
18244        return mUserNeedsBadging.valueAt(index);
18245    }
18246
18247    @Override
18248    public KeySet getKeySetByAlias(String packageName, String alias) {
18249        if (packageName == null || alias == null) {
18250            return null;
18251        }
18252        synchronized(mPackages) {
18253            final PackageParser.Package pkg = mPackages.get(packageName);
18254            if (pkg == null) {
18255                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18256                throw new IllegalArgumentException("Unknown package: " + packageName);
18257            }
18258            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18259            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18260        }
18261    }
18262
18263    @Override
18264    public KeySet getSigningKeySet(String packageName) {
18265        if (packageName == null) {
18266            return null;
18267        }
18268        synchronized(mPackages) {
18269            final PackageParser.Package pkg = mPackages.get(packageName);
18270            if (pkg == null) {
18271                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18272                throw new IllegalArgumentException("Unknown package: " + packageName);
18273            }
18274            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18275                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18276                throw new SecurityException("May not access signing KeySet of other apps.");
18277            }
18278            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18279            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18280        }
18281    }
18282
18283    @Override
18284    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18285        if (packageName == null || ks == null) {
18286            return false;
18287        }
18288        synchronized(mPackages) {
18289            final PackageParser.Package pkg = mPackages.get(packageName);
18290            if (pkg == null) {
18291                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18292                throw new IllegalArgumentException("Unknown package: " + packageName);
18293            }
18294            IBinder ksh = ks.getToken();
18295            if (ksh instanceof KeySetHandle) {
18296                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18297                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18298            }
18299            return false;
18300        }
18301    }
18302
18303    @Override
18304    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18305        if (packageName == null || ks == null) {
18306            return false;
18307        }
18308        synchronized(mPackages) {
18309            final PackageParser.Package pkg = mPackages.get(packageName);
18310            if (pkg == null) {
18311                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18312                throw new IllegalArgumentException("Unknown package: " + packageName);
18313            }
18314            IBinder ksh = ks.getToken();
18315            if (ksh instanceof KeySetHandle) {
18316                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18317                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18318            }
18319            return false;
18320        }
18321    }
18322
18323    private void deletePackageIfUnusedLPr(final String packageName) {
18324        PackageSetting ps = mSettings.mPackages.get(packageName);
18325        if (ps == null) {
18326            return;
18327        }
18328        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18329            // TODO Implement atomic delete if package is unused
18330            // It is currently possible that the package will be deleted even if it is installed
18331            // after this method returns.
18332            mHandler.post(new Runnable() {
18333                public void run() {
18334                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18335                }
18336            });
18337        }
18338    }
18339
18340    /**
18341     * Check and throw if the given before/after packages would be considered a
18342     * downgrade.
18343     */
18344    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18345            throws PackageManagerException {
18346        if (after.versionCode < before.mVersionCode) {
18347            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18348                    "Update version code " + after.versionCode + " is older than current "
18349                    + before.mVersionCode);
18350        } else if (after.versionCode == before.mVersionCode) {
18351            if (after.baseRevisionCode < before.baseRevisionCode) {
18352                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18353                        "Update base revision code " + after.baseRevisionCode
18354                        + " is older than current " + before.baseRevisionCode);
18355            }
18356
18357            if (!ArrayUtils.isEmpty(after.splitNames)) {
18358                for (int i = 0; i < after.splitNames.length; i++) {
18359                    final String splitName = after.splitNames[i];
18360                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18361                    if (j != -1) {
18362                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18363                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18364                                    "Update split " + splitName + " revision code "
18365                                    + after.splitRevisionCodes[i] + " is older than current "
18366                                    + before.splitRevisionCodes[j]);
18367                        }
18368                    }
18369                }
18370            }
18371        }
18372    }
18373
18374    private static class MoveCallbacks extends Handler {
18375        private static final int MSG_CREATED = 1;
18376        private static final int MSG_STATUS_CHANGED = 2;
18377
18378        private final RemoteCallbackList<IPackageMoveObserver>
18379                mCallbacks = new RemoteCallbackList<>();
18380
18381        private final SparseIntArray mLastStatus = new SparseIntArray();
18382
18383        public MoveCallbacks(Looper looper) {
18384            super(looper);
18385        }
18386
18387        public void register(IPackageMoveObserver callback) {
18388            mCallbacks.register(callback);
18389        }
18390
18391        public void unregister(IPackageMoveObserver callback) {
18392            mCallbacks.unregister(callback);
18393        }
18394
18395        @Override
18396        public void handleMessage(Message msg) {
18397            final SomeArgs args = (SomeArgs) msg.obj;
18398            final int n = mCallbacks.beginBroadcast();
18399            for (int i = 0; i < n; i++) {
18400                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18401                try {
18402                    invokeCallback(callback, msg.what, args);
18403                } catch (RemoteException ignored) {
18404                }
18405            }
18406            mCallbacks.finishBroadcast();
18407            args.recycle();
18408        }
18409
18410        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18411                throws RemoteException {
18412            switch (what) {
18413                case MSG_CREATED: {
18414                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18415                    break;
18416                }
18417                case MSG_STATUS_CHANGED: {
18418                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18419                    break;
18420                }
18421            }
18422        }
18423
18424        private void notifyCreated(int moveId, Bundle extras) {
18425            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18426
18427            final SomeArgs args = SomeArgs.obtain();
18428            args.argi1 = moveId;
18429            args.arg2 = extras;
18430            obtainMessage(MSG_CREATED, args).sendToTarget();
18431        }
18432
18433        private void notifyStatusChanged(int moveId, int status) {
18434            notifyStatusChanged(moveId, status, -1);
18435        }
18436
18437        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18438            Slog.v(TAG, "Move " + moveId + " status " + status);
18439
18440            final SomeArgs args = SomeArgs.obtain();
18441            args.argi1 = moveId;
18442            args.argi2 = status;
18443            args.arg3 = estMillis;
18444            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18445
18446            synchronized (mLastStatus) {
18447                mLastStatus.put(moveId, status);
18448            }
18449        }
18450    }
18451
18452    private final static class OnPermissionChangeListeners extends Handler {
18453        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18454
18455        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18456                new RemoteCallbackList<>();
18457
18458        public OnPermissionChangeListeners(Looper looper) {
18459            super(looper);
18460        }
18461
18462        @Override
18463        public void handleMessage(Message msg) {
18464            switch (msg.what) {
18465                case MSG_ON_PERMISSIONS_CHANGED: {
18466                    final int uid = msg.arg1;
18467                    handleOnPermissionsChanged(uid);
18468                } break;
18469            }
18470        }
18471
18472        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18473            mPermissionListeners.register(listener);
18474
18475        }
18476
18477        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18478            mPermissionListeners.unregister(listener);
18479        }
18480
18481        public void onPermissionsChanged(int uid) {
18482            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18483                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18484            }
18485        }
18486
18487        private void handleOnPermissionsChanged(int uid) {
18488            final int count = mPermissionListeners.beginBroadcast();
18489            try {
18490                for (int i = 0; i < count; i++) {
18491                    IOnPermissionsChangeListener callback = mPermissionListeners
18492                            .getBroadcastItem(i);
18493                    try {
18494                        callback.onPermissionsChanged(uid);
18495                    } catch (RemoteException e) {
18496                        Log.e(TAG, "Permission listener is dead", e);
18497                    }
18498                }
18499            } finally {
18500                mPermissionListeners.finishBroadcast();
18501            }
18502        }
18503    }
18504
18505    private class PackageManagerInternalImpl extends PackageManagerInternal {
18506        @Override
18507        public void setLocationPackagesProvider(PackagesProvider provider) {
18508            synchronized (mPackages) {
18509                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18510            }
18511        }
18512
18513        @Override
18514        public void setImePackagesProvider(PackagesProvider provider) {
18515            synchronized (mPackages) {
18516                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18517            }
18518        }
18519
18520        @Override
18521        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18522            synchronized (mPackages) {
18523                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18524            }
18525        }
18526
18527        @Override
18528        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18529            synchronized (mPackages) {
18530                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18531            }
18532        }
18533
18534        @Override
18535        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18536            synchronized (mPackages) {
18537                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18538            }
18539        }
18540
18541        @Override
18542        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18543            synchronized (mPackages) {
18544                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18545            }
18546        }
18547
18548        @Override
18549        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18550            synchronized (mPackages) {
18551                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18552            }
18553        }
18554
18555        @Override
18556        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18557            synchronized (mPackages) {
18558                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18559                        packageName, userId);
18560            }
18561        }
18562
18563        @Override
18564        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18565            synchronized (mPackages) {
18566                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18567                        packageName, userId);
18568            }
18569        }
18570
18571        @Override
18572        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18573            synchronized (mPackages) {
18574                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18575                        packageName, userId);
18576            }
18577        }
18578
18579        @Override
18580        public void setKeepUninstalledPackages(final List<String> packageList) {
18581            Preconditions.checkNotNull(packageList);
18582            List<String> removedFromList = null;
18583            synchronized (mPackages) {
18584                if (mKeepUninstalledPackages != null) {
18585                    final int packagesCount = mKeepUninstalledPackages.size();
18586                    for (int i = 0; i < packagesCount; i++) {
18587                        String oldPackage = mKeepUninstalledPackages.get(i);
18588                        if (packageList != null && packageList.contains(oldPackage)) {
18589                            continue;
18590                        }
18591                        if (removedFromList == null) {
18592                            removedFromList = new ArrayList<>();
18593                        }
18594                        removedFromList.add(oldPackage);
18595                    }
18596                }
18597                mKeepUninstalledPackages = new ArrayList<>(packageList);
18598                if (removedFromList != null) {
18599                    final int removedCount = removedFromList.size();
18600                    for (int i = 0; i < removedCount; i++) {
18601                        deletePackageIfUnusedLPr(removedFromList.get(i));
18602                    }
18603                }
18604            }
18605        }
18606
18607        @Override
18608        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18609            synchronized (mPackages) {
18610                // If we do not support permission review, done.
18611                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18612                    return false;
18613                }
18614
18615                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18616                if (packageSetting == null) {
18617                    return false;
18618                }
18619
18620                // Permission review applies only to apps not supporting the new permission model.
18621                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18622                    return false;
18623                }
18624
18625                // Legacy apps have the permission and get user consent on launch.
18626                PermissionsState permissionsState = packageSetting.getPermissionsState();
18627                return permissionsState.isPermissionReviewRequired(userId);
18628            }
18629        }
18630    }
18631
18632    @Override
18633    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18634        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18635        synchronized (mPackages) {
18636            final long identity = Binder.clearCallingIdentity();
18637            try {
18638                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18639                        packageNames, userId);
18640            } finally {
18641                Binder.restoreCallingIdentity(identity);
18642            }
18643        }
18644    }
18645
18646    private static void enforceSystemOrPhoneCaller(String tag) {
18647        int callingUid = Binder.getCallingUid();
18648        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18649            throw new SecurityException(
18650                    "Cannot call " + tag + " from UID " + callingUid);
18651        }
18652    }
18653
18654    boolean isHistoricalPackageUsageAvailable() {
18655        return mPackageUsage.isHistoricalPackageUsageAvailable();
18656    }
18657}
18658