PackageManagerService.java revision 6b4736d604fd91aaedc6f3fe9be5a1e757aab86c
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.LinkedList;
286import java.util.List;
287import java.util.Map;
288import java.util.Objects;
289import java.util.Set;
290import java.util.concurrent.CountDownLatch;
291import java.util.concurrent.TimeUnit;
292import java.util.concurrent.atomic.AtomicBoolean;
293import java.util.concurrent.atomic.AtomicInteger;
294import java.util.concurrent.atomic.AtomicLong;
295
296/**
297 * Keep track of all those .apks everywhere.
298 *
299 * This is very central to the platform's security; please run the unit
300 * tests whenever making modifications here:
301 *
302runtest -c android.content.pm.PackageManagerTests frameworks-core
303 *
304 * {@hide}
305 */
306public class PackageManagerService extends IPackageManager.Stub {
307    static final String TAG = "PackageManager";
308    static final boolean DEBUG_SETTINGS = false;
309    static final boolean DEBUG_PREFERRED = false;
310    static final boolean DEBUG_UPGRADE = false;
311    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
312    private static final boolean DEBUG_BACKUP = false;
313    private static final boolean DEBUG_INSTALL = false;
314    private static final boolean DEBUG_REMOVE = false;
315    private static final boolean DEBUG_BROADCASTS = false;
316    private static final boolean DEBUG_SHOW_INFO = false;
317    private static final boolean DEBUG_PACKAGE_INFO = false;
318    private static final boolean DEBUG_INTENT_MATCHING = false;
319    private static final boolean DEBUG_PACKAGE_SCANNING = false;
320    private static final boolean DEBUG_VERIFY = false;
321
322    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
323    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
324    // user, but by default initialize to this.
325    static final boolean DEBUG_DEXOPT = false;
326
327    private static final boolean DEBUG_ABI_SELECTION = false;
328    private static final boolean DEBUG_EPHEMERAL = false;
329    private static final boolean DEBUG_TRIAGED_MISSING = false;
330    private static final boolean DEBUG_APP_DATA = false;
331
332    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
333
334    private static final boolean DISABLE_EPHEMERAL_APPS = true;
335
336    private static final int RADIO_UID = Process.PHONE_UID;
337    private static final int LOG_UID = Process.LOG_UID;
338    private static final int NFC_UID = Process.NFC_UID;
339    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
340    private static final int SHELL_UID = Process.SHELL_UID;
341
342    // Cap the size of permission trees that 3rd party apps can define
343    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
344
345    // Suffix used during package installation when copying/moving
346    // package apks to install directory.
347    private static final String INSTALL_PACKAGE_SUFFIX = "-";
348
349    static final int SCAN_NO_DEX = 1<<1;
350    static final int SCAN_FORCE_DEX = 1<<2;
351    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
352    static final int SCAN_NEW_INSTALL = 1<<4;
353    static final int SCAN_NO_PATHS = 1<<5;
354    static final int SCAN_UPDATE_TIME = 1<<6;
355    static final int SCAN_DEFER_DEX = 1<<7;
356    static final int SCAN_BOOTING = 1<<8;
357    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
358    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
359    static final int SCAN_REPLACING = 1<<11;
360    static final int SCAN_REQUIRE_KNOWN = 1<<12;
361    static final int SCAN_MOVE = 1<<13;
362    static final int SCAN_INITIAL = 1<<14;
363    static final int SCAN_CHECK_ONLY = 1<<15;
364
365    static final int REMOVE_CHATTY = 1<<16;
366
367    private static final int[] EMPTY_INT_ARRAY = new int[0];
368
369    /**
370     * Timeout (in milliseconds) after which the watchdog should declare that
371     * our handler thread is wedged.  The usual default for such things is one
372     * minute but we sometimes do very lengthy I/O operations on this thread,
373     * such as installing multi-gigabyte applications, so ours needs to be longer.
374     */
375    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
376
377    /**
378     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
379     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
380     * settings entry if available, otherwise we use the hardcoded default.  If it's been
381     * more than this long since the last fstrim, we force one during the boot sequence.
382     *
383     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
384     * one gets run at the next available charging+idle time.  This final mandatory
385     * no-fstrim check kicks in only of the other scheduling criteria is never met.
386     */
387    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
388
389    /**
390     * Whether verification is enabled by default.
391     */
392    private static final boolean DEFAULT_VERIFY_ENABLE = true;
393
394    /**
395     * The default maximum time to wait for the verification agent to return in
396     * milliseconds.
397     */
398    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
399
400    /**
401     * The default response for package verification timeout.
402     *
403     * This can be either PackageManager.VERIFICATION_ALLOW or
404     * PackageManager.VERIFICATION_REJECT.
405     */
406    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
407
408    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
409
410    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
411            DEFAULT_CONTAINER_PACKAGE,
412            "com.android.defcontainer.DefaultContainerService");
413
414    private static final String KILL_APP_REASON_GIDS_CHANGED =
415            "permission grant or revoke changed gids";
416
417    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
418            "permissions revoked";
419
420    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
421
422    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
423
424    /** Permission grant: not grant the permission. */
425    private static final int GRANT_DENIED = 1;
426
427    /** Permission grant: grant the permission as an install permission. */
428    private static final int GRANT_INSTALL = 2;
429
430    /** Permission grant: grant the permission as a runtime one. */
431    private static final int GRANT_RUNTIME = 3;
432
433    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
434    private static final int GRANT_UPGRADE = 4;
435
436    /** Canonical intent used to identify what counts as a "web browser" app */
437    private static final Intent sBrowserIntent;
438    static {
439        sBrowserIntent = new Intent();
440        sBrowserIntent.setAction(Intent.ACTION_VIEW);
441        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
442        sBrowserIntent.setData(Uri.parse("http:"));
443    }
444
445    final ServiceThread mHandlerThread;
446
447    final PackageHandler mHandler;
448
449    /**
450     * Messages for {@link #mHandler} that need to wait for system ready before
451     * being dispatched.
452     */
453    private ArrayList<Message> mPostSystemReadyMessages;
454
455    final int mSdkVersion = Build.VERSION.SDK_INT;
456
457    final Context mContext;
458    final boolean mFactoryTest;
459    final boolean mOnlyCore;
460    final DisplayMetrics mMetrics;
461    final int mDefParseFlags;
462    final String[] mSeparateProcesses;
463    final boolean mIsUpgrade;
464
465    /** The location for ASEC container files on internal storage. */
466    final String mAsecInternalPath;
467
468    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
469    // LOCK HELD.  Can be called with mInstallLock held.
470    @GuardedBy("mInstallLock")
471    final Installer mInstaller;
472
473    /** Directory where installed third-party apps stored */
474    final File mAppInstallDir;
475    final File mEphemeralInstallDir;
476
477    /**
478     * Directory to which applications installed internally have their
479     * 32 bit native libraries copied.
480     */
481    private File mAppLib32InstallDir;
482
483    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
484    // apps.
485    final File mDrmAppPrivateInstallDir;
486
487    // ----------------------------------------------------------------
488
489    // Lock for state used when installing and doing other long running
490    // operations.  Methods that must be called with this lock held have
491    // the suffix "LI".
492    final Object mInstallLock = new Object();
493
494    // ----------------------------------------------------------------
495
496    // Keys are String (package name), values are Package.  This also serves
497    // as the lock for the global state.  Methods that must be called with
498    // this lock held have the prefix "LP".
499    @GuardedBy("mPackages")
500    final ArrayMap<String, PackageParser.Package> mPackages =
501            new ArrayMap<String, PackageParser.Package>();
502
503    // Tracks available target package names -> overlay package paths.
504    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
505        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
506
507    /**
508     * Tracks new system packages [received in an OTA] that we expect to
509     * find updated user-installed versions. Keys are package name, values
510     * are package location.
511     */
512    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
513
514    /**
515     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
516     */
517    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
518    /**
519     * Whether or not system app permissions should be promoted from install to runtime.
520     */
521    boolean mPromoteSystemApps;
522
523    final Settings mSettings;
524    boolean mRestoredSettings;
525
526    // System configuration read by SystemConfig.
527    final int[] mGlobalGids;
528    final SparseArray<ArraySet<String>> mSystemPermissions;
529    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
530
531    // If mac_permissions.xml was found for seinfo labeling.
532    boolean mFoundPolicyFile;
533
534    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
535
536    public static final class SharedLibraryEntry {
537        public final String path;
538        public final String apk;
539
540        SharedLibraryEntry(String _path, String _apk) {
541            path = _path;
542            apk = _apk;
543        }
544    }
545
546    // Currently known shared libraries.
547    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
548            new ArrayMap<String, SharedLibraryEntry>();
549
550    // All available activities, for your resolving pleasure.
551    final ActivityIntentResolver mActivities =
552            new ActivityIntentResolver();
553
554    // All available receivers, for your resolving pleasure.
555    final ActivityIntentResolver mReceivers =
556            new ActivityIntentResolver();
557
558    // All available services, for your resolving pleasure.
559    final ServiceIntentResolver mServices = new ServiceIntentResolver();
560
561    // All available providers, for your resolving pleasure.
562    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
563
564    // Mapping from provider base names (first directory in content URI codePath)
565    // to the provider information.
566    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
567            new ArrayMap<String, PackageParser.Provider>();
568
569    // Mapping from instrumentation class names to info about them.
570    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
571            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
572
573    // Mapping from permission names to info about them.
574    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
575            new ArrayMap<String, PackageParser.PermissionGroup>();
576
577    // Packages whose data we have transfered into another package, thus
578    // should no longer exist.
579    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
580
581    // Broadcast actions that are only available to the system.
582    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
583
584    /** List of packages waiting for verification. */
585    final SparseArray<PackageVerificationState> mPendingVerification
586            = new SparseArray<PackageVerificationState>();
587
588    /** Set of packages associated with each app op permission. */
589    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
590
591    final PackageInstallerService mInstallerService;
592
593    private final PackageDexOptimizer mPackageDexOptimizer;
594
595    private AtomicInteger mNextMoveId = new AtomicInteger();
596    private final MoveCallbacks mMoveCallbacks;
597
598    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
599
600    // Cache of users who need badging.
601    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
602
603    /** Token for keys in mPendingVerification. */
604    private int mPendingVerificationToken = 0;
605
606    volatile boolean mSystemReady;
607    volatile boolean mSafeMode;
608    volatile boolean mHasSystemUidErrors;
609
610    ApplicationInfo mAndroidApplication;
611    final ActivityInfo mResolveActivity = new ActivityInfo();
612    final ResolveInfo mResolveInfo = new ResolveInfo();
613    ComponentName mResolveComponentName;
614    PackageParser.Package mPlatformPackage;
615    ComponentName mCustomResolverComponentName;
616
617    boolean mResolverReplaced = false;
618
619    private final @Nullable ComponentName mIntentFilterVerifierComponent;
620    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
621
622    private int mIntentFilterVerificationToken = 0;
623
624    /** Component that knows whether or not an ephemeral application exists */
625    final ComponentName mEphemeralResolverComponent;
626    /** The service connection to the ephemeral resolver */
627    final EphemeralResolverConnection mEphemeralResolverConnection;
628
629    /** Component used to install ephemeral applications */
630    final ComponentName mEphemeralInstallerComponent;
631    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
632    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
633
634    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
635            = new SparseArray<IntentFilterVerificationState>();
636
637    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
638            new DefaultPermissionGrantPolicy(this);
639
640    // List of packages names to keep cached, even if they are uninstalled for all users
641    private List<String> mKeepUninstalledPackages;
642
643    private boolean mUseJitProfiles =
644            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
645
646    private static class IFVerificationParams {
647        PackageParser.Package pkg;
648        boolean replacing;
649        int userId;
650        int verifierUid;
651
652        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
653                int _userId, int _verifierUid) {
654            pkg = _pkg;
655            replacing = _replacing;
656            userId = _userId;
657            replacing = _replacing;
658            verifierUid = _verifierUid;
659        }
660    }
661
662    private interface IntentFilterVerifier<T extends IntentFilter> {
663        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
664                                               T filter, String packageName);
665        void startVerifications(int userId);
666        void receiveVerificationResponse(int verificationId);
667    }
668
669    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
670        private Context mContext;
671        private ComponentName mIntentFilterVerifierComponent;
672        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
673
674        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
675            mContext = context;
676            mIntentFilterVerifierComponent = verifierComponent;
677        }
678
679        private String getDefaultScheme() {
680            return IntentFilter.SCHEME_HTTPS;
681        }
682
683        @Override
684        public void startVerifications(int userId) {
685            // Launch verifications requests
686            int count = mCurrentIntentFilterVerifications.size();
687            for (int n=0; n<count; n++) {
688                int verificationId = mCurrentIntentFilterVerifications.get(n);
689                final IntentFilterVerificationState ivs =
690                        mIntentFilterVerificationStates.get(verificationId);
691
692                String packageName = ivs.getPackageName();
693
694                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
695                final int filterCount = filters.size();
696                ArraySet<String> domainsSet = new ArraySet<>();
697                for (int m=0; m<filterCount; m++) {
698                    PackageParser.ActivityIntentInfo filter = filters.get(m);
699                    domainsSet.addAll(filter.getHostsList());
700                }
701                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
702                synchronized (mPackages) {
703                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
704                            packageName, domainsList) != null) {
705                        scheduleWriteSettingsLocked();
706                    }
707                }
708                sendVerificationRequest(userId, verificationId, ivs);
709            }
710            mCurrentIntentFilterVerifications.clear();
711        }
712
713        private void sendVerificationRequest(int userId, int verificationId,
714                IntentFilterVerificationState ivs) {
715
716            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
717            verificationIntent.putExtra(
718                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
719                    verificationId);
720            verificationIntent.putExtra(
721                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
722                    getDefaultScheme());
723            verificationIntent.putExtra(
724                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
725                    ivs.getHostsString());
726            verificationIntent.putExtra(
727                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
728                    ivs.getPackageName());
729            verificationIntent.setComponent(mIntentFilterVerifierComponent);
730            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
731
732            UserHandle user = new UserHandle(userId);
733            mContext.sendBroadcastAsUser(verificationIntent, user);
734            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
735                    "Sending IntentFilter verification broadcast");
736        }
737
738        public void receiveVerificationResponse(int verificationId) {
739            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
740
741            final boolean verified = ivs.isVerified();
742
743            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
744            final int count = filters.size();
745            if (DEBUG_DOMAIN_VERIFICATION) {
746                Slog.i(TAG, "Received verification response " + verificationId
747                        + " for " + count + " filters, verified=" + verified);
748            }
749            for (int n=0; n<count; n++) {
750                PackageParser.ActivityIntentInfo filter = filters.get(n);
751                filter.setVerified(verified);
752
753                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
754                        + " verified with result:" + verified + " and hosts:"
755                        + ivs.getHostsString());
756            }
757
758            mIntentFilterVerificationStates.remove(verificationId);
759
760            final String packageName = ivs.getPackageName();
761            IntentFilterVerificationInfo ivi = null;
762
763            synchronized (mPackages) {
764                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
765            }
766            if (ivi == null) {
767                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
768                        + verificationId + " packageName:" + packageName);
769                return;
770            }
771            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
772                    "Updating IntentFilterVerificationInfo for package " + packageName
773                            +" verificationId:" + verificationId);
774
775            synchronized (mPackages) {
776                if (verified) {
777                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
778                } else {
779                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
780                }
781                scheduleWriteSettingsLocked();
782
783                final int userId = ivs.getUserId();
784                if (userId != UserHandle.USER_ALL) {
785                    final int userStatus =
786                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
787
788                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
789                    boolean needUpdate = false;
790
791                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
792                    // already been set by the User thru the Disambiguation dialog
793                    switch (userStatus) {
794                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
795                            if (verified) {
796                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
797                            } else {
798                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
799                            }
800                            needUpdate = true;
801                            break;
802
803                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
804                            if (verified) {
805                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
806                                needUpdate = true;
807                            }
808                            break;
809
810                        default:
811                            // Nothing to do
812                    }
813
814                    if (needUpdate) {
815                        mSettings.updateIntentFilterVerificationStatusLPw(
816                                packageName, updatedStatus, userId);
817                        scheduleWritePackageRestrictionsLocked(userId);
818                    }
819                }
820            }
821        }
822
823        @Override
824        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
825                    ActivityIntentInfo filter, String packageName) {
826            if (!hasValidDomains(filter)) {
827                return false;
828            }
829            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
830            if (ivs == null) {
831                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
832                        packageName);
833            }
834            if (DEBUG_DOMAIN_VERIFICATION) {
835                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
836            }
837            ivs.addFilter(filter);
838            return true;
839        }
840
841        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
842                int userId, int verificationId, String packageName) {
843            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
844                    verifierUid, userId, packageName);
845            ivs.setPendingState();
846            synchronized (mPackages) {
847                mIntentFilterVerificationStates.append(verificationId, ivs);
848                mCurrentIntentFilterVerifications.add(verificationId);
849            }
850            return ivs;
851        }
852    }
853
854    private static boolean hasValidDomains(ActivityIntentInfo filter) {
855        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
856                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
857                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
858    }
859
860    // Set of pending broadcasts for aggregating enable/disable of components.
861    static class PendingPackageBroadcasts {
862        // for each user id, a map of <package name -> components within that package>
863        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
864
865        public PendingPackageBroadcasts() {
866            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
867        }
868
869        public ArrayList<String> get(int userId, String packageName) {
870            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
871            return packages.get(packageName);
872        }
873
874        public void put(int userId, String packageName, ArrayList<String> components) {
875            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
876            packages.put(packageName, components);
877        }
878
879        public void remove(int userId, String packageName) {
880            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
881            if (packages != null) {
882                packages.remove(packageName);
883            }
884        }
885
886        public void remove(int userId) {
887            mUidMap.remove(userId);
888        }
889
890        public int userIdCount() {
891            return mUidMap.size();
892        }
893
894        public int userIdAt(int n) {
895            return mUidMap.keyAt(n);
896        }
897
898        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
899            return mUidMap.get(userId);
900        }
901
902        public int size() {
903            // total number of pending broadcast entries across all userIds
904            int num = 0;
905            for (int i = 0; i< mUidMap.size(); i++) {
906                num += mUidMap.valueAt(i).size();
907            }
908            return num;
909        }
910
911        public void clear() {
912            mUidMap.clear();
913        }
914
915        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
916            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
917            if (map == null) {
918                map = new ArrayMap<String, ArrayList<String>>();
919                mUidMap.put(userId, map);
920            }
921            return map;
922        }
923    }
924    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
925
926    // Service Connection to remote media container service to copy
927    // package uri's from external media onto secure containers
928    // or internal storage.
929    private IMediaContainerService mContainerService = null;
930
931    static final int SEND_PENDING_BROADCAST = 1;
932    static final int MCS_BOUND = 3;
933    static final int END_COPY = 4;
934    static final int INIT_COPY = 5;
935    static final int MCS_UNBIND = 6;
936    static final int START_CLEANING_PACKAGE = 7;
937    static final int FIND_INSTALL_LOC = 8;
938    static final int POST_INSTALL = 9;
939    static final int MCS_RECONNECT = 10;
940    static final int MCS_GIVE_UP = 11;
941    static final int UPDATED_MEDIA_STATUS = 12;
942    static final int WRITE_SETTINGS = 13;
943    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
944    static final int PACKAGE_VERIFIED = 15;
945    static final int CHECK_PENDING_VERIFICATION = 16;
946    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
947    static final int INTENT_FILTER_VERIFIED = 18;
948
949    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
950
951    // Delay time in millisecs
952    static final int BROADCAST_DELAY = 10 * 1000;
953
954    static UserManagerService sUserManager;
955
956    // Stores a list of users whose package restrictions file needs to be updated
957    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
958
959    final private DefaultContainerConnection mDefContainerConn =
960            new DefaultContainerConnection();
961    class DefaultContainerConnection implements ServiceConnection {
962        public void onServiceConnected(ComponentName name, IBinder service) {
963            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
964            IMediaContainerService imcs =
965                IMediaContainerService.Stub.asInterface(service);
966            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
967        }
968
969        public void onServiceDisconnected(ComponentName name) {
970            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
971        }
972    }
973
974    // Recordkeeping of restore-after-install operations that are currently in flight
975    // between the Package Manager and the Backup Manager
976    static class PostInstallData {
977        public InstallArgs args;
978        public PackageInstalledInfo res;
979
980        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
981            args = _a;
982            res = _r;
983        }
984    }
985
986    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
987    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
988
989    // XML tags for backup/restore of various bits of state
990    private static final String TAG_PREFERRED_BACKUP = "pa";
991    private static final String TAG_DEFAULT_APPS = "da";
992    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
993
994    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
995    private static final String TAG_ALL_GRANTS = "rt-grants";
996    private static final String TAG_GRANT = "grant";
997    private static final String ATTR_PACKAGE_NAME = "pkg";
998
999    private static final String TAG_PERMISSION = "perm";
1000    private static final String ATTR_PERMISSION_NAME = "name";
1001    private static final String ATTR_IS_GRANTED = "g";
1002    private static final String ATTR_USER_SET = "set";
1003    private static final String ATTR_USER_FIXED = "fixed";
1004    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1005
1006    // System/policy permission grants are not backed up
1007    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1008            FLAG_PERMISSION_POLICY_FIXED
1009            | FLAG_PERMISSION_SYSTEM_FIXED
1010            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1011
1012    // And we back up these user-adjusted states
1013    private static final int USER_RUNTIME_GRANT_MASK =
1014            FLAG_PERMISSION_USER_SET
1015            | FLAG_PERMISSION_USER_FIXED
1016            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1017
1018    final @Nullable String mRequiredVerifierPackage;
1019    final @Nullable String mRequiredInstallerPackage;
1020
1021    private final PackageUsage mPackageUsage = new PackageUsage();
1022
1023    private class PackageUsage {
1024        private static final int WRITE_INTERVAL
1025            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1026
1027        private final Object mFileLock = new Object();
1028        private final AtomicLong mLastWritten = new AtomicLong(0);
1029        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1030
1031        private boolean mIsHistoricalPackageUsageAvailable = true;
1032
1033        boolean isHistoricalPackageUsageAvailable() {
1034            return mIsHistoricalPackageUsageAvailable;
1035        }
1036
1037        void write(boolean force) {
1038            if (force) {
1039                writeInternal();
1040                return;
1041            }
1042            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1043                && !DEBUG_DEXOPT) {
1044                return;
1045            }
1046            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1047                new Thread("PackageUsage_DiskWriter") {
1048                    @Override
1049                    public void run() {
1050                        try {
1051                            writeInternal();
1052                        } finally {
1053                            mBackgroundWriteRunning.set(false);
1054                        }
1055                    }
1056                }.start();
1057            }
1058        }
1059
1060        private void writeInternal() {
1061            synchronized (mPackages) {
1062                synchronized (mFileLock) {
1063                    AtomicFile file = getFile();
1064                    FileOutputStream f = null;
1065                    try {
1066                        f = file.startWrite();
1067                        BufferedOutputStream out = new BufferedOutputStream(f);
1068                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1069                        StringBuilder sb = new StringBuilder();
1070                        for (PackageParser.Package pkg : mPackages.values()) {
1071                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1072                                continue;
1073                            }
1074                            sb.setLength(0);
1075                            sb.append(pkg.packageName);
1076                            sb.append(' ');
1077                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1078                            sb.append('\n');
1079                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1080                        }
1081                        out.flush();
1082                        file.finishWrite(f);
1083                    } catch (IOException e) {
1084                        if (f != null) {
1085                            file.failWrite(f);
1086                        }
1087                        Log.e(TAG, "Failed to write package usage times", e);
1088                    }
1089                }
1090            }
1091            mLastWritten.set(SystemClock.elapsedRealtime());
1092        }
1093
1094        void readLP() {
1095            synchronized (mFileLock) {
1096                AtomicFile file = getFile();
1097                BufferedInputStream in = null;
1098                try {
1099                    in = new BufferedInputStream(file.openRead());
1100                    StringBuffer sb = new StringBuffer();
1101                    while (true) {
1102                        String packageName = readToken(in, sb, ' ');
1103                        if (packageName == null) {
1104                            break;
1105                        }
1106                        String timeInMillisString = readToken(in, sb, '\n');
1107                        if (timeInMillisString == null) {
1108                            throw new IOException("Failed to find last usage time for package "
1109                                                  + packageName);
1110                        }
1111                        PackageParser.Package pkg = mPackages.get(packageName);
1112                        if (pkg == null) {
1113                            continue;
1114                        }
1115                        long timeInMillis;
1116                        try {
1117                            timeInMillis = Long.parseLong(timeInMillisString);
1118                        } catch (NumberFormatException e) {
1119                            throw new IOException("Failed to parse " + timeInMillisString
1120                                                  + " as a long.", e);
1121                        }
1122                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1123                    }
1124                } catch (FileNotFoundException expected) {
1125                    mIsHistoricalPackageUsageAvailable = false;
1126                } catch (IOException e) {
1127                    Log.w(TAG, "Failed to read package usage times", e);
1128                } finally {
1129                    IoUtils.closeQuietly(in);
1130                }
1131            }
1132            mLastWritten.set(SystemClock.elapsedRealtime());
1133        }
1134
1135        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1136                throws IOException {
1137            sb.setLength(0);
1138            while (true) {
1139                int ch = in.read();
1140                if (ch == -1) {
1141                    if (sb.length() == 0) {
1142                        return null;
1143                    }
1144                    throw new IOException("Unexpected EOF");
1145                }
1146                if (ch == endOfToken) {
1147                    return sb.toString();
1148                }
1149                sb.append((char)ch);
1150            }
1151        }
1152
1153        private AtomicFile getFile() {
1154            File dataDir = Environment.getDataDirectory();
1155            File systemDir = new File(dataDir, "system");
1156            File fname = new File(systemDir, "package-usage.list");
1157            return new AtomicFile(fname);
1158        }
1159    }
1160
1161    class PackageHandler extends Handler {
1162        private boolean mBound = false;
1163        final ArrayList<HandlerParams> mPendingInstalls =
1164            new ArrayList<HandlerParams>();
1165
1166        private boolean connectToService() {
1167            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1168                    " DefaultContainerService");
1169            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1170            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1171            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1172                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1173                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174                mBound = true;
1175                return true;
1176            }
1177            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1178            return false;
1179        }
1180
1181        private void disconnectService() {
1182            mContainerService = null;
1183            mBound = false;
1184            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1185            mContext.unbindService(mDefContainerConn);
1186            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1187        }
1188
1189        PackageHandler(Looper looper) {
1190            super(looper);
1191        }
1192
1193        public void handleMessage(Message msg) {
1194            try {
1195                doHandleMessage(msg);
1196            } finally {
1197                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1198            }
1199        }
1200
1201        void doHandleMessage(Message msg) {
1202            switch (msg.what) {
1203                case INIT_COPY: {
1204                    HandlerParams params = (HandlerParams) msg.obj;
1205                    int idx = mPendingInstalls.size();
1206                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1207                    // If a bind was already initiated we dont really
1208                    // need to do anything. The pending install
1209                    // will be processed later on.
1210                    if (!mBound) {
1211                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1212                                System.identityHashCode(mHandler));
1213                        // If this is the only one pending we might
1214                        // have to bind to the service again.
1215                        if (!connectToService()) {
1216                            Slog.e(TAG, "Failed to bind to media container service");
1217                            params.serviceError();
1218                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1219                                    System.identityHashCode(mHandler));
1220                            if (params.traceMethod != null) {
1221                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1222                                        params.traceCookie);
1223                            }
1224                            return;
1225                        } else {
1226                            // Once we bind to the service, the first
1227                            // pending request will be processed.
1228                            mPendingInstalls.add(idx, params);
1229                        }
1230                    } else {
1231                        mPendingInstalls.add(idx, params);
1232                        // Already bound to the service. Just make
1233                        // sure we trigger off processing the first request.
1234                        if (idx == 0) {
1235                            mHandler.sendEmptyMessage(MCS_BOUND);
1236                        }
1237                    }
1238                    break;
1239                }
1240                case MCS_BOUND: {
1241                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1242                    if (msg.obj != null) {
1243                        mContainerService = (IMediaContainerService) msg.obj;
1244                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1245                                System.identityHashCode(mHandler));
1246                    }
1247                    if (mContainerService == null) {
1248                        if (!mBound) {
1249                            // Something seriously wrong since we are not bound and we are not
1250                            // waiting for connection. Bail out.
1251                            Slog.e(TAG, "Cannot bind to media container service");
1252                            for (HandlerParams params : mPendingInstalls) {
1253                                // Indicate service bind error
1254                                params.serviceError();
1255                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1256                                        System.identityHashCode(params));
1257                                if (params.traceMethod != null) {
1258                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1259                                            params.traceMethod, params.traceCookie);
1260                                }
1261                                return;
1262                            }
1263                            mPendingInstalls.clear();
1264                        } else {
1265                            Slog.w(TAG, "Waiting to connect to media container service");
1266                        }
1267                    } else if (mPendingInstalls.size() > 0) {
1268                        HandlerParams params = mPendingInstalls.get(0);
1269                        if (params != null) {
1270                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1271                                    System.identityHashCode(params));
1272                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1273                            if (params.startCopy()) {
1274                                // We are done...  look for more work or to
1275                                // go idle.
1276                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1277                                        "Checking for more work or unbind...");
1278                                // Delete pending install
1279                                if (mPendingInstalls.size() > 0) {
1280                                    mPendingInstalls.remove(0);
1281                                }
1282                                if (mPendingInstalls.size() == 0) {
1283                                    if (mBound) {
1284                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1285                                                "Posting delayed MCS_UNBIND");
1286                                        removeMessages(MCS_UNBIND);
1287                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1288                                        // Unbind after a little delay, to avoid
1289                                        // continual thrashing.
1290                                        sendMessageDelayed(ubmsg, 10000);
1291                                    }
1292                                } else {
1293                                    // There are more pending requests in queue.
1294                                    // Just post MCS_BOUND message to trigger processing
1295                                    // of next pending install.
1296                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1297                                            "Posting MCS_BOUND for next work");
1298                                    mHandler.sendEmptyMessage(MCS_BOUND);
1299                                }
1300                            }
1301                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1302                        }
1303                    } else {
1304                        // Should never happen ideally.
1305                        Slog.w(TAG, "Empty queue");
1306                    }
1307                    break;
1308                }
1309                case MCS_RECONNECT: {
1310                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1311                    if (mPendingInstalls.size() > 0) {
1312                        if (mBound) {
1313                            disconnectService();
1314                        }
1315                        if (!connectToService()) {
1316                            Slog.e(TAG, "Failed to bind to media container service");
1317                            for (HandlerParams params : mPendingInstalls) {
1318                                // Indicate service bind error
1319                                params.serviceError();
1320                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                                        System.identityHashCode(params));
1322                            }
1323                            mPendingInstalls.clear();
1324                        }
1325                    }
1326                    break;
1327                }
1328                case MCS_UNBIND: {
1329                    // If there is no actual work left, then time to unbind.
1330                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1331
1332                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1333                        if (mBound) {
1334                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1335
1336                            disconnectService();
1337                        }
1338                    } else if (mPendingInstalls.size() > 0) {
1339                        // There are more pending requests in queue.
1340                        // Just post MCS_BOUND message to trigger processing
1341                        // of next pending install.
1342                        mHandler.sendEmptyMessage(MCS_BOUND);
1343                    }
1344
1345                    break;
1346                }
1347                case MCS_GIVE_UP: {
1348                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1349                    HandlerParams params = mPendingInstalls.remove(0);
1350                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1351                            System.identityHashCode(params));
1352                    break;
1353                }
1354                case SEND_PENDING_BROADCAST: {
1355                    String packages[];
1356                    ArrayList<String> components[];
1357                    int size = 0;
1358                    int uids[];
1359                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1360                    synchronized (mPackages) {
1361                        if (mPendingBroadcasts == null) {
1362                            return;
1363                        }
1364                        size = mPendingBroadcasts.size();
1365                        if (size <= 0) {
1366                            // Nothing to be done. Just return
1367                            return;
1368                        }
1369                        packages = new String[size];
1370                        components = new ArrayList[size];
1371                        uids = new int[size];
1372                        int i = 0;  // filling out the above arrays
1373
1374                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1375                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1376                            Iterator<Map.Entry<String, ArrayList<String>>> it
1377                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1378                                            .entrySet().iterator();
1379                            while (it.hasNext() && i < size) {
1380                                Map.Entry<String, ArrayList<String>> ent = it.next();
1381                                packages[i] = ent.getKey();
1382                                components[i] = ent.getValue();
1383                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1384                                uids[i] = (ps != null)
1385                                        ? UserHandle.getUid(packageUserId, ps.appId)
1386                                        : -1;
1387                                i++;
1388                            }
1389                        }
1390                        size = i;
1391                        mPendingBroadcasts.clear();
1392                    }
1393                    // Send broadcasts
1394                    for (int i = 0; i < size; i++) {
1395                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1396                    }
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1398                    break;
1399                }
1400                case START_CLEANING_PACKAGE: {
1401                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402                    final String packageName = (String)msg.obj;
1403                    final int userId = msg.arg1;
1404                    final boolean andCode = msg.arg2 != 0;
1405                    synchronized (mPackages) {
1406                        if (userId == UserHandle.USER_ALL) {
1407                            int[] users = sUserManager.getUserIds();
1408                            for (int user : users) {
1409                                mSettings.addPackageToCleanLPw(
1410                                        new PackageCleanItem(user, packageName, andCode));
1411                            }
1412                        } else {
1413                            mSettings.addPackageToCleanLPw(
1414                                    new PackageCleanItem(userId, packageName, andCode));
1415                        }
1416                    }
1417                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418                    startCleaningPackages();
1419                } break;
1420                case POST_INSTALL: {
1421                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1422
1423                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1424                    mRunningInstalls.delete(msg.arg1);
1425                    boolean deleteOld = false;
1426
1427                    if (data != null) {
1428                        InstallArgs args = data.args;
1429                        PackageInstalledInfo res = data.res;
1430
1431                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1432                            //TODO: Broadcast for child packages too
1433                            final String packageName = res.pkg.applicationInfo.packageName;
1434                            res.removedInfo.sendBroadcast(false, true, false);
1435                            Bundle extras = new Bundle(1);
1436                            extras.putInt(Intent.EXTRA_UID, res.uid);
1437
1438                            // Now that we successfully installed the package, grant runtime
1439                            // permissions if requested before broadcasting the install.
1440                            if ((args.installFlags
1441                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1442                                    && res.pkg.applicationInfo.targetSdkVersion
1443                                            >= Build.VERSION_CODES.M) {
1444                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1445                                        args.installGrantPermissions);
1446                            }
1447
1448                            synchronized (mPackages) {
1449                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1450                            }
1451
1452                            // Determine the set of users who are adding this
1453                            // package for the first time vs. those who are seeing
1454                            // an update.
1455                            int[] firstUsers;
1456                            int[] updateUsers = new int[0];
1457                            if (res.origUsers == null || res.origUsers.length == 0) {
1458                                firstUsers = res.newUsers;
1459                            } else {
1460                                firstUsers = new int[0];
1461                                for (int i=0; i<res.newUsers.length; i++) {
1462                                    int user = res.newUsers[i];
1463                                    boolean isNew = true;
1464                                    for (int j=0; j<res.origUsers.length; j++) {
1465                                        if (res.origUsers[j] == user) {
1466                                            isNew = false;
1467                                            break;
1468                                        }
1469                                    }
1470                                    if (isNew) {
1471                                        int[] newFirst = new int[firstUsers.length+1];
1472                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1473                                                firstUsers.length);
1474                                        newFirst[firstUsers.length] = user;
1475                                        firstUsers = newFirst;
1476                                    } else {
1477                                        int[] newUpdate = new int[updateUsers.length+1];
1478                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1479                                                updateUsers.length);
1480                                        newUpdate[updateUsers.length] = user;
1481                                        updateUsers = newUpdate;
1482                                    }
1483                                }
1484                            }
1485                            // don't broadcast for ephemeral installs/updates
1486                            final boolean isEphemeral = isEphemeral(res.pkg);
1487                            if (!isEphemeral) {
1488                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1489                                        extras, 0 /*flags*/, null /*targetPackage*/,
1490                                        null /*finishedReceiver*/, firstUsers);
1491                            }
1492                            final boolean update = res.removedInfo.removedPackage != null;
1493                            if (update) {
1494                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1495                            }
1496                            if (!isEphemeral) {
1497                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1498                                        extras, 0 /*flags*/, null /*targetPackage*/,
1499                                        null /*finishedReceiver*/, updateUsers);
1500                            }
1501                            if (update) {
1502                                if (!isEphemeral) {
1503                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1504                                            packageName, extras, 0 /*flags*/,
1505                                            null /*targetPackage*/, null /*finishedReceiver*/,
1506                                            updateUsers);
1507                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1508                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1509                                            packageName /*targetPackage*/,
1510                                            null /*finishedReceiver*/, updateUsers);
1511                                }
1512
1513                                // treat asec-hosted packages like removable media on upgrade
1514                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1515                                    if (DEBUG_INSTALL) {
1516                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1517                                                + " is ASEC-hosted -> AVAILABLE");
1518                                    }
1519                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1520                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1521                                    pkgList.add(packageName);
1522                                    sendResourcesChangedBroadcast(true, true,
1523                                            pkgList,uidArray, null);
1524                                }
1525                            }
1526                            if (res.removedInfo.args != null) {
1527                                // Remove the replaced package's older resources safely now
1528                                deleteOld = true;
1529                            }
1530
1531
1532                            // Work that needs to happen on first install within each user
1533                            if (firstUsers.length > 0) {
1534                                for (int userId : firstUsers) {
1535                                    synchronized (mPackages) {
1536                                        // If this app is a browser and it's newly-installed for
1537                                        // some users, clear any default-browser state in those
1538                                        // users.  The app's nature doesn't depend on the user,
1539                                        // so we can just check its browser nature in any user
1540                                        // and generalize.
1541                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1542                                            mSettings.setDefaultBrowserPackageNameLPw(
1543                                                    null, userId);
1544                                        }
1545
1546                                        // We may also need to apply pending (restored) runtime
1547                                        // permission grants within these users.
1548                                        mSettings.applyPendingPermissionGrantsLPw(
1549                                                packageName, userId);
1550                                    }
1551                                }
1552                            }
1553                            // Log current value of "unknown sources" setting
1554                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1555                                getUnknownSourcesSettings());
1556                        }
1557                        // Force a gc to clear up things
1558                        Runtime.getRuntime().gc();
1559                        // We delete after a gc for applications  on sdcard.
1560                        if (deleteOld) {
1561                            synchronized (mInstallLock) {
1562                                res.removedInfo.args.doPostDeleteLI(true);
1563                            }
1564                        }
1565                        if (args.observer != null) {
1566                            try {
1567                                Bundle extras = extrasForInstallResult(res);
1568                                args.observer.onPackageInstalled(res.name, res.returnCode,
1569                                        res.returnMsg, extras);
1570                            } catch (RemoteException e) {
1571                                Slog.i(TAG, "Observer no longer exists.");
1572                            }
1573                        }
1574                        if (args.traceMethod != null) {
1575                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1576                                    args.traceCookie);
1577                        }
1578                        return;
1579                    } else {
1580                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1581                    }
1582
1583                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1584                } break;
1585                case UPDATED_MEDIA_STATUS: {
1586                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1587                    boolean reportStatus = msg.arg1 == 1;
1588                    boolean doGc = msg.arg2 == 1;
1589                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1590                    if (doGc) {
1591                        // Force a gc to clear up stale containers.
1592                        Runtime.getRuntime().gc();
1593                    }
1594                    if (msg.obj != null) {
1595                        @SuppressWarnings("unchecked")
1596                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1597                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1598                        // Unload containers
1599                        unloadAllContainers(args);
1600                    }
1601                    if (reportStatus) {
1602                        try {
1603                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1604                            PackageHelper.getMountService().finishMediaUpdate();
1605                        } catch (RemoteException e) {
1606                            Log.e(TAG, "MountService not running?");
1607                        }
1608                    }
1609                } break;
1610                case WRITE_SETTINGS: {
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        removeMessages(WRITE_SETTINGS);
1614                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1615                        mSettings.writeLPr();
1616                        mDirtyUsers.clear();
1617                    }
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1619                } break;
1620                case WRITE_PACKAGE_RESTRICTIONS: {
1621                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1622                    synchronized (mPackages) {
1623                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1624                        for (int userId : mDirtyUsers) {
1625                            mSettings.writePackageRestrictionsLPr(userId);
1626                        }
1627                        mDirtyUsers.clear();
1628                    }
1629                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1630                } break;
1631                case CHECK_PENDING_VERIFICATION: {
1632                    final int verificationId = msg.arg1;
1633                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1634
1635                    if ((state != null) && !state.timeoutExtended()) {
1636                        final InstallArgs args = state.getInstallArgs();
1637                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1638
1639                        Slog.i(TAG, "Verification timed out for " + originUri);
1640                        mPendingVerification.remove(verificationId);
1641
1642                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1643
1644                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1645                            Slog.i(TAG, "Continuing with installation of " + originUri);
1646                            state.setVerifierResponse(Binder.getCallingUid(),
1647                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1648                            broadcastPackageVerified(verificationId, originUri,
1649                                    PackageManager.VERIFICATION_ALLOW,
1650                                    state.getInstallArgs().getUser());
1651                            try {
1652                                ret = args.copyApk(mContainerService, true);
1653                            } catch (RemoteException e) {
1654                                Slog.e(TAG, "Could not contact the ContainerService");
1655                            }
1656                        } else {
1657                            broadcastPackageVerified(verificationId, originUri,
1658                                    PackageManager.VERIFICATION_REJECT,
1659                                    state.getInstallArgs().getUser());
1660                        }
1661
1662                        Trace.asyncTraceEnd(
1663                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1664
1665                        processPendingInstall(args, ret);
1666                        mHandler.sendEmptyMessage(MCS_UNBIND);
1667                    }
1668                    break;
1669                }
1670                case PACKAGE_VERIFIED: {
1671                    final int verificationId = msg.arg1;
1672
1673                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1674                    if (state == null) {
1675                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1676                        break;
1677                    }
1678
1679                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1680
1681                    state.setVerifierResponse(response.callerUid, response.code);
1682
1683                    if (state.isVerificationComplete()) {
1684                        mPendingVerification.remove(verificationId);
1685
1686                        final InstallArgs args = state.getInstallArgs();
1687                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1688
1689                        int ret;
1690                        if (state.isInstallAllowed()) {
1691                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1692                            broadcastPackageVerified(verificationId, originUri,
1693                                    response.code, state.getInstallArgs().getUser());
1694                            try {
1695                                ret = args.copyApk(mContainerService, true);
1696                            } catch (RemoteException e) {
1697                                Slog.e(TAG, "Could not contact the ContainerService");
1698                            }
1699                        } else {
1700                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1701                        }
1702
1703                        Trace.asyncTraceEnd(
1704                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1705
1706                        processPendingInstall(args, ret);
1707                        mHandler.sendEmptyMessage(MCS_UNBIND);
1708                    }
1709
1710                    break;
1711                }
1712                case START_INTENT_FILTER_VERIFICATIONS: {
1713                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1714                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1715                            params.replacing, params.pkg);
1716                    break;
1717                }
1718                case INTENT_FILTER_VERIFIED: {
1719                    final int verificationId = msg.arg1;
1720
1721                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1722                            verificationId);
1723                    if (state == null) {
1724                        Slog.w(TAG, "Invalid IntentFilter verification token "
1725                                + verificationId + " received");
1726                        break;
1727                    }
1728
1729                    final int userId = state.getUserId();
1730
1731                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1732                            "Processing IntentFilter verification with token:"
1733                            + verificationId + " and userId:" + userId);
1734
1735                    final IntentFilterVerificationResponse response =
1736                            (IntentFilterVerificationResponse) msg.obj;
1737
1738                    state.setVerifierResponse(response.callerUid, response.code);
1739
1740                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1741                            "IntentFilter verification with token:" + verificationId
1742                            + " and userId:" + userId
1743                            + " is settings verifier response with response code:"
1744                            + response.code);
1745
1746                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1747                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1748                                + response.getFailedDomainsString());
1749                    }
1750
1751                    if (state.isVerificationComplete()) {
1752                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1753                    } else {
1754                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1755                                "IntentFilter verification with token:" + verificationId
1756                                + " was not said to be complete");
1757                    }
1758
1759                    break;
1760                }
1761            }
1762        }
1763    }
1764
1765    private StorageEventListener mStorageListener = new StorageEventListener() {
1766        @Override
1767        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1768            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1769                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1770                    final String volumeUuid = vol.getFsUuid();
1771
1772                    // Clean up any users or apps that were removed or recreated
1773                    // while this volume was missing
1774                    reconcileUsers(volumeUuid);
1775                    reconcileApps(volumeUuid);
1776
1777                    // Clean up any install sessions that expired or were
1778                    // cancelled while this volume was missing
1779                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1780
1781                    loadPrivatePackages(vol);
1782
1783                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1784                    unloadPrivatePackages(vol);
1785                }
1786            }
1787
1788            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1789                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1790                    updateExternalMediaStatus(true, false);
1791                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1792                    updateExternalMediaStatus(false, false);
1793                }
1794            }
1795        }
1796
1797        @Override
1798        public void onVolumeForgotten(String fsUuid) {
1799            if (TextUtils.isEmpty(fsUuid)) {
1800                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1801                return;
1802            }
1803
1804            // Remove any apps installed on the forgotten volume
1805            synchronized (mPackages) {
1806                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1807                for (PackageSetting ps : packages) {
1808                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1809                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1810                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1811                }
1812
1813                mSettings.onVolumeForgotten(fsUuid);
1814                mSettings.writeLPr();
1815            }
1816        }
1817    };
1818
1819    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1820            String[] grantedPermissions) {
1821        if (userId >= UserHandle.USER_SYSTEM) {
1822            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1823        } else if (userId == UserHandle.USER_ALL) {
1824            final int[] userIds;
1825            synchronized (mPackages) {
1826                userIds = UserManagerService.getInstance().getUserIds();
1827            }
1828            for (int someUserId : userIds) {
1829                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1830            }
1831        }
1832
1833        // We could have touched GID membership, so flush out packages.list
1834        synchronized (mPackages) {
1835            mSettings.writePackageListLPr();
1836        }
1837    }
1838
1839    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1840            String[] grantedPermissions) {
1841        SettingBase sb = (SettingBase) pkg.mExtras;
1842        if (sb == null) {
1843            return;
1844        }
1845
1846        PermissionsState permissionsState = sb.getPermissionsState();
1847
1848        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1849                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1850
1851        synchronized (mPackages) {
1852            for (String permission : pkg.requestedPermissions) {
1853                BasePermission bp = mSettings.mPermissions.get(permission);
1854                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1855                        && (grantedPermissions == null
1856                               || ArrayUtils.contains(grantedPermissions, permission))) {
1857                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1858                    // Installer cannot change immutable permissions.
1859                    if ((flags & immutableFlags) == 0) {
1860                        grantRuntimePermission(pkg.packageName, permission, userId);
1861                    }
1862                }
1863            }
1864        }
1865    }
1866
1867    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1868        Bundle extras = null;
1869        switch (res.returnCode) {
1870            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1871                extras = new Bundle();
1872                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1873                        res.origPermission);
1874                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1875                        res.origPackage);
1876                break;
1877            }
1878            case PackageManager.INSTALL_SUCCEEDED: {
1879                extras = new Bundle();
1880                extras.putBoolean(Intent.EXTRA_REPLACING,
1881                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1882                break;
1883            }
1884        }
1885        return extras;
1886    }
1887
1888    void scheduleWriteSettingsLocked() {
1889        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1890            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1891        }
1892    }
1893
1894    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1895        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1896        scheduleWritePackageRestrictionsLocked(userId);
1897    }
1898
1899    void scheduleWritePackageRestrictionsLocked(int userId) {
1900        final int[] userIds = (userId == UserHandle.USER_ALL)
1901                ? sUserManager.getUserIds() : new int[]{userId};
1902        for (int nextUserId : userIds) {
1903            if (!sUserManager.exists(nextUserId)) return;
1904            mDirtyUsers.add(nextUserId);
1905            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1906                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1907            }
1908        }
1909    }
1910
1911    public static PackageManagerService main(Context context, Installer installer,
1912            boolean factoryTest, boolean onlyCore) {
1913        PackageManagerService m = new PackageManagerService(context, installer,
1914                factoryTest, onlyCore);
1915        m.enableSystemUserPackages();
1916        ServiceManager.addService("package", m);
1917        return m;
1918    }
1919
1920    private void enableSystemUserPackages() {
1921        if (!UserManager.isSplitSystemUser()) {
1922            return;
1923        }
1924        // For system user, enable apps based on the following conditions:
1925        // - app is whitelisted or belong to one of these groups:
1926        //   -- system app which has no launcher icons
1927        //   -- system app which has INTERACT_ACROSS_USERS permission
1928        //   -- system IME app
1929        // - app is not in the blacklist
1930        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1931        Set<String> enableApps = new ArraySet<>();
1932        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1933                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1934                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1935        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1936        enableApps.addAll(wlApps);
1937        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1938                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1939        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1940        enableApps.removeAll(blApps);
1941        Log.i(TAG, "Applications installed for system user: " + enableApps);
1942        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1943                UserHandle.SYSTEM);
1944        final int allAppsSize = allAps.size();
1945        synchronized (mPackages) {
1946            for (int i = 0; i < allAppsSize; i++) {
1947                String pName = allAps.get(i);
1948                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1949                // Should not happen, but we shouldn't be failing if it does
1950                if (pkgSetting == null) {
1951                    continue;
1952                }
1953                boolean install = enableApps.contains(pName);
1954                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1955                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1956                            + " for system user");
1957                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1958                }
1959            }
1960        }
1961    }
1962
1963    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1964        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1965                Context.DISPLAY_SERVICE);
1966        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1967    }
1968
1969    public PackageManagerService(Context context, Installer installer,
1970            boolean factoryTest, boolean onlyCore) {
1971        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1972                SystemClock.uptimeMillis());
1973
1974        if (mSdkVersion <= 0) {
1975            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1976        }
1977
1978        mContext = context;
1979        mFactoryTest = factoryTest;
1980        mOnlyCore = onlyCore;
1981        mMetrics = new DisplayMetrics();
1982        mSettings = new Settings(mPackages);
1983        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1984                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1985        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1986                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1987        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1988                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1989        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1990                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1991        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1992                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1993        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1994                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1995
1996        String separateProcesses = SystemProperties.get("debug.separate_processes");
1997        if (separateProcesses != null && separateProcesses.length() > 0) {
1998            if ("*".equals(separateProcesses)) {
1999                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2000                mSeparateProcesses = null;
2001                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2002            } else {
2003                mDefParseFlags = 0;
2004                mSeparateProcesses = separateProcesses.split(",");
2005                Slog.w(TAG, "Running with debug.separate_processes: "
2006                        + separateProcesses);
2007            }
2008        } else {
2009            mDefParseFlags = 0;
2010            mSeparateProcesses = null;
2011        }
2012
2013        mInstaller = installer;
2014        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2015                "*dexopt*");
2016        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2017
2018        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2019                FgThread.get().getLooper());
2020
2021        getDefaultDisplayMetrics(context, mMetrics);
2022
2023        SystemConfig systemConfig = SystemConfig.getInstance();
2024        mGlobalGids = systemConfig.getGlobalGids();
2025        mSystemPermissions = systemConfig.getSystemPermissions();
2026        mAvailableFeatures = systemConfig.getAvailableFeatures();
2027
2028        synchronized (mInstallLock) {
2029        // writer
2030        synchronized (mPackages) {
2031            mHandlerThread = new ServiceThread(TAG,
2032                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2033            mHandlerThread.start();
2034            mHandler = new PackageHandler(mHandlerThread.getLooper());
2035            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2036
2037            File dataDir = Environment.getDataDirectory();
2038            mAppInstallDir = new File(dataDir, "app");
2039            mAppLib32InstallDir = new File(dataDir, "app-lib");
2040            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2041            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2042            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2043
2044            sUserManager = new UserManagerService(context, this, mPackages);
2045
2046            // Propagate permission configuration in to package manager.
2047            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2048                    = systemConfig.getPermissions();
2049            for (int i=0; i<permConfig.size(); i++) {
2050                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2051                BasePermission bp = mSettings.mPermissions.get(perm.name);
2052                if (bp == null) {
2053                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2054                    mSettings.mPermissions.put(perm.name, bp);
2055                }
2056                if (perm.gids != null) {
2057                    bp.setGids(perm.gids, perm.perUser);
2058                }
2059            }
2060
2061            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2062            for (int i=0; i<libConfig.size(); i++) {
2063                mSharedLibraries.put(libConfig.keyAt(i),
2064                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2065            }
2066
2067            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2068
2069            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2070
2071            String customResolverActivity = Resources.getSystem().getString(
2072                    R.string.config_customResolverActivity);
2073            if (TextUtils.isEmpty(customResolverActivity)) {
2074                customResolverActivity = null;
2075            } else {
2076                mCustomResolverComponentName = ComponentName.unflattenFromString(
2077                        customResolverActivity);
2078            }
2079
2080            long startTime = SystemClock.uptimeMillis();
2081
2082            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2083                    startTime);
2084
2085            // Set flag to monitor and not change apk file paths when
2086            // scanning install directories.
2087            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2088
2089            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2090            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2091
2092            if (bootClassPath == null) {
2093                Slog.w(TAG, "No BOOTCLASSPATH found!");
2094            }
2095
2096            if (systemServerClassPath == null) {
2097                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2098            }
2099
2100            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2101            final String[] dexCodeInstructionSets =
2102                    getDexCodeInstructionSets(
2103                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2104
2105            /**
2106             * Ensure all external libraries have had dexopt run on them.
2107             */
2108            if (mSharedLibraries.size() > 0) {
2109                // NOTE: For now, we're compiling these system "shared libraries"
2110                // (and framework jars) into all available architectures. It's possible
2111                // to compile them only when we come across an app that uses them (there's
2112                // already logic for that in scanPackageLI) but that adds some complexity.
2113                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2114                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2115                        final String lib = libEntry.path;
2116                        if (lib == null) {
2117                            continue;
2118                        }
2119
2120                        try {
2121                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2122                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2123                                // Shared libraries do not have profiles so we perform a full
2124                                // AOT compilation.
2125                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2126                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2127                                        StorageManager.UUID_PRIVATE_INTERNAL,
2128                                        false /*useProfiles*/);
2129                            }
2130                        } catch (FileNotFoundException e) {
2131                            Slog.w(TAG, "Library not found: " + lib);
2132                        } catch (IOException | InstallerException e) {
2133                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2134                                    + e.getMessage());
2135                        }
2136                    }
2137                }
2138            }
2139
2140            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2141
2142            final VersionInfo ver = mSettings.getInternalVersion();
2143            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2144            // when upgrading from pre-M, promote system app permissions from install to runtime
2145            mPromoteSystemApps =
2146                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2147
2148            // save off the names of pre-existing system packages prior to scanning; we don't
2149            // want to automatically grant runtime permissions for new system apps
2150            if (mPromoteSystemApps) {
2151                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2152                while (pkgSettingIter.hasNext()) {
2153                    PackageSetting ps = pkgSettingIter.next();
2154                    if (isSystemApp(ps)) {
2155                        mExistingSystemPackages.add(ps.name);
2156                    }
2157                }
2158            }
2159
2160            // Collect vendor overlay packages.
2161            // (Do this before scanning any apps.)
2162            // For security and version matching reason, only consider
2163            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2164            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2165            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2166                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2167
2168            // Find base frameworks (resource packages without code).
2169            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2170                    | PackageParser.PARSE_IS_SYSTEM_DIR
2171                    | PackageParser.PARSE_IS_PRIVILEGED,
2172                    scanFlags | SCAN_NO_DEX, 0);
2173
2174            // Collected privileged system packages.
2175            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2176            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2177                    | PackageParser.PARSE_IS_SYSTEM_DIR
2178                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2179
2180            // Collect ordinary system packages.
2181            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2182            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2183                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2184
2185            // Collect all vendor packages.
2186            File vendorAppDir = new File("/vendor/app");
2187            try {
2188                vendorAppDir = vendorAppDir.getCanonicalFile();
2189            } catch (IOException e) {
2190                // failed to look up canonical path, continue with original one
2191            }
2192            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2193                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2194
2195            // Collect all OEM packages.
2196            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2197            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2198                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2199
2200            // Prune any system packages that no longer exist.
2201            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2202            if (!mOnlyCore) {
2203                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2204                while (psit.hasNext()) {
2205                    PackageSetting ps = psit.next();
2206
2207                    /*
2208                     * If this is not a system app, it can't be a
2209                     * disable system app.
2210                     */
2211                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2212                        continue;
2213                    }
2214
2215                    /*
2216                     * If the package is scanned, it's not erased.
2217                     */
2218                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2219                    if (scannedPkg != null) {
2220                        /*
2221                         * If the system app is both scanned and in the
2222                         * disabled packages list, then it must have been
2223                         * added via OTA. Remove it from the currently
2224                         * scanned package so the previously user-installed
2225                         * application can be scanned.
2226                         */
2227                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2228                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2229                                    + ps.name + "; removing system app.  Last known codePath="
2230                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2231                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2232                                    + scannedPkg.mVersionCode);
2233                            removePackageSettingLI(scannedPkg, true);
2234                            mExpectingBetter.put(ps.name, ps.codePath);
2235                        }
2236
2237                        continue;
2238                    }
2239
2240                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2241                        psit.remove();
2242                        logCriticalInfo(Log.WARN, "System package " + ps.name
2243                                + " no longer exists; wiping its data");
2244                        removeDataDirsLI(null, ps.name);
2245                    } else {
2246                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2247                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2248                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2249                        }
2250                    }
2251                }
2252            }
2253
2254            //look for any incomplete package installations
2255            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2256            //clean up list
2257            for(int i = 0; i < deletePkgsList.size(); i++) {
2258                //clean up here
2259                cleanupInstallFailedPackage(deletePkgsList.get(i));
2260            }
2261            //delete tmp files
2262            deleteTempPackageFiles();
2263
2264            // Remove any shared userIDs that have no associated packages
2265            mSettings.pruneSharedUsersLPw();
2266
2267            if (!mOnlyCore) {
2268                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2269                        SystemClock.uptimeMillis());
2270                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2271
2272                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2273                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2274
2275                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2276                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2277
2278                /**
2279                 * Remove disable package settings for any updated system
2280                 * apps that were removed via an OTA. If they're not a
2281                 * previously-updated app, remove them completely.
2282                 * Otherwise, just revoke their system-level permissions.
2283                 */
2284                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2285                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2286                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2287
2288                    String msg;
2289                    if (deletedPkg == null) {
2290                        msg = "Updated system package " + deletedAppName
2291                                + " no longer exists; wiping its data";
2292                        removeDataDirsLI(null, deletedAppName);
2293                    } else {
2294                        msg = "Updated system app + " + deletedAppName
2295                                + " no longer present; removing system privileges for "
2296                                + deletedAppName;
2297
2298                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2299
2300                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2301                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2302                    }
2303                    logCriticalInfo(Log.WARN, msg);
2304                }
2305
2306                /**
2307                 * Make sure all system apps that we expected to appear on
2308                 * the userdata partition actually showed up. If they never
2309                 * appeared, crawl back and revive the system version.
2310                 */
2311                for (int i = 0; i < mExpectingBetter.size(); i++) {
2312                    final String packageName = mExpectingBetter.keyAt(i);
2313                    if (!mPackages.containsKey(packageName)) {
2314                        final File scanFile = mExpectingBetter.valueAt(i);
2315
2316                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2317                                + " but never showed up; reverting to system");
2318
2319                        final int reparseFlags;
2320                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2321                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2322                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2323                                    | PackageParser.PARSE_IS_PRIVILEGED;
2324                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2325                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2326                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2327                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2328                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2329                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2330                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2331                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2332                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2333                        } else {
2334                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2335                            continue;
2336                        }
2337
2338                        mSettings.enableSystemPackageLPw(packageName);
2339
2340                        try {
2341                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2342                        } catch (PackageManagerException e) {
2343                            Slog.e(TAG, "Failed to parse original system package: "
2344                                    + e.getMessage());
2345                        }
2346                    }
2347                }
2348            }
2349            mExpectingBetter.clear();
2350
2351            // Now that we know all of the shared libraries, update all clients to have
2352            // the correct library paths.
2353            updateAllSharedLibrariesLPw();
2354
2355            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2356                // NOTE: We ignore potential failures here during a system scan (like
2357                // the rest of the commands above) because there's precious little we
2358                // can do about it. A settings error is reported, though.
2359                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2360                        false /* boot complete */);
2361            }
2362
2363            // Now that we know all the packages we are keeping,
2364            // read and update their last usage times.
2365            mPackageUsage.readLP();
2366
2367            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2368                    SystemClock.uptimeMillis());
2369            Slog.i(TAG, "Time to scan packages: "
2370                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2371                    + " seconds");
2372
2373            // If the platform SDK has changed since the last time we booted,
2374            // we need to re-grant app permission to catch any new ones that
2375            // appear.  This is really a hack, and means that apps can in some
2376            // cases get permissions that the user didn't initially explicitly
2377            // allow...  it would be nice to have some better way to handle
2378            // this situation.
2379            int updateFlags = UPDATE_PERMISSIONS_ALL;
2380            if (ver.sdkVersion != mSdkVersion) {
2381                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2382                        + mSdkVersion + "; regranting permissions for internal storage");
2383                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2384            }
2385            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2386            ver.sdkVersion = mSdkVersion;
2387
2388            // If this is the first boot or an update from pre-M, and it is a normal
2389            // boot, then we need to initialize the default preferred apps across
2390            // all defined users.
2391            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2392                for (UserInfo user : sUserManager.getUsers(true)) {
2393                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2394                    applyFactoryDefaultBrowserLPw(user.id);
2395                    primeDomainVerificationsLPw(user.id);
2396                }
2397            }
2398
2399            // Prepare storage for system user really early during boot,
2400            // since core system apps like SettingsProvider and SystemUI
2401            // can't wait for user to start
2402            final int storageFlags;
2403            if (StorageManager.isFileBasedEncryptionEnabled()) {
2404                storageFlags = StorageManager.FLAG_STORAGE_DE;
2405            } else {
2406                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2407            }
2408            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2409                    storageFlags);
2410
2411            if (!StorageManager.isFileBasedEncryptionEnabled()
2412                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2413                // When upgrading a non-FBE device, we might need to shuffle
2414                // around the default storage location of system apps
2415                final List<UserInfo> users = sUserManager.getUsers(true);
2416                for (PackageSetting ps : mSettings.mPackages.values()) {
2417                    if (ps.pkg == null || !ps.isSystem()) continue;
2418                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2419                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2420                    for (UserInfo user : users) {
2421                        if (ps.getInstalled(user.id)) {
2422                            try {
2423                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2424                                        ps.name, user.id, storageTarget);
2425                            } catch (InstallerException e) {
2426                                logCriticalInfo(Log.WARN,
2427                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2428                            }
2429                            // We may have just shuffled around app data
2430                            // directories, so prepare it one more time
2431                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2432                                    storageFlags, ps.pkg, false);
2433                        }
2434                    }
2435                }
2436            }
2437
2438            // If this is first boot after an OTA, and a normal boot, then
2439            // we need to clear code cache directories.
2440            if (mIsUpgrade && !onlyCore) {
2441                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2442                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2443                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2444                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2445                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2446                    }
2447                }
2448                ver.fingerprint = Build.FINGERPRINT;
2449            }
2450
2451            checkDefaultBrowser();
2452
2453            // clear only after permissions and other defaults have been updated
2454            mExistingSystemPackages.clear();
2455            mPromoteSystemApps = false;
2456
2457            // All the changes are done during package scanning.
2458            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2459
2460            // can downgrade to reader
2461            mSettings.writeLPr();
2462
2463            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2464                    SystemClock.uptimeMillis());
2465
2466            if (!mOnlyCore) {
2467                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2468                mRequiredInstallerPackage = getRequiredInstallerLPr();
2469                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2470                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2471                        mIntentFilterVerifierComponent);
2472            } else {
2473                mRequiredVerifierPackage = null;
2474                mRequiredInstallerPackage = null;
2475                mIntentFilterVerifierComponent = null;
2476                mIntentFilterVerifier = null;
2477            }
2478
2479            mInstallerService = new PackageInstallerService(context, this);
2480
2481            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2482            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2483            // both the installer and resolver must be present to enable ephemeral
2484            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2485                if (DEBUG_EPHEMERAL) {
2486                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2487                            + " installer:" + ephemeralInstallerComponent);
2488                }
2489                mEphemeralResolverComponent = ephemeralResolverComponent;
2490                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2491                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2492                mEphemeralResolverConnection =
2493                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2494            } else {
2495                if (DEBUG_EPHEMERAL) {
2496                    final String missingComponent =
2497                            (ephemeralResolverComponent == null)
2498                            ? (ephemeralInstallerComponent == null)
2499                                    ? "resolver and installer"
2500                                    : "resolver"
2501                            : "installer";
2502                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2503                }
2504                mEphemeralResolverComponent = null;
2505                mEphemeralInstallerComponent = null;
2506                mEphemeralResolverConnection = null;
2507            }
2508
2509            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2510        } // synchronized (mPackages)
2511        } // synchronized (mInstallLock)
2512
2513        // Now after opening every single application zip, make sure they
2514        // are all flushed.  Not really needed, but keeps things nice and
2515        // tidy.
2516        Runtime.getRuntime().gc();
2517
2518        // The initial scanning above does many calls into installd while
2519        // holding the mPackages lock, but we're mostly interested in yelling
2520        // once we have a booted system.
2521        mInstaller.setWarnIfHeld(mPackages);
2522
2523        // Expose private service for system components to use.
2524        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2525    }
2526
2527    @Override
2528    public boolean isFirstBoot() {
2529        return !mRestoredSettings;
2530    }
2531
2532    @Override
2533    public boolean isOnlyCoreApps() {
2534        return mOnlyCore;
2535    }
2536
2537    @Override
2538    public boolean isUpgrade() {
2539        return mIsUpgrade;
2540    }
2541
2542    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2543        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2544
2545        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2546                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2547        if (matches.size() == 1) {
2548            return matches.get(0).getComponentInfo().packageName;
2549        } else {
2550            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2551            return null;
2552        }
2553    }
2554
2555    private @NonNull String getRequiredInstallerLPr() {
2556        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2557        intent.addCategory(Intent.CATEGORY_DEFAULT);
2558        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2559
2560        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2561                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2562        if (matches.size() == 1) {
2563            return matches.get(0).getComponentInfo().packageName;
2564        } else {
2565            throw new RuntimeException("There must be exactly one installer; found " + matches);
2566        }
2567    }
2568
2569    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2570        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2571
2572        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2573                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2574        ResolveInfo best = null;
2575        final int N = matches.size();
2576        for (int i = 0; i < N; i++) {
2577            final ResolveInfo cur = matches.get(i);
2578            final String packageName = cur.getComponentInfo().packageName;
2579            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2580                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2581                continue;
2582            }
2583
2584            if (best == null || cur.priority > best.priority) {
2585                best = cur;
2586            }
2587        }
2588
2589        if (best != null) {
2590            return best.getComponentInfo().getComponentName();
2591        } else {
2592            throw new RuntimeException("There must be at least one intent filter verifier");
2593        }
2594    }
2595
2596    private @Nullable ComponentName getEphemeralResolverLPr() {
2597        final String[] packageArray =
2598                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2599        if (packageArray.length == 0) {
2600            if (DEBUG_EPHEMERAL) {
2601                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2602            }
2603            return null;
2604        }
2605
2606        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2607        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2608                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2609
2610        final int N = resolvers.size();
2611        if (N == 0) {
2612            if (DEBUG_EPHEMERAL) {
2613                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2614            }
2615            return null;
2616        }
2617
2618        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2619        for (int i = 0; i < N; i++) {
2620            final ResolveInfo info = resolvers.get(i);
2621
2622            if (info.serviceInfo == null) {
2623                continue;
2624            }
2625
2626            final String packageName = info.serviceInfo.packageName;
2627            if (!possiblePackages.contains(packageName)) {
2628                if (DEBUG_EPHEMERAL) {
2629                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2630                            + " pkg: " + packageName + ", info:" + info);
2631                }
2632                continue;
2633            }
2634
2635            if (DEBUG_EPHEMERAL) {
2636                Slog.v(TAG, "Ephemeral resolver found;"
2637                        + " pkg: " + packageName + ", info:" + info);
2638            }
2639            return new ComponentName(packageName, info.serviceInfo.name);
2640        }
2641        if (DEBUG_EPHEMERAL) {
2642            Slog.v(TAG, "Ephemeral resolver NOT found");
2643        }
2644        return null;
2645    }
2646
2647    private @Nullable ComponentName getEphemeralInstallerLPr() {
2648        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2649        intent.addCategory(Intent.CATEGORY_DEFAULT);
2650        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2651
2652        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2653                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2654        if (matches.size() == 0) {
2655            return null;
2656        } else if (matches.size() == 1) {
2657            return matches.get(0).getComponentInfo().getComponentName();
2658        } else {
2659            throw new RuntimeException(
2660                    "There must be at most one ephemeral installer; found " + matches);
2661        }
2662    }
2663
2664    private void primeDomainVerificationsLPw(int userId) {
2665        if (DEBUG_DOMAIN_VERIFICATION) {
2666            Slog.d(TAG, "Priming domain verifications in user " + userId);
2667        }
2668
2669        SystemConfig systemConfig = SystemConfig.getInstance();
2670        ArraySet<String> packages = systemConfig.getLinkedApps();
2671        ArraySet<String> domains = new ArraySet<String>();
2672
2673        for (String packageName : packages) {
2674            PackageParser.Package pkg = mPackages.get(packageName);
2675            if (pkg != null) {
2676                if (!pkg.isSystemApp()) {
2677                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2678                    continue;
2679                }
2680
2681                domains.clear();
2682                for (PackageParser.Activity a : pkg.activities) {
2683                    for (ActivityIntentInfo filter : a.intents) {
2684                        if (hasValidDomains(filter)) {
2685                            domains.addAll(filter.getHostsList());
2686                        }
2687                    }
2688                }
2689
2690                if (domains.size() > 0) {
2691                    if (DEBUG_DOMAIN_VERIFICATION) {
2692                        Slog.v(TAG, "      + " + packageName);
2693                    }
2694                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2695                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2696                    // and then 'always' in the per-user state actually used for intent resolution.
2697                    final IntentFilterVerificationInfo ivi;
2698                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2699                            new ArrayList<String>(domains));
2700                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2701                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2702                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2703                } else {
2704                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2705                            + "' does not handle web links");
2706                }
2707            } else {
2708                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2709            }
2710        }
2711
2712        scheduleWritePackageRestrictionsLocked(userId);
2713        scheduleWriteSettingsLocked();
2714    }
2715
2716    private void applyFactoryDefaultBrowserLPw(int userId) {
2717        // The default browser app's package name is stored in a string resource,
2718        // with a product-specific overlay used for vendor customization.
2719        String browserPkg = mContext.getResources().getString(
2720                com.android.internal.R.string.default_browser);
2721        if (!TextUtils.isEmpty(browserPkg)) {
2722            // non-empty string => required to be a known package
2723            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2724            if (ps == null) {
2725                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2726                browserPkg = null;
2727            } else {
2728                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2729            }
2730        }
2731
2732        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2733        // default.  If there's more than one, just leave everything alone.
2734        if (browserPkg == null) {
2735            calculateDefaultBrowserLPw(userId);
2736        }
2737    }
2738
2739    private void calculateDefaultBrowserLPw(int userId) {
2740        List<String> allBrowsers = resolveAllBrowserApps(userId);
2741        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2742        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2743    }
2744
2745    private List<String> resolveAllBrowserApps(int userId) {
2746        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2747        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2748                PackageManager.MATCH_ALL, userId);
2749
2750        final int count = list.size();
2751        List<String> result = new ArrayList<String>(count);
2752        for (int i=0; i<count; i++) {
2753            ResolveInfo info = list.get(i);
2754            if (info.activityInfo == null
2755                    || !info.handleAllWebDataURI
2756                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2757                    || result.contains(info.activityInfo.packageName)) {
2758                continue;
2759            }
2760            result.add(info.activityInfo.packageName);
2761        }
2762
2763        return result;
2764    }
2765
2766    private boolean packageIsBrowser(String packageName, int userId) {
2767        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2768                PackageManager.MATCH_ALL, userId);
2769        final int N = list.size();
2770        for (int i = 0; i < N; i++) {
2771            ResolveInfo info = list.get(i);
2772            if (packageName.equals(info.activityInfo.packageName)) {
2773                return true;
2774            }
2775        }
2776        return false;
2777    }
2778
2779    private void checkDefaultBrowser() {
2780        final int myUserId = UserHandle.myUserId();
2781        final String packageName = getDefaultBrowserPackageName(myUserId);
2782        if (packageName != null) {
2783            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2784            if (info == null) {
2785                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2786                synchronized (mPackages) {
2787                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2788                }
2789            }
2790        }
2791    }
2792
2793    @Override
2794    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2795            throws RemoteException {
2796        try {
2797            return super.onTransact(code, data, reply, flags);
2798        } catch (RuntimeException e) {
2799            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2800                Slog.wtf(TAG, "Package Manager Crash", e);
2801            }
2802            throw e;
2803        }
2804    }
2805
2806    void cleanupInstallFailedPackage(PackageSetting ps) {
2807        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2808
2809        removeDataDirsLI(ps.volumeUuid, ps.name);
2810        if (ps.codePath != null) {
2811            removeCodePathLI(ps.codePath);
2812        }
2813        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2814            if (ps.resourcePath.isDirectory()) {
2815                FileUtils.deleteContents(ps.resourcePath);
2816            }
2817            ps.resourcePath.delete();
2818        }
2819        mSettings.removePackageLPw(ps.name);
2820    }
2821
2822    static int[] appendInts(int[] cur, int[] add) {
2823        if (add == null) return cur;
2824        if (cur == null) return add;
2825        final int N = add.length;
2826        for (int i=0; i<N; i++) {
2827            cur = appendInt(cur, add[i]);
2828        }
2829        return cur;
2830    }
2831
2832    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2833        if (!sUserManager.exists(userId)) return null;
2834        final PackageSetting ps = (PackageSetting) p.mExtras;
2835        if (ps == null) {
2836            return null;
2837        }
2838
2839        final PermissionsState permissionsState = ps.getPermissionsState();
2840
2841        final int[] gids = permissionsState.computeGids(userId);
2842        final Set<String> permissions = permissionsState.getPermissions(userId);
2843        final PackageUserState state = ps.readUserState(userId);
2844
2845        return PackageParser.generatePackageInfo(p, gids, flags,
2846                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2847    }
2848
2849    @Override
2850    public void checkPackageStartable(String packageName, int userId) {
2851        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2852
2853        synchronized (mPackages) {
2854            final PackageSetting ps = mSettings.mPackages.get(packageName);
2855            if (ps == null) {
2856                throw new SecurityException("Package " + packageName + " was not found!");
2857            }
2858
2859            if (ps.frozen) {
2860                throw new SecurityException("Package " + packageName + " is currently frozen!");
2861            }
2862
2863            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2864                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2865                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2866            }
2867        }
2868    }
2869
2870    @Override
2871    public boolean isPackageAvailable(String packageName, int userId) {
2872        if (!sUserManager.exists(userId)) return false;
2873        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2874        synchronized (mPackages) {
2875            PackageParser.Package p = mPackages.get(packageName);
2876            if (p != null) {
2877                final PackageSetting ps = (PackageSetting) p.mExtras;
2878                if (ps != null) {
2879                    final PackageUserState state = ps.readUserState(userId);
2880                    if (state != null) {
2881                        return PackageParser.isAvailable(state);
2882                    }
2883                }
2884            }
2885        }
2886        return false;
2887    }
2888
2889    @Override
2890    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2891        if (!sUserManager.exists(userId)) return null;
2892        flags = updateFlagsForPackage(flags, userId, packageName);
2893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2894        // reader
2895        synchronized (mPackages) {
2896            PackageParser.Package p = mPackages.get(packageName);
2897            if (DEBUG_PACKAGE_INFO)
2898                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2899            if (p != null) {
2900                return generatePackageInfo(p, flags, userId);
2901            }
2902            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2903                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2904            }
2905        }
2906        return null;
2907    }
2908
2909    @Override
2910    public String[] currentToCanonicalPackageNames(String[] names) {
2911        String[] out = new String[names.length];
2912        // reader
2913        synchronized (mPackages) {
2914            for (int i=names.length-1; i>=0; i--) {
2915                PackageSetting ps = mSettings.mPackages.get(names[i]);
2916                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2917            }
2918        }
2919        return out;
2920    }
2921
2922    @Override
2923    public String[] canonicalToCurrentPackageNames(String[] names) {
2924        String[] out = new String[names.length];
2925        // reader
2926        synchronized (mPackages) {
2927            for (int i=names.length-1; i>=0; i--) {
2928                String cur = mSettings.mRenamedPackages.get(names[i]);
2929                out[i] = cur != null ? cur : names[i];
2930            }
2931        }
2932        return out;
2933    }
2934
2935    @Override
2936    public int getPackageUid(String packageName, int flags, int userId) {
2937        if (!sUserManager.exists(userId)) return -1;
2938        flags = updateFlagsForPackage(flags, userId, packageName);
2939        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2940
2941        // reader
2942        synchronized (mPackages) {
2943            final PackageParser.Package p = mPackages.get(packageName);
2944            if (p != null && p.isMatch(flags)) {
2945                return UserHandle.getUid(userId, p.applicationInfo.uid);
2946            }
2947            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2948                final PackageSetting ps = mSettings.mPackages.get(packageName);
2949                if (ps != null && ps.isMatch(flags)) {
2950                    return UserHandle.getUid(userId, ps.appId);
2951                }
2952            }
2953        }
2954
2955        return -1;
2956    }
2957
2958    @Override
2959    public int[] getPackageGids(String packageName, int flags, int userId) {
2960        if (!sUserManager.exists(userId)) return null;
2961        flags = updateFlagsForPackage(flags, userId, packageName);
2962        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2963                "getPackageGids");
2964
2965        // reader
2966        synchronized (mPackages) {
2967            final PackageParser.Package p = mPackages.get(packageName);
2968            if (p != null && p.isMatch(flags)) {
2969                PackageSetting ps = (PackageSetting) p.mExtras;
2970                return ps.getPermissionsState().computeGids(userId);
2971            }
2972            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2973                final PackageSetting ps = mSettings.mPackages.get(packageName);
2974                if (ps != null && ps.isMatch(flags)) {
2975                    return ps.getPermissionsState().computeGids(userId);
2976                }
2977            }
2978        }
2979
2980        return null;
2981    }
2982
2983    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2984        if (bp.perm != null) {
2985            return PackageParser.generatePermissionInfo(bp.perm, flags);
2986        }
2987        PermissionInfo pi = new PermissionInfo();
2988        pi.name = bp.name;
2989        pi.packageName = bp.sourcePackage;
2990        pi.nonLocalizedLabel = bp.name;
2991        pi.protectionLevel = bp.protectionLevel;
2992        return pi;
2993    }
2994
2995    @Override
2996    public PermissionInfo getPermissionInfo(String name, int flags) {
2997        // reader
2998        synchronized (mPackages) {
2999            final BasePermission p = mSettings.mPermissions.get(name);
3000            if (p != null) {
3001                return generatePermissionInfo(p, flags);
3002            }
3003            return null;
3004        }
3005    }
3006
3007    @Override
3008    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3009        // reader
3010        synchronized (mPackages) {
3011            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3012            for (BasePermission p : mSettings.mPermissions.values()) {
3013                if (group == null) {
3014                    if (p.perm == null || p.perm.info.group == null) {
3015                        out.add(generatePermissionInfo(p, flags));
3016                    }
3017                } else {
3018                    if (p.perm != null && group.equals(p.perm.info.group)) {
3019                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3020                    }
3021                }
3022            }
3023
3024            if (out.size() > 0) {
3025                return out;
3026            }
3027            return mPermissionGroups.containsKey(group) ? out : null;
3028        }
3029    }
3030
3031    @Override
3032    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3033        // reader
3034        synchronized (mPackages) {
3035            return PackageParser.generatePermissionGroupInfo(
3036                    mPermissionGroups.get(name), flags);
3037        }
3038    }
3039
3040    @Override
3041    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3042        // reader
3043        synchronized (mPackages) {
3044            final int N = mPermissionGroups.size();
3045            ArrayList<PermissionGroupInfo> out
3046                    = new ArrayList<PermissionGroupInfo>(N);
3047            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3048                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3049            }
3050            return out;
3051        }
3052    }
3053
3054    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3055            int userId) {
3056        if (!sUserManager.exists(userId)) return null;
3057        PackageSetting ps = mSettings.mPackages.get(packageName);
3058        if (ps != null) {
3059            if (ps.pkg == null) {
3060                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3061                        flags, userId);
3062                if (pInfo != null) {
3063                    return pInfo.applicationInfo;
3064                }
3065                return null;
3066            }
3067            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3068                    ps.readUserState(userId), userId);
3069        }
3070        return null;
3071    }
3072
3073    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3074            int userId) {
3075        if (!sUserManager.exists(userId)) return null;
3076        PackageSetting ps = mSettings.mPackages.get(packageName);
3077        if (ps != null) {
3078            PackageParser.Package pkg = ps.pkg;
3079            if (pkg == null) {
3080                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3081                    return null;
3082                }
3083                // Only data remains, so we aren't worried about code paths
3084                pkg = new PackageParser.Package(packageName);
3085                pkg.applicationInfo.packageName = packageName;
3086                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3087                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3088                pkg.applicationInfo.uid = ps.appId;
3089                pkg.applicationInfo.initForUser(userId);
3090                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3091                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3092            }
3093            return generatePackageInfo(pkg, flags, userId);
3094        }
3095        return null;
3096    }
3097
3098    @Override
3099    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3100        if (!sUserManager.exists(userId)) return null;
3101        flags = updateFlagsForApplication(flags, userId, packageName);
3102        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3103        // writer
3104        synchronized (mPackages) {
3105            PackageParser.Package p = mPackages.get(packageName);
3106            if (DEBUG_PACKAGE_INFO) Log.v(
3107                    TAG, "getApplicationInfo " + packageName
3108                    + ": " + p);
3109            if (p != null) {
3110                PackageSetting ps = mSettings.mPackages.get(packageName);
3111                if (ps == null) return null;
3112                // Note: isEnabledLP() does not apply here - always return info
3113                return PackageParser.generateApplicationInfo(
3114                        p, flags, ps.readUserState(userId), userId);
3115            }
3116            if ("android".equals(packageName)||"system".equals(packageName)) {
3117                return mAndroidApplication;
3118            }
3119            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3120                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3121            }
3122        }
3123        return null;
3124    }
3125
3126    @Override
3127    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3128            final IPackageDataObserver observer) {
3129        mContext.enforceCallingOrSelfPermission(
3130                android.Manifest.permission.CLEAR_APP_CACHE, null);
3131        // Queue up an async operation since clearing cache may take a little while.
3132        mHandler.post(new Runnable() {
3133            public void run() {
3134                mHandler.removeCallbacks(this);
3135                boolean success = true;
3136                synchronized (mInstallLock) {
3137                    try {
3138                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3139                    } catch (InstallerException e) {
3140                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3141                        success = false;
3142                    }
3143                }
3144                if (observer != null) {
3145                    try {
3146                        observer.onRemoveCompleted(null, success);
3147                    } catch (RemoteException e) {
3148                        Slog.w(TAG, "RemoveException when invoking call back");
3149                    }
3150                }
3151            }
3152        });
3153    }
3154
3155    @Override
3156    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3157            final IntentSender pi) {
3158        mContext.enforceCallingOrSelfPermission(
3159                android.Manifest.permission.CLEAR_APP_CACHE, null);
3160        // Queue up an async operation since clearing cache may take a little while.
3161        mHandler.post(new Runnable() {
3162            public void run() {
3163                mHandler.removeCallbacks(this);
3164                boolean success = true;
3165                synchronized (mInstallLock) {
3166                    try {
3167                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3168                    } catch (InstallerException e) {
3169                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3170                        success = false;
3171                    }
3172                }
3173                if(pi != null) {
3174                    try {
3175                        // Callback via pending intent
3176                        int code = success ? 1 : 0;
3177                        pi.sendIntent(null, code, null,
3178                                null, null);
3179                    } catch (SendIntentException e1) {
3180                        Slog.i(TAG, "Failed to send pending intent");
3181                    }
3182                }
3183            }
3184        });
3185    }
3186
3187    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3188        synchronized (mInstallLock) {
3189            try {
3190                mInstaller.freeCache(volumeUuid, freeStorageSize);
3191            } catch (InstallerException e) {
3192                throw new IOException("Failed to free enough space", e);
3193            }
3194        }
3195    }
3196
3197    /**
3198     * Return if the user key is currently unlocked.
3199     */
3200    private boolean isUserKeyUnlocked(int userId) {
3201        if (StorageManager.isFileBasedEncryptionEnabled()) {
3202            final IMountService mount = IMountService.Stub
3203                    .asInterface(ServiceManager.getService("mount"));
3204            if (mount == null) {
3205                Slog.w(TAG, "Early during boot, assuming locked");
3206                return false;
3207            }
3208            final long token = Binder.clearCallingIdentity();
3209            try {
3210                return mount.isUserKeyUnlocked(userId);
3211            } catch (RemoteException e) {
3212                throw e.rethrowAsRuntimeException();
3213            } finally {
3214                Binder.restoreCallingIdentity(token);
3215            }
3216        } else {
3217            return true;
3218        }
3219    }
3220
3221    /**
3222     * Update given flags based on encryption status of current user.
3223     */
3224    private int updateFlags(int flags, int userId) {
3225        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3226                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3227            // Caller expressed an explicit opinion about what encryption
3228            // aware/unaware components they want to see, so fall through and
3229            // give them what they want
3230        } else {
3231            // Caller expressed no opinion, so match based on user state
3232            if (isUserKeyUnlocked(userId)) {
3233                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3234            } else {
3235                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3236            }
3237        }
3238
3239        // Safe mode means we should ignore any third-party apps
3240        if (mSafeMode) {
3241            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3242        }
3243
3244        return flags;
3245    }
3246
3247    /**
3248     * Update given flags when being used to request {@link PackageInfo}.
3249     */
3250    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3251        boolean triaged = true;
3252        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3253                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3254            // Caller is asking for component details, so they'd better be
3255            // asking for specific encryption matching behavior, or be triaged
3256            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3257                    | PackageManager.MATCH_ENCRYPTION_AWARE
3258                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3259                triaged = false;
3260            }
3261        }
3262        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3263                | PackageManager.MATCH_SYSTEM_ONLY
3264                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3265            triaged = false;
3266        }
3267        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3268            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3269                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3270        }
3271        return updateFlags(flags, userId);
3272    }
3273
3274    /**
3275     * Update given flags when being used to request {@link ApplicationInfo}.
3276     */
3277    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3278        return updateFlagsForPackage(flags, userId, cookie);
3279    }
3280
3281    /**
3282     * Update given flags when being used to request {@link ComponentInfo}.
3283     */
3284    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3285        if (cookie instanceof Intent) {
3286            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3287                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3288            }
3289        }
3290
3291        boolean triaged = true;
3292        // Caller is asking for component details, so they'd better be
3293        // asking for specific encryption matching behavior, or be triaged
3294        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3295                | PackageManager.MATCH_ENCRYPTION_AWARE
3296                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3297            triaged = false;
3298        }
3299        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3300            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3301                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3302        }
3303        return updateFlags(flags, userId);
3304    }
3305
3306    /**
3307     * Update given flags when being used to request {@link ResolveInfo}.
3308     */
3309    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3310        return updateFlagsForComponent(flags, userId, cookie);
3311    }
3312
3313    @Override
3314    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3315        if (!sUserManager.exists(userId)) return null;
3316        flags = updateFlagsForComponent(flags, userId, component);
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3318        synchronized (mPackages) {
3319            PackageParser.Activity a = mActivities.mActivities.get(component);
3320
3321            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3322            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3323                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3324                if (ps == null) return null;
3325                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3326                        userId);
3327            }
3328            if (mResolveComponentName.equals(component)) {
3329                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3330                        new PackageUserState(), userId);
3331            }
3332        }
3333        return null;
3334    }
3335
3336    @Override
3337    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3338            String resolvedType) {
3339        synchronized (mPackages) {
3340            if (component.equals(mResolveComponentName)) {
3341                // The resolver supports EVERYTHING!
3342                return true;
3343            }
3344            PackageParser.Activity a = mActivities.mActivities.get(component);
3345            if (a == null) {
3346                return false;
3347            }
3348            for (int i=0; i<a.intents.size(); i++) {
3349                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3350                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3351                    return true;
3352                }
3353            }
3354            return false;
3355        }
3356    }
3357
3358    @Override
3359    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3360        if (!sUserManager.exists(userId)) return null;
3361        flags = updateFlagsForComponent(flags, userId, component);
3362        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3363        synchronized (mPackages) {
3364            PackageParser.Activity a = mReceivers.mActivities.get(component);
3365            if (DEBUG_PACKAGE_INFO) Log.v(
3366                TAG, "getReceiverInfo " + component + ": " + a);
3367            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3368                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3369                if (ps == null) return null;
3370                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3371                        userId);
3372            }
3373        }
3374        return null;
3375    }
3376
3377    @Override
3378    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3379        if (!sUserManager.exists(userId)) return null;
3380        flags = updateFlagsForComponent(flags, userId, component);
3381        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3382        synchronized (mPackages) {
3383            PackageParser.Service s = mServices.mServices.get(component);
3384            if (DEBUG_PACKAGE_INFO) Log.v(
3385                TAG, "getServiceInfo " + component + ": " + s);
3386            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3387                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3388                if (ps == null) return null;
3389                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3390                        userId);
3391            }
3392        }
3393        return null;
3394    }
3395
3396    @Override
3397    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3398        if (!sUserManager.exists(userId)) return null;
3399        flags = updateFlagsForComponent(flags, userId, component);
3400        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3401        synchronized (mPackages) {
3402            PackageParser.Provider p = mProviders.mProviders.get(component);
3403            if (DEBUG_PACKAGE_INFO) Log.v(
3404                TAG, "getProviderInfo " + component + ": " + p);
3405            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3406                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3407                if (ps == null) return null;
3408                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3409                        userId);
3410            }
3411        }
3412        return null;
3413    }
3414
3415    @Override
3416    public String[] getSystemSharedLibraryNames() {
3417        Set<String> libSet;
3418        synchronized (mPackages) {
3419            libSet = mSharedLibraries.keySet();
3420            int size = libSet.size();
3421            if (size > 0) {
3422                String[] libs = new String[size];
3423                libSet.toArray(libs);
3424                return libs;
3425            }
3426        }
3427        return null;
3428    }
3429
3430    @Override
3431    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3432        synchronized (mPackages) {
3433            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3434                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3435            if (libraryEntry != null) {
3436                return libraryEntry.apk;
3437            }
3438        }
3439        return null;
3440    }
3441
3442    @Override
3443    public FeatureInfo[] getSystemAvailableFeatures() {
3444        Collection<FeatureInfo> featSet;
3445        synchronized (mPackages) {
3446            featSet = mAvailableFeatures.values();
3447            int size = featSet.size();
3448            if (size > 0) {
3449                FeatureInfo[] features = new FeatureInfo[size+1];
3450                featSet.toArray(features);
3451                FeatureInfo fi = new FeatureInfo();
3452                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3453                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3454                features[size] = fi;
3455                return features;
3456            }
3457        }
3458        return null;
3459    }
3460
3461    @Override
3462    public boolean hasSystemFeature(String name) {
3463        synchronized (mPackages) {
3464            return mAvailableFeatures.containsKey(name);
3465        }
3466    }
3467
3468    @Override
3469    public int checkPermission(String permName, String pkgName, int userId) {
3470        if (!sUserManager.exists(userId)) {
3471            return PackageManager.PERMISSION_DENIED;
3472        }
3473
3474        synchronized (mPackages) {
3475            final PackageParser.Package p = mPackages.get(pkgName);
3476            if (p != null && p.mExtras != null) {
3477                final PackageSetting ps = (PackageSetting) p.mExtras;
3478                final PermissionsState permissionsState = ps.getPermissionsState();
3479                if (permissionsState.hasPermission(permName, userId)) {
3480                    return PackageManager.PERMISSION_GRANTED;
3481                }
3482                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3483                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3484                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3485                    return PackageManager.PERMISSION_GRANTED;
3486                }
3487            }
3488        }
3489
3490        return PackageManager.PERMISSION_DENIED;
3491    }
3492
3493    @Override
3494    public int checkUidPermission(String permName, int uid) {
3495        final int userId = UserHandle.getUserId(uid);
3496
3497        if (!sUserManager.exists(userId)) {
3498            return PackageManager.PERMISSION_DENIED;
3499        }
3500
3501        synchronized (mPackages) {
3502            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3503            if (obj != null) {
3504                final SettingBase ps = (SettingBase) obj;
3505                final PermissionsState permissionsState = ps.getPermissionsState();
3506                if (permissionsState.hasPermission(permName, userId)) {
3507                    return PackageManager.PERMISSION_GRANTED;
3508                }
3509                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3510                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3511                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3512                    return PackageManager.PERMISSION_GRANTED;
3513                }
3514            } else {
3515                ArraySet<String> perms = mSystemPermissions.get(uid);
3516                if (perms != null) {
3517                    if (perms.contains(permName)) {
3518                        return PackageManager.PERMISSION_GRANTED;
3519                    }
3520                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3521                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3522                        return PackageManager.PERMISSION_GRANTED;
3523                    }
3524                }
3525            }
3526        }
3527
3528        return PackageManager.PERMISSION_DENIED;
3529    }
3530
3531    @Override
3532    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3533        if (UserHandle.getCallingUserId() != userId) {
3534            mContext.enforceCallingPermission(
3535                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3536                    "isPermissionRevokedByPolicy for user " + userId);
3537        }
3538
3539        if (checkPermission(permission, packageName, userId)
3540                == PackageManager.PERMISSION_GRANTED) {
3541            return false;
3542        }
3543
3544        final long identity = Binder.clearCallingIdentity();
3545        try {
3546            final int flags = getPermissionFlags(permission, packageName, userId);
3547            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3548        } finally {
3549            Binder.restoreCallingIdentity(identity);
3550        }
3551    }
3552
3553    @Override
3554    public String getPermissionControllerPackageName() {
3555        synchronized (mPackages) {
3556            return mRequiredInstallerPackage;
3557        }
3558    }
3559
3560    /**
3561     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3562     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3563     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3564     * @param message the message to log on security exception
3565     */
3566    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3567            boolean checkShell, String message) {
3568        if (userId < 0) {
3569            throw new IllegalArgumentException("Invalid userId " + userId);
3570        }
3571        if (checkShell) {
3572            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3573        }
3574        if (userId == UserHandle.getUserId(callingUid)) return;
3575        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3576            if (requireFullPermission) {
3577                mContext.enforceCallingOrSelfPermission(
3578                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3579            } else {
3580                try {
3581                    mContext.enforceCallingOrSelfPermission(
3582                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3583                } catch (SecurityException se) {
3584                    mContext.enforceCallingOrSelfPermission(
3585                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3586                }
3587            }
3588        }
3589    }
3590
3591    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3592        if (callingUid == Process.SHELL_UID) {
3593            if (userHandle >= 0
3594                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3595                throw new SecurityException("Shell does not have permission to access user "
3596                        + userHandle);
3597            } else if (userHandle < 0) {
3598                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3599                        + Debug.getCallers(3));
3600            }
3601        }
3602    }
3603
3604    private BasePermission findPermissionTreeLP(String permName) {
3605        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3606            if (permName.startsWith(bp.name) &&
3607                    permName.length() > bp.name.length() &&
3608                    permName.charAt(bp.name.length()) == '.') {
3609                return bp;
3610            }
3611        }
3612        return null;
3613    }
3614
3615    private BasePermission checkPermissionTreeLP(String permName) {
3616        if (permName != null) {
3617            BasePermission bp = findPermissionTreeLP(permName);
3618            if (bp != null) {
3619                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3620                    return bp;
3621                }
3622                throw new SecurityException("Calling uid "
3623                        + Binder.getCallingUid()
3624                        + " is not allowed to add to permission tree "
3625                        + bp.name + " owned by uid " + bp.uid);
3626            }
3627        }
3628        throw new SecurityException("No permission tree found for " + permName);
3629    }
3630
3631    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3632        if (s1 == null) {
3633            return s2 == null;
3634        }
3635        if (s2 == null) {
3636            return false;
3637        }
3638        if (s1.getClass() != s2.getClass()) {
3639            return false;
3640        }
3641        return s1.equals(s2);
3642    }
3643
3644    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3645        if (pi1.icon != pi2.icon) return false;
3646        if (pi1.logo != pi2.logo) return false;
3647        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3648        if (!compareStrings(pi1.name, pi2.name)) return false;
3649        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3650        // We'll take care of setting this one.
3651        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3652        // These are not currently stored in settings.
3653        //if (!compareStrings(pi1.group, pi2.group)) return false;
3654        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3655        //if (pi1.labelRes != pi2.labelRes) return false;
3656        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3657        return true;
3658    }
3659
3660    int permissionInfoFootprint(PermissionInfo info) {
3661        int size = info.name.length();
3662        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3663        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3664        return size;
3665    }
3666
3667    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3668        int size = 0;
3669        for (BasePermission perm : mSettings.mPermissions.values()) {
3670            if (perm.uid == tree.uid) {
3671                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3672            }
3673        }
3674        return size;
3675    }
3676
3677    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3678        // We calculate the max size of permissions defined by this uid and throw
3679        // if that plus the size of 'info' would exceed our stated maximum.
3680        if (tree.uid != Process.SYSTEM_UID) {
3681            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3682            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3683                throw new SecurityException("Permission tree size cap exceeded");
3684            }
3685        }
3686    }
3687
3688    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3689        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3690            throw new SecurityException("Label must be specified in permission");
3691        }
3692        BasePermission tree = checkPermissionTreeLP(info.name);
3693        BasePermission bp = mSettings.mPermissions.get(info.name);
3694        boolean added = bp == null;
3695        boolean changed = true;
3696        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3697        if (added) {
3698            enforcePermissionCapLocked(info, tree);
3699            bp = new BasePermission(info.name, tree.sourcePackage,
3700                    BasePermission.TYPE_DYNAMIC);
3701        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3702            throw new SecurityException(
3703                    "Not allowed to modify non-dynamic permission "
3704                    + info.name);
3705        } else {
3706            if (bp.protectionLevel == fixedLevel
3707                    && bp.perm.owner.equals(tree.perm.owner)
3708                    && bp.uid == tree.uid
3709                    && comparePermissionInfos(bp.perm.info, info)) {
3710                changed = false;
3711            }
3712        }
3713        bp.protectionLevel = fixedLevel;
3714        info = new PermissionInfo(info);
3715        info.protectionLevel = fixedLevel;
3716        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3717        bp.perm.info.packageName = tree.perm.info.packageName;
3718        bp.uid = tree.uid;
3719        if (added) {
3720            mSettings.mPermissions.put(info.name, bp);
3721        }
3722        if (changed) {
3723            if (!async) {
3724                mSettings.writeLPr();
3725            } else {
3726                scheduleWriteSettingsLocked();
3727            }
3728        }
3729        return added;
3730    }
3731
3732    @Override
3733    public boolean addPermission(PermissionInfo info) {
3734        synchronized (mPackages) {
3735            return addPermissionLocked(info, false);
3736        }
3737    }
3738
3739    @Override
3740    public boolean addPermissionAsync(PermissionInfo info) {
3741        synchronized (mPackages) {
3742            return addPermissionLocked(info, true);
3743        }
3744    }
3745
3746    @Override
3747    public void removePermission(String name) {
3748        synchronized (mPackages) {
3749            checkPermissionTreeLP(name);
3750            BasePermission bp = mSettings.mPermissions.get(name);
3751            if (bp != null) {
3752                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3753                    throw new SecurityException(
3754                            "Not allowed to modify non-dynamic permission "
3755                            + name);
3756                }
3757                mSettings.mPermissions.remove(name);
3758                mSettings.writeLPr();
3759            }
3760        }
3761    }
3762
3763    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3764            BasePermission bp) {
3765        int index = pkg.requestedPermissions.indexOf(bp.name);
3766        if (index == -1) {
3767            throw new SecurityException("Package " + pkg.packageName
3768                    + " has not requested permission " + bp.name);
3769        }
3770        if (!bp.isRuntime() && !bp.isDevelopment()) {
3771            throw new SecurityException("Permission " + bp.name
3772                    + " is not a changeable permission type");
3773        }
3774    }
3775
3776    @Override
3777    public void grantRuntimePermission(String packageName, String name, final int userId) {
3778        if (!sUserManager.exists(userId)) {
3779            Log.e(TAG, "No such user:" + userId);
3780            return;
3781        }
3782
3783        mContext.enforceCallingOrSelfPermission(
3784                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3785                "grantRuntimePermission");
3786
3787        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3788                "grantRuntimePermission");
3789
3790        final int uid;
3791        final SettingBase sb;
3792
3793        synchronized (mPackages) {
3794            final PackageParser.Package pkg = mPackages.get(packageName);
3795            if (pkg == null) {
3796                throw new IllegalArgumentException("Unknown package: " + packageName);
3797            }
3798
3799            final BasePermission bp = mSettings.mPermissions.get(name);
3800            if (bp == null) {
3801                throw new IllegalArgumentException("Unknown permission: " + name);
3802            }
3803
3804            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3805
3806            // If a permission review is required for legacy apps we represent
3807            // their permissions as always granted runtime ones since we need
3808            // to keep the review required permission flag per user while an
3809            // install permission's state is shared across all users.
3810            if (Build.PERMISSIONS_REVIEW_REQUIRED
3811                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3812                    && bp.isRuntime()) {
3813                return;
3814            }
3815
3816            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3817            sb = (SettingBase) pkg.mExtras;
3818            if (sb == null) {
3819                throw new IllegalArgumentException("Unknown package: " + packageName);
3820            }
3821
3822            final PermissionsState permissionsState = sb.getPermissionsState();
3823
3824            final int flags = permissionsState.getPermissionFlags(name, userId);
3825            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3826                throw new SecurityException("Cannot grant system fixed permission "
3827                        + name + " for package " + packageName);
3828            }
3829
3830            if (bp.isDevelopment()) {
3831                // Development permissions must be handled specially, since they are not
3832                // normal runtime permissions.  For now they apply to all users.
3833                if (permissionsState.grantInstallPermission(bp) !=
3834                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3835                    scheduleWriteSettingsLocked();
3836                }
3837                return;
3838            }
3839
3840            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3841                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3842                return;
3843            }
3844
3845            final int result = permissionsState.grantRuntimePermission(bp, userId);
3846            switch (result) {
3847                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3848                    return;
3849                }
3850
3851                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3852                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3853                    mHandler.post(new Runnable() {
3854                        @Override
3855                        public void run() {
3856                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3857                        }
3858                    });
3859                }
3860                break;
3861            }
3862
3863            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3864
3865            // Not critical if that is lost - app has to request again.
3866            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3867        }
3868
3869        // Only need to do this if user is initialized. Otherwise it's a new user
3870        // and there are no processes running as the user yet and there's no need
3871        // to make an expensive call to remount processes for the changed permissions.
3872        if (READ_EXTERNAL_STORAGE.equals(name)
3873                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3874            final long token = Binder.clearCallingIdentity();
3875            try {
3876                if (sUserManager.isInitialized(userId)) {
3877                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3878                            MountServiceInternal.class);
3879                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3880                }
3881            } finally {
3882                Binder.restoreCallingIdentity(token);
3883            }
3884        }
3885    }
3886
3887    @Override
3888    public void revokeRuntimePermission(String packageName, String name, int userId) {
3889        if (!sUserManager.exists(userId)) {
3890            Log.e(TAG, "No such user:" + userId);
3891            return;
3892        }
3893
3894        mContext.enforceCallingOrSelfPermission(
3895                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3896                "revokeRuntimePermission");
3897
3898        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3899                "revokeRuntimePermission");
3900
3901        final int appId;
3902
3903        synchronized (mPackages) {
3904            final PackageParser.Package pkg = mPackages.get(packageName);
3905            if (pkg == null) {
3906                throw new IllegalArgumentException("Unknown package: " + packageName);
3907            }
3908
3909            final BasePermission bp = mSettings.mPermissions.get(name);
3910            if (bp == null) {
3911                throw new IllegalArgumentException("Unknown permission: " + name);
3912            }
3913
3914            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3915
3916            // If a permission review is required for legacy apps we represent
3917            // their permissions as always granted runtime ones since we need
3918            // to keep the review required permission flag per user while an
3919            // install permission's state is shared across all users.
3920            if (Build.PERMISSIONS_REVIEW_REQUIRED
3921                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3922                    && bp.isRuntime()) {
3923                return;
3924            }
3925
3926            SettingBase sb = (SettingBase) pkg.mExtras;
3927            if (sb == null) {
3928                throw new IllegalArgumentException("Unknown package: " + packageName);
3929            }
3930
3931            final PermissionsState permissionsState = sb.getPermissionsState();
3932
3933            final int flags = permissionsState.getPermissionFlags(name, userId);
3934            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3935                throw new SecurityException("Cannot revoke system fixed permission "
3936                        + name + " for package " + packageName);
3937            }
3938
3939            if (bp.isDevelopment()) {
3940                // Development permissions must be handled specially, since they are not
3941                // normal runtime permissions.  For now they apply to all users.
3942                if (permissionsState.revokeInstallPermission(bp) !=
3943                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3944                    scheduleWriteSettingsLocked();
3945                }
3946                return;
3947            }
3948
3949            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3950                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3951                return;
3952            }
3953
3954            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3955
3956            // Critical, after this call app should never have the permission.
3957            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3958
3959            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3960        }
3961
3962        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3963    }
3964
3965    @Override
3966    public void resetRuntimePermissions() {
3967        mContext.enforceCallingOrSelfPermission(
3968                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3969                "revokeRuntimePermission");
3970
3971        int callingUid = Binder.getCallingUid();
3972        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3973            mContext.enforceCallingOrSelfPermission(
3974                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3975                    "resetRuntimePermissions");
3976        }
3977
3978        synchronized (mPackages) {
3979            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3980            for (int userId : UserManagerService.getInstance().getUserIds()) {
3981                final int packageCount = mPackages.size();
3982                for (int i = 0; i < packageCount; i++) {
3983                    PackageParser.Package pkg = mPackages.valueAt(i);
3984                    if (!(pkg.mExtras instanceof PackageSetting)) {
3985                        continue;
3986                    }
3987                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3988                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3989                }
3990            }
3991        }
3992    }
3993
3994    @Override
3995    public int getPermissionFlags(String name, String packageName, int userId) {
3996        if (!sUserManager.exists(userId)) {
3997            return 0;
3998        }
3999
4000        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4001
4002        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4003                "getPermissionFlags");
4004
4005        synchronized (mPackages) {
4006            final PackageParser.Package pkg = mPackages.get(packageName);
4007            if (pkg == null) {
4008                throw new IllegalArgumentException("Unknown package: " + packageName);
4009            }
4010
4011            final BasePermission bp = mSettings.mPermissions.get(name);
4012            if (bp == null) {
4013                throw new IllegalArgumentException("Unknown permission: " + name);
4014            }
4015
4016            SettingBase sb = (SettingBase) pkg.mExtras;
4017            if (sb == null) {
4018                throw new IllegalArgumentException("Unknown package: " + packageName);
4019            }
4020
4021            PermissionsState permissionsState = sb.getPermissionsState();
4022            return permissionsState.getPermissionFlags(name, userId);
4023        }
4024    }
4025
4026    @Override
4027    public void updatePermissionFlags(String name, String packageName, int flagMask,
4028            int flagValues, int userId) {
4029        if (!sUserManager.exists(userId)) {
4030            return;
4031        }
4032
4033        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4034
4035        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4036                "updatePermissionFlags");
4037
4038        // Only the system can change these flags and nothing else.
4039        if (getCallingUid() != Process.SYSTEM_UID) {
4040            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4041            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4042            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4043            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4044            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4045        }
4046
4047        synchronized (mPackages) {
4048            final PackageParser.Package pkg = mPackages.get(packageName);
4049            if (pkg == null) {
4050                throw new IllegalArgumentException("Unknown package: " + packageName);
4051            }
4052
4053            final BasePermission bp = mSettings.mPermissions.get(name);
4054            if (bp == null) {
4055                throw new IllegalArgumentException("Unknown permission: " + name);
4056            }
4057
4058            SettingBase sb = (SettingBase) pkg.mExtras;
4059            if (sb == null) {
4060                throw new IllegalArgumentException("Unknown package: " + packageName);
4061            }
4062
4063            PermissionsState permissionsState = sb.getPermissionsState();
4064
4065            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4066
4067            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4068                // Install and runtime permissions are stored in different places,
4069                // so figure out what permission changed and persist the change.
4070                if (permissionsState.getInstallPermissionState(name) != null) {
4071                    scheduleWriteSettingsLocked();
4072                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4073                        || hadState) {
4074                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4075                }
4076            }
4077        }
4078    }
4079
4080    /**
4081     * Update the permission flags for all packages and runtime permissions of a user in order
4082     * to allow device or profile owner to remove POLICY_FIXED.
4083     */
4084    @Override
4085    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4086        if (!sUserManager.exists(userId)) {
4087            return;
4088        }
4089
4090        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4091
4092        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4093                "updatePermissionFlagsForAllApps");
4094
4095        // Only the system can change system fixed flags.
4096        if (getCallingUid() != Process.SYSTEM_UID) {
4097            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4098            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4099        }
4100
4101        synchronized (mPackages) {
4102            boolean changed = false;
4103            final int packageCount = mPackages.size();
4104            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4105                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4106                SettingBase sb = (SettingBase) pkg.mExtras;
4107                if (sb == null) {
4108                    continue;
4109                }
4110                PermissionsState permissionsState = sb.getPermissionsState();
4111                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4112                        userId, flagMask, flagValues);
4113            }
4114            if (changed) {
4115                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4116            }
4117        }
4118    }
4119
4120    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4121        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4122                != PackageManager.PERMISSION_GRANTED
4123            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4124                != PackageManager.PERMISSION_GRANTED) {
4125            throw new SecurityException(message + " requires "
4126                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4127                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4128        }
4129    }
4130
4131    @Override
4132    public boolean shouldShowRequestPermissionRationale(String permissionName,
4133            String packageName, int userId) {
4134        if (UserHandle.getCallingUserId() != userId) {
4135            mContext.enforceCallingPermission(
4136                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4137                    "canShowRequestPermissionRationale for user " + userId);
4138        }
4139
4140        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4141        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4142            return false;
4143        }
4144
4145        if (checkPermission(permissionName, packageName, userId)
4146                == PackageManager.PERMISSION_GRANTED) {
4147            return false;
4148        }
4149
4150        final int flags;
4151
4152        final long identity = Binder.clearCallingIdentity();
4153        try {
4154            flags = getPermissionFlags(permissionName,
4155                    packageName, userId);
4156        } finally {
4157            Binder.restoreCallingIdentity(identity);
4158        }
4159
4160        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4161                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4162                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4163
4164        if ((flags & fixedFlags) != 0) {
4165            return false;
4166        }
4167
4168        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4169    }
4170
4171    @Override
4172    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4173        mContext.enforceCallingOrSelfPermission(
4174                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4175                "addOnPermissionsChangeListener");
4176
4177        synchronized (mPackages) {
4178            mOnPermissionChangeListeners.addListenerLocked(listener);
4179        }
4180    }
4181
4182    @Override
4183    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4184        synchronized (mPackages) {
4185            mOnPermissionChangeListeners.removeListenerLocked(listener);
4186        }
4187    }
4188
4189    @Override
4190    public boolean isProtectedBroadcast(String actionName) {
4191        synchronized (mPackages) {
4192            if (mProtectedBroadcasts.contains(actionName)) {
4193                return true;
4194            } else if (actionName != null) {
4195                // TODO: remove these terrible hacks
4196                if (actionName.startsWith("android.net.netmon.lingerExpired")
4197                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4198                    return true;
4199                }
4200            }
4201        }
4202        return false;
4203    }
4204
4205    @Override
4206    public int checkSignatures(String pkg1, String pkg2) {
4207        synchronized (mPackages) {
4208            final PackageParser.Package p1 = mPackages.get(pkg1);
4209            final PackageParser.Package p2 = mPackages.get(pkg2);
4210            if (p1 == null || p1.mExtras == null
4211                    || p2 == null || p2.mExtras == null) {
4212                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4213            }
4214            return compareSignatures(p1.mSignatures, p2.mSignatures);
4215        }
4216    }
4217
4218    @Override
4219    public int checkUidSignatures(int uid1, int uid2) {
4220        // Map to base uids.
4221        uid1 = UserHandle.getAppId(uid1);
4222        uid2 = UserHandle.getAppId(uid2);
4223        // reader
4224        synchronized (mPackages) {
4225            Signature[] s1;
4226            Signature[] s2;
4227            Object obj = mSettings.getUserIdLPr(uid1);
4228            if (obj != null) {
4229                if (obj instanceof SharedUserSetting) {
4230                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4231                } else if (obj instanceof PackageSetting) {
4232                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4233                } else {
4234                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4235                }
4236            } else {
4237                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4238            }
4239            obj = mSettings.getUserIdLPr(uid2);
4240            if (obj != null) {
4241                if (obj instanceof SharedUserSetting) {
4242                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4243                } else if (obj instanceof PackageSetting) {
4244                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4245                } else {
4246                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4247                }
4248            } else {
4249                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4250            }
4251            return compareSignatures(s1, s2);
4252        }
4253    }
4254
4255    private void killUid(int appId, int userId, String reason) {
4256        final long identity = Binder.clearCallingIdentity();
4257        try {
4258            IActivityManager am = ActivityManagerNative.getDefault();
4259            if (am != null) {
4260                try {
4261                    am.killUid(appId, userId, reason);
4262                } catch (RemoteException e) {
4263                    /* ignore - same process */
4264                }
4265            }
4266        } finally {
4267            Binder.restoreCallingIdentity(identity);
4268        }
4269    }
4270
4271    /**
4272     * Compares two sets of signatures. Returns:
4273     * <br />
4274     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4275     * <br />
4276     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4277     * <br />
4278     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4279     * <br />
4280     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4281     * <br />
4282     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4283     */
4284    static int compareSignatures(Signature[] s1, Signature[] s2) {
4285        if (s1 == null) {
4286            return s2 == null
4287                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4288                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4289        }
4290
4291        if (s2 == null) {
4292            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4293        }
4294
4295        if (s1.length != s2.length) {
4296            return PackageManager.SIGNATURE_NO_MATCH;
4297        }
4298
4299        // Since both signature sets are of size 1, we can compare without HashSets.
4300        if (s1.length == 1) {
4301            return s1[0].equals(s2[0]) ?
4302                    PackageManager.SIGNATURE_MATCH :
4303                    PackageManager.SIGNATURE_NO_MATCH;
4304        }
4305
4306        ArraySet<Signature> set1 = new ArraySet<Signature>();
4307        for (Signature sig : s1) {
4308            set1.add(sig);
4309        }
4310        ArraySet<Signature> set2 = new ArraySet<Signature>();
4311        for (Signature sig : s2) {
4312            set2.add(sig);
4313        }
4314        // Make sure s2 contains all signatures in s1.
4315        if (set1.equals(set2)) {
4316            return PackageManager.SIGNATURE_MATCH;
4317        }
4318        return PackageManager.SIGNATURE_NO_MATCH;
4319    }
4320
4321    /**
4322     * If the database version for this type of package (internal storage or
4323     * external storage) is less than the version where package signatures
4324     * were updated, return true.
4325     */
4326    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4327        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4328        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4329    }
4330
4331    /**
4332     * Used for backward compatibility to make sure any packages with
4333     * certificate chains get upgraded to the new style. {@code existingSigs}
4334     * will be in the old format (since they were stored on disk from before the
4335     * system upgrade) and {@code scannedSigs} will be in the newer format.
4336     */
4337    private int compareSignaturesCompat(PackageSignatures existingSigs,
4338            PackageParser.Package scannedPkg) {
4339        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4340            return PackageManager.SIGNATURE_NO_MATCH;
4341        }
4342
4343        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4344        for (Signature sig : existingSigs.mSignatures) {
4345            existingSet.add(sig);
4346        }
4347        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4348        for (Signature sig : scannedPkg.mSignatures) {
4349            try {
4350                Signature[] chainSignatures = sig.getChainSignatures();
4351                for (Signature chainSig : chainSignatures) {
4352                    scannedCompatSet.add(chainSig);
4353                }
4354            } catch (CertificateEncodingException e) {
4355                scannedCompatSet.add(sig);
4356            }
4357        }
4358        /*
4359         * Make sure the expanded scanned set contains all signatures in the
4360         * existing one.
4361         */
4362        if (scannedCompatSet.equals(existingSet)) {
4363            // Migrate the old signatures to the new scheme.
4364            existingSigs.assignSignatures(scannedPkg.mSignatures);
4365            // The new KeySets will be re-added later in the scanning process.
4366            synchronized (mPackages) {
4367                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4368            }
4369            return PackageManager.SIGNATURE_MATCH;
4370        }
4371        return PackageManager.SIGNATURE_NO_MATCH;
4372    }
4373
4374    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4375        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4376        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4377    }
4378
4379    private int compareSignaturesRecover(PackageSignatures existingSigs,
4380            PackageParser.Package scannedPkg) {
4381        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4382            return PackageManager.SIGNATURE_NO_MATCH;
4383        }
4384
4385        String msg = null;
4386        try {
4387            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4388                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4389                        + scannedPkg.packageName);
4390                return PackageManager.SIGNATURE_MATCH;
4391            }
4392        } catch (CertificateException e) {
4393            msg = e.getMessage();
4394        }
4395
4396        logCriticalInfo(Log.INFO,
4397                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4398        return PackageManager.SIGNATURE_NO_MATCH;
4399    }
4400
4401    @Override
4402    public String[] getPackagesForUid(int uid) {
4403        uid = UserHandle.getAppId(uid);
4404        // reader
4405        synchronized (mPackages) {
4406            Object obj = mSettings.getUserIdLPr(uid);
4407            if (obj instanceof SharedUserSetting) {
4408                final SharedUserSetting sus = (SharedUserSetting) obj;
4409                final int N = sus.packages.size();
4410                final String[] res = new String[N];
4411                final Iterator<PackageSetting> it = sus.packages.iterator();
4412                int i = 0;
4413                while (it.hasNext()) {
4414                    res[i++] = it.next().name;
4415                }
4416                return res;
4417            } else if (obj instanceof PackageSetting) {
4418                final PackageSetting ps = (PackageSetting) obj;
4419                return new String[] { ps.name };
4420            }
4421        }
4422        return null;
4423    }
4424
4425    @Override
4426    public String getNameForUid(int uid) {
4427        // reader
4428        synchronized (mPackages) {
4429            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4430            if (obj instanceof SharedUserSetting) {
4431                final SharedUserSetting sus = (SharedUserSetting) obj;
4432                return sus.name + ":" + sus.userId;
4433            } else if (obj instanceof PackageSetting) {
4434                final PackageSetting ps = (PackageSetting) obj;
4435                return ps.name;
4436            }
4437        }
4438        return null;
4439    }
4440
4441    @Override
4442    public int getUidForSharedUser(String sharedUserName) {
4443        if(sharedUserName == null) {
4444            return -1;
4445        }
4446        // reader
4447        synchronized (mPackages) {
4448            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4449            if (suid == null) {
4450                return -1;
4451            }
4452            return suid.userId;
4453        }
4454    }
4455
4456    @Override
4457    public int getFlagsForUid(int uid) {
4458        synchronized (mPackages) {
4459            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4460            if (obj instanceof SharedUserSetting) {
4461                final SharedUserSetting sus = (SharedUserSetting) obj;
4462                return sus.pkgFlags;
4463            } else if (obj instanceof PackageSetting) {
4464                final PackageSetting ps = (PackageSetting) obj;
4465                return ps.pkgFlags;
4466            }
4467        }
4468        return 0;
4469    }
4470
4471    @Override
4472    public int getPrivateFlagsForUid(int uid) {
4473        synchronized (mPackages) {
4474            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4475            if (obj instanceof SharedUserSetting) {
4476                final SharedUserSetting sus = (SharedUserSetting) obj;
4477                return sus.pkgPrivateFlags;
4478            } else if (obj instanceof PackageSetting) {
4479                final PackageSetting ps = (PackageSetting) obj;
4480                return ps.pkgPrivateFlags;
4481            }
4482        }
4483        return 0;
4484    }
4485
4486    @Override
4487    public boolean isUidPrivileged(int uid) {
4488        uid = UserHandle.getAppId(uid);
4489        // reader
4490        synchronized (mPackages) {
4491            Object obj = mSettings.getUserIdLPr(uid);
4492            if (obj instanceof SharedUserSetting) {
4493                final SharedUserSetting sus = (SharedUserSetting) obj;
4494                final Iterator<PackageSetting> it = sus.packages.iterator();
4495                while (it.hasNext()) {
4496                    if (it.next().isPrivileged()) {
4497                        return true;
4498                    }
4499                }
4500            } else if (obj instanceof PackageSetting) {
4501                final PackageSetting ps = (PackageSetting) obj;
4502                return ps.isPrivileged();
4503            }
4504        }
4505        return false;
4506    }
4507
4508    @Override
4509    public String[] getAppOpPermissionPackages(String permissionName) {
4510        synchronized (mPackages) {
4511            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4512            if (pkgs == null) {
4513                return null;
4514            }
4515            return pkgs.toArray(new String[pkgs.size()]);
4516        }
4517    }
4518
4519    @Override
4520    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4521            int flags, int userId) {
4522        if (!sUserManager.exists(userId)) return null;
4523        flags = updateFlagsForResolve(flags, userId, intent);
4524        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4525        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4526        final ResolveInfo bestChoice =
4527                chooseBestActivity(intent, resolvedType, flags, query, userId);
4528
4529        if (isEphemeralAllowed(intent, query, userId)) {
4530            final EphemeralResolveInfo ai =
4531                    getEphemeralResolveInfo(intent, resolvedType, userId);
4532            if (ai != null) {
4533                if (DEBUG_EPHEMERAL) {
4534                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4535                }
4536                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4537                bestChoice.ephemeralResolveInfo = ai;
4538            }
4539        }
4540        return bestChoice;
4541    }
4542
4543    @Override
4544    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4545            IntentFilter filter, int match, ComponentName activity) {
4546        final int userId = UserHandle.getCallingUserId();
4547        if (DEBUG_PREFERRED) {
4548            Log.v(TAG, "setLastChosenActivity intent=" + intent
4549                + " resolvedType=" + resolvedType
4550                + " flags=" + flags
4551                + " filter=" + filter
4552                + " match=" + match
4553                + " activity=" + activity);
4554            filter.dump(new PrintStreamPrinter(System.out), "    ");
4555        }
4556        intent.setComponent(null);
4557        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4558        // Find any earlier preferred or last chosen entries and nuke them
4559        findPreferredActivity(intent, resolvedType,
4560                flags, query, 0, false, true, false, userId);
4561        // Add the new activity as the last chosen for this filter
4562        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4563                "Setting last chosen");
4564    }
4565
4566    @Override
4567    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4568        final int userId = UserHandle.getCallingUserId();
4569        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4570        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4571        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4572                false, false, false, userId);
4573    }
4574
4575
4576    private boolean isEphemeralAllowed(
4577            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4578        // Short circuit and return early if possible.
4579        if (DISABLE_EPHEMERAL_APPS) {
4580            return false;
4581        }
4582        final int callingUser = UserHandle.getCallingUserId();
4583        if (callingUser != UserHandle.USER_SYSTEM) {
4584            return false;
4585        }
4586        if (mEphemeralResolverConnection == null) {
4587            return false;
4588        }
4589        if (intent.getComponent() != null) {
4590            return false;
4591        }
4592        if (intent.getPackage() != null) {
4593            return false;
4594        }
4595        final boolean isWebUri = hasWebURI(intent);
4596        if (!isWebUri) {
4597            return false;
4598        }
4599        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4600        synchronized (mPackages) {
4601            final int count = resolvedActivites.size();
4602            for (int n = 0; n < count; n++) {
4603                ResolveInfo info = resolvedActivites.get(n);
4604                String packageName = info.activityInfo.packageName;
4605                PackageSetting ps = mSettings.mPackages.get(packageName);
4606                if (ps != null) {
4607                    // Try to get the status from User settings first
4608                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4609                    int status = (int) (packedStatus >> 32);
4610                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4611                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4612                        if (DEBUG_EPHEMERAL) {
4613                            Slog.v(TAG, "DENY ephemeral apps;"
4614                                + " pkg: " + packageName + ", status: " + status);
4615                        }
4616                        return false;
4617                    }
4618                }
4619            }
4620        }
4621        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4622        return true;
4623    }
4624
4625    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4626            int userId) {
4627        MessageDigest digest = null;
4628        try {
4629            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4630        } catch (NoSuchAlgorithmException e) {
4631            // If we can't create a digest, ignore ephemeral apps.
4632            return null;
4633        }
4634
4635        final byte[] hostBytes = intent.getData().getHost().getBytes();
4636        final byte[] digestBytes = digest.digest(hostBytes);
4637        int shaPrefix =
4638                digestBytes[0] << 24
4639                | digestBytes[1] << 16
4640                | digestBytes[2] << 8
4641                | digestBytes[3] << 0;
4642        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4643                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4644        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4645            // No hash prefix match; there are no ephemeral apps for this domain.
4646            return null;
4647        }
4648        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4649            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4650            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4651                continue;
4652            }
4653            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4654            // No filters; this should never happen.
4655            if (filters.isEmpty()) {
4656                continue;
4657            }
4658            // We have a domain match; resolve the filters to see if anything matches.
4659            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4660            for (int j = filters.size() - 1; j >= 0; --j) {
4661                final EphemeralResolveIntentInfo intentInfo =
4662                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4663                ephemeralResolver.addFilter(intentInfo);
4664            }
4665            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4666                    intent, resolvedType, false /*defaultOnly*/, userId);
4667            if (!matchedResolveInfoList.isEmpty()) {
4668                return matchedResolveInfoList.get(0);
4669            }
4670        }
4671        // Hash or filter mis-match; no ephemeral apps for this domain.
4672        return null;
4673    }
4674
4675    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4676            int flags, List<ResolveInfo> query, int userId) {
4677        if (query != null) {
4678            final int N = query.size();
4679            if (N == 1) {
4680                return query.get(0);
4681            } else if (N > 1) {
4682                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4683                // If there is more than one activity with the same priority,
4684                // then let the user decide between them.
4685                ResolveInfo r0 = query.get(0);
4686                ResolveInfo r1 = query.get(1);
4687                if (DEBUG_INTENT_MATCHING || debug) {
4688                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4689                            + r1.activityInfo.name + "=" + r1.priority);
4690                }
4691                // If the first activity has a higher priority, or a different
4692                // default, then it is always desirable to pick it.
4693                if (r0.priority != r1.priority
4694                        || r0.preferredOrder != r1.preferredOrder
4695                        || r0.isDefault != r1.isDefault) {
4696                    return query.get(0);
4697                }
4698                // If we have saved a preference for a preferred activity for
4699                // this Intent, use that.
4700                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4701                        flags, query, r0.priority, true, false, debug, userId);
4702                if (ri != null) {
4703                    return ri;
4704                }
4705                ri = new ResolveInfo(mResolveInfo);
4706                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4707                ri.activityInfo.applicationInfo = new ApplicationInfo(
4708                        ri.activityInfo.applicationInfo);
4709                if (userId != 0) {
4710                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4711                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4712                }
4713                // Make sure that the resolver is displayable in car mode
4714                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4715                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4716                return ri;
4717            }
4718        }
4719        return null;
4720    }
4721
4722    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4723            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4724        final int N = query.size();
4725        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4726                .get(userId);
4727        // Get the list of persistent preferred activities that handle the intent
4728        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4729        List<PersistentPreferredActivity> pprefs = ppir != null
4730                ? ppir.queryIntent(intent, resolvedType,
4731                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4732                : null;
4733        if (pprefs != null && pprefs.size() > 0) {
4734            final int M = pprefs.size();
4735            for (int i=0; i<M; i++) {
4736                final PersistentPreferredActivity ppa = pprefs.get(i);
4737                if (DEBUG_PREFERRED || debug) {
4738                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4739                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4740                            + "\n  component=" + ppa.mComponent);
4741                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4742                }
4743                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4744                        flags | MATCH_DISABLED_COMPONENTS, userId);
4745                if (DEBUG_PREFERRED || debug) {
4746                    Slog.v(TAG, "Found persistent preferred activity:");
4747                    if (ai != null) {
4748                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4749                    } else {
4750                        Slog.v(TAG, "  null");
4751                    }
4752                }
4753                if (ai == null) {
4754                    // This previously registered persistent preferred activity
4755                    // component is no longer known. Ignore it and do NOT remove it.
4756                    continue;
4757                }
4758                for (int j=0; j<N; j++) {
4759                    final ResolveInfo ri = query.get(j);
4760                    if (!ri.activityInfo.applicationInfo.packageName
4761                            .equals(ai.applicationInfo.packageName)) {
4762                        continue;
4763                    }
4764                    if (!ri.activityInfo.name.equals(ai.name)) {
4765                        continue;
4766                    }
4767                    //  Found a persistent preference that can handle the intent.
4768                    if (DEBUG_PREFERRED || debug) {
4769                        Slog.v(TAG, "Returning persistent preferred activity: " +
4770                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4771                    }
4772                    return ri;
4773                }
4774            }
4775        }
4776        return null;
4777    }
4778
4779    // TODO: handle preferred activities missing while user has amnesia
4780    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4781            List<ResolveInfo> query, int priority, boolean always,
4782            boolean removeMatches, boolean debug, int userId) {
4783        if (!sUserManager.exists(userId)) return null;
4784        flags = updateFlagsForResolve(flags, userId, intent);
4785        // writer
4786        synchronized (mPackages) {
4787            if (intent.getSelector() != null) {
4788                intent = intent.getSelector();
4789            }
4790            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4791
4792            // Try to find a matching persistent preferred activity.
4793            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4794                    debug, userId);
4795
4796            // If a persistent preferred activity matched, use it.
4797            if (pri != null) {
4798                return pri;
4799            }
4800
4801            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4802            // Get the list of preferred activities that handle the intent
4803            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4804            List<PreferredActivity> prefs = pir != null
4805                    ? pir.queryIntent(intent, resolvedType,
4806                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4807                    : null;
4808            if (prefs != null && prefs.size() > 0) {
4809                boolean changed = false;
4810                try {
4811                    // First figure out how good the original match set is.
4812                    // We will only allow preferred activities that came
4813                    // from the same match quality.
4814                    int match = 0;
4815
4816                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4817
4818                    final int N = query.size();
4819                    for (int j=0; j<N; j++) {
4820                        final ResolveInfo ri = query.get(j);
4821                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4822                                + ": 0x" + Integer.toHexString(match));
4823                        if (ri.match > match) {
4824                            match = ri.match;
4825                        }
4826                    }
4827
4828                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4829                            + Integer.toHexString(match));
4830
4831                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4832                    final int M = prefs.size();
4833                    for (int i=0; i<M; i++) {
4834                        final PreferredActivity pa = prefs.get(i);
4835                        if (DEBUG_PREFERRED || debug) {
4836                            Slog.v(TAG, "Checking PreferredActivity ds="
4837                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4838                                    + "\n  component=" + pa.mPref.mComponent);
4839                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4840                        }
4841                        if (pa.mPref.mMatch != match) {
4842                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4843                                    + Integer.toHexString(pa.mPref.mMatch));
4844                            continue;
4845                        }
4846                        // If it's not an "always" type preferred activity and that's what we're
4847                        // looking for, skip it.
4848                        if (always && !pa.mPref.mAlways) {
4849                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4850                            continue;
4851                        }
4852                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4853                                flags | MATCH_DISABLED_COMPONENTS, userId);
4854                        if (DEBUG_PREFERRED || debug) {
4855                            Slog.v(TAG, "Found preferred activity:");
4856                            if (ai != null) {
4857                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4858                            } else {
4859                                Slog.v(TAG, "  null");
4860                            }
4861                        }
4862                        if (ai == null) {
4863                            // This previously registered preferred activity
4864                            // component is no longer known.  Most likely an update
4865                            // to the app was installed and in the new version this
4866                            // component no longer exists.  Clean it up by removing
4867                            // it from the preferred activities list, and skip it.
4868                            Slog.w(TAG, "Removing dangling preferred activity: "
4869                                    + pa.mPref.mComponent);
4870                            pir.removeFilter(pa);
4871                            changed = true;
4872                            continue;
4873                        }
4874                        for (int j=0; j<N; j++) {
4875                            final ResolveInfo ri = query.get(j);
4876                            if (!ri.activityInfo.applicationInfo.packageName
4877                                    .equals(ai.applicationInfo.packageName)) {
4878                                continue;
4879                            }
4880                            if (!ri.activityInfo.name.equals(ai.name)) {
4881                                continue;
4882                            }
4883
4884                            if (removeMatches) {
4885                                pir.removeFilter(pa);
4886                                changed = true;
4887                                if (DEBUG_PREFERRED) {
4888                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4889                                }
4890                                break;
4891                            }
4892
4893                            // Okay we found a previously set preferred or last chosen app.
4894                            // If the result set is different from when this
4895                            // was created, we need to clear it and re-ask the
4896                            // user their preference, if we're looking for an "always" type entry.
4897                            if (always && !pa.mPref.sameSet(query)) {
4898                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4899                                        + intent + " type " + resolvedType);
4900                                if (DEBUG_PREFERRED) {
4901                                    Slog.v(TAG, "Removing preferred activity since set changed "
4902                                            + pa.mPref.mComponent);
4903                                }
4904                                pir.removeFilter(pa);
4905                                // Re-add the filter as a "last chosen" entry (!always)
4906                                PreferredActivity lastChosen = new PreferredActivity(
4907                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4908                                pir.addFilter(lastChosen);
4909                                changed = true;
4910                                return null;
4911                            }
4912
4913                            // Yay! Either the set matched or we're looking for the last chosen
4914                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4915                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4916                            return ri;
4917                        }
4918                    }
4919                } finally {
4920                    if (changed) {
4921                        if (DEBUG_PREFERRED) {
4922                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4923                        }
4924                        scheduleWritePackageRestrictionsLocked(userId);
4925                    }
4926                }
4927            }
4928        }
4929        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4930        return null;
4931    }
4932
4933    /*
4934     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4935     */
4936    @Override
4937    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4938            int targetUserId) {
4939        mContext.enforceCallingOrSelfPermission(
4940                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4941        List<CrossProfileIntentFilter> matches =
4942                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4943        if (matches != null) {
4944            int size = matches.size();
4945            for (int i = 0; i < size; i++) {
4946                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4947            }
4948        }
4949        if (hasWebURI(intent)) {
4950            // cross-profile app linking works only towards the parent.
4951            final UserInfo parent = getProfileParent(sourceUserId);
4952            synchronized(mPackages) {
4953                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4954                        intent, resolvedType, 0, sourceUserId, parent.id);
4955                return xpDomainInfo != null;
4956            }
4957        }
4958        return false;
4959    }
4960
4961    private UserInfo getProfileParent(int userId) {
4962        final long identity = Binder.clearCallingIdentity();
4963        try {
4964            return sUserManager.getProfileParent(userId);
4965        } finally {
4966            Binder.restoreCallingIdentity(identity);
4967        }
4968    }
4969
4970    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4971            String resolvedType, int userId) {
4972        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4973        if (resolver != null) {
4974            return resolver.queryIntent(intent, resolvedType, false, userId);
4975        }
4976        return null;
4977    }
4978
4979    @Override
4980    public List<ResolveInfo> queryIntentActivities(Intent intent,
4981            String resolvedType, int flags, int userId) {
4982        if (!sUserManager.exists(userId)) return Collections.emptyList();
4983        flags = updateFlagsForResolve(flags, userId, intent);
4984        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4985        ComponentName comp = intent.getComponent();
4986        if (comp == null) {
4987            if (intent.getSelector() != null) {
4988                intent = intent.getSelector();
4989                comp = intent.getComponent();
4990            }
4991        }
4992
4993        if (comp != null) {
4994            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4995            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4996            if (ai != null) {
4997                final ResolveInfo ri = new ResolveInfo();
4998                ri.activityInfo = ai;
4999                list.add(ri);
5000            }
5001            return list;
5002        }
5003
5004        // reader
5005        synchronized (mPackages) {
5006            final String pkgName = intent.getPackage();
5007            if (pkgName == null) {
5008                List<CrossProfileIntentFilter> matchingFilters =
5009                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5010                // Check for results that need to skip the current profile.
5011                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5012                        resolvedType, flags, userId);
5013                if (xpResolveInfo != null) {
5014                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5015                    result.add(xpResolveInfo);
5016                    return filterIfNotSystemUser(result, userId);
5017                }
5018
5019                // Check for results in the current profile.
5020                List<ResolveInfo> result = mActivities.queryIntent(
5021                        intent, resolvedType, flags, userId);
5022                result = filterIfNotSystemUser(result, userId);
5023
5024                // Check for cross profile results.
5025                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5026                xpResolveInfo = queryCrossProfileIntents(
5027                        matchingFilters, intent, resolvedType, flags, userId,
5028                        hasNonNegativePriorityResult);
5029                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5030                    boolean isVisibleToUser = filterIfNotSystemUser(
5031                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5032                    if (isVisibleToUser) {
5033                        result.add(xpResolveInfo);
5034                        Collections.sort(result, mResolvePrioritySorter);
5035                    }
5036                }
5037                if (hasWebURI(intent)) {
5038                    CrossProfileDomainInfo xpDomainInfo = null;
5039                    final UserInfo parent = getProfileParent(userId);
5040                    if (parent != null) {
5041                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5042                                flags, userId, parent.id);
5043                    }
5044                    if (xpDomainInfo != null) {
5045                        if (xpResolveInfo != null) {
5046                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5047                            // in the result.
5048                            result.remove(xpResolveInfo);
5049                        }
5050                        if (result.size() == 0) {
5051                            result.add(xpDomainInfo.resolveInfo);
5052                            return result;
5053                        }
5054                    } else if (result.size() <= 1) {
5055                        return result;
5056                    }
5057                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5058                            xpDomainInfo, userId);
5059                    Collections.sort(result, mResolvePrioritySorter);
5060                }
5061                return result;
5062            }
5063            final PackageParser.Package pkg = mPackages.get(pkgName);
5064            if (pkg != null) {
5065                return filterIfNotSystemUser(
5066                        mActivities.queryIntentForPackage(
5067                                intent, resolvedType, flags, pkg.activities, userId),
5068                        userId);
5069            }
5070            return new ArrayList<ResolveInfo>();
5071        }
5072    }
5073
5074    private static class CrossProfileDomainInfo {
5075        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5076        ResolveInfo resolveInfo;
5077        /* Best domain verification status of the activities found in the other profile */
5078        int bestDomainVerificationStatus;
5079    }
5080
5081    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5082            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5083        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5084                sourceUserId)) {
5085            return null;
5086        }
5087        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5088                resolvedType, flags, parentUserId);
5089
5090        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5091            return null;
5092        }
5093        CrossProfileDomainInfo result = null;
5094        int size = resultTargetUser.size();
5095        for (int i = 0; i < size; i++) {
5096            ResolveInfo riTargetUser = resultTargetUser.get(i);
5097            // Intent filter verification is only for filters that specify a host. So don't return
5098            // those that handle all web uris.
5099            if (riTargetUser.handleAllWebDataURI) {
5100                continue;
5101            }
5102            String packageName = riTargetUser.activityInfo.packageName;
5103            PackageSetting ps = mSettings.mPackages.get(packageName);
5104            if (ps == null) {
5105                continue;
5106            }
5107            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5108            int status = (int)(verificationState >> 32);
5109            if (result == null) {
5110                result = new CrossProfileDomainInfo();
5111                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5112                        sourceUserId, parentUserId);
5113                result.bestDomainVerificationStatus = status;
5114            } else {
5115                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5116                        result.bestDomainVerificationStatus);
5117            }
5118        }
5119        // Don't consider matches with status NEVER across profiles.
5120        if (result != null && result.bestDomainVerificationStatus
5121                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5122            return null;
5123        }
5124        return result;
5125    }
5126
5127    /**
5128     * Verification statuses are ordered from the worse to the best, except for
5129     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5130     */
5131    private int bestDomainVerificationStatus(int status1, int status2) {
5132        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5133            return status2;
5134        }
5135        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5136            return status1;
5137        }
5138        return (int) MathUtils.max(status1, status2);
5139    }
5140
5141    private boolean isUserEnabled(int userId) {
5142        long callingId = Binder.clearCallingIdentity();
5143        try {
5144            UserInfo userInfo = sUserManager.getUserInfo(userId);
5145            return userInfo != null && userInfo.isEnabled();
5146        } finally {
5147            Binder.restoreCallingIdentity(callingId);
5148        }
5149    }
5150
5151    /**
5152     * Filter out activities with systemUserOnly flag set, when current user is not System.
5153     *
5154     * @return filtered list
5155     */
5156    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5157        if (userId == UserHandle.USER_SYSTEM) {
5158            return resolveInfos;
5159        }
5160        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5161            ResolveInfo info = resolveInfos.get(i);
5162            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5163                resolveInfos.remove(i);
5164            }
5165        }
5166        return resolveInfos;
5167    }
5168
5169    /**
5170     * @param resolveInfos list of resolve infos in descending priority order
5171     * @return if the list contains a resolve info with non-negative priority
5172     */
5173    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5174        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5175    }
5176
5177    private static boolean hasWebURI(Intent intent) {
5178        if (intent.getData() == null) {
5179            return false;
5180        }
5181        final String scheme = intent.getScheme();
5182        if (TextUtils.isEmpty(scheme)) {
5183            return false;
5184        }
5185        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5186    }
5187
5188    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5189            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5190            int userId) {
5191        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5192
5193        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5194            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5195                    candidates.size());
5196        }
5197
5198        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5199        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5200        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5201        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5202        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5203        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5204
5205        synchronized (mPackages) {
5206            final int count = candidates.size();
5207            // First, try to use linked apps. Partition the candidates into four lists:
5208            // one for the final results, one for the "do not use ever", one for "undefined status"
5209            // and finally one for "browser app type".
5210            for (int n=0; n<count; n++) {
5211                ResolveInfo info = candidates.get(n);
5212                String packageName = info.activityInfo.packageName;
5213                PackageSetting ps = mSettings.mPackages.get(packageName);
5214                if (ps != null) {
5215                    // Add to the special match all list (Browser use case)
5216                    if (info.handleAllWebDataURI) {
5217                        matchAllList.add(info);
5218                        continue;
5219                    }
5220                    // Try to get the status from User settings first
5221                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5222                    int status = (int)(packedStatus >> 32);
5223                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5224                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5225                        if (DEBUG_DOMAIN_VERIFICATION) {
5226                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5227                                    + " : linkgen=" + linkGeneration);
5228                        }
5229                        // Use link-enabled generation as preferredOrder, i.e.
5230                        // prefer newly-enabled over earlier-enabled.
5231                        info.preferredOrder = linkGeneration;
5232                        alwaysList.add(info);
5233                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5234                        if (DEBUG_DOMAIN_VERIFICATION) {
5235                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5236                        }
5237                        neverList.add(info);
5238                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5239                        if (DEBUG_DOMAIN_VERIFICATION) {
5240                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5241                        }
5242                        alwaysAskList.add(info);
5243                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5244                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5245                        if (DEBUG_DOMAIN_VERIFICATION) {
5246                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5247                        }
5248                        undefinedList.add(info);
5249                    }
5250                }
5251            }
5252
5253            // We'll want to include browser possibilities in a few cases
5254            boolean includeBrowser = false;
5255
5256            // First try to add the "always" resolution(s) for the current user, if any
5257            if (alwaysList.size() > 0) {
5258                result.addAll(alwaysList);
5259            } else {
5260                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5261                result.addAll(undefinedList);
5262                // Maybe add one for the other profile.
5263                if (xpDomainInfo != null && (
5264                        xpDomainInfo.bestDomainVerificationStatus
5265                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5266                    result.add(xpDomainInfo.resolveInfo);
5267                }
5268                includeBrowser = true;
5269            }
5270
5271            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5272            // If there were 'always' entries their preferred order has been set, so we also
5273            // back that off to make the alternatives equivalent
5274            if (alwaysAskList.size() > 0) {
5275                for (ResolveInfo i : result) {
5276                    i.preferredOrder = 0;
5277                }
5278                result.addAll(alwaysAskList);
5279                includeBrowser = true;
5280            }
5281
5282            if (includeBrowser) {
5283                // Also add browsers (all of them or only the default one)
5284                if (DEBUG_DOMAIN_VERIFICATION) {
5285                    Slog.v(TAG, "   ...including browsers in candidate set");
5286                }
5287                if ((matchFlags & MATCH_ALL) != 0) {
5288                    result.addAll(matchAllList);
5289                } else {
5290                    // Browser/generic handling case.  If there's a default browser, go straight
5291                    // to that (but only if there is no other higher-priority match).
5292                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5293                    int maxMatchPrio = 0;
5294                    ResolveInfo defaultBrowserMatch = null;
5295                    final int numCandidates = matchAllList.size();
5296                    for (int n = 0; n < numCandidates; n++) {
5297                        ResolveInfo info = matchAllList.get(n);
5298                        // track the highest overall match priority...
5299                        if (info.priority > maxMatchPrio) {
5300                            maxMatchPrio = info.priority;
5301                        }
5302                        // ...and the highest-priority default browser match
5303                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5304                            if (defaultBrowserMatch == null
5305                                    || (defaultBrowserMatch.priority < info.priority)) {
5306                                if (debug) {
5307                                    Slog.v(TAG, "Considering default browser match " + info);
5308                                }
5309                                defaultBrowserMatch = info;
5310                            }
5311                        }
5312                    }
5313                    if (defaultBrowserMatch != null
5314                            && defaultBrowserMatch.priority >= maxMatchPrio
5315                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5316                    {
5317                        if (debug) {
5318                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5319                        }
5320                        result.add(defaultBrowserMatch);
5321                    } else {
5322                        result.addAll(matchAllList);
5323                    }
5324                }
5325
5326                // If there is nothing selected, add all candidates and remove the ones that the user
5327                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5328                if (result.size() == 0) {
5329                    result.addAll(candidates);
5330                    result.removeAll(neverList);
5331                }
5332            }
5333        }
5334        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5335            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5336                    result.size());
5337            for (ResolveInfo info : result) {
5338                Slog.v(TAG, "  + " + info.activityInfo);
5339            }
5340        }
5341        return result;
5342    }
5343
5344    // Returns a packed value as a long:
5345    //
5346    // high 'int'-sized word: link status: undefined/ask/never/always.
5347    // low 'int'-sized word: relative priority among 'always' results.
5348    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5349        long result = ps.getDomainVerificationStatusForUser(userId);
5350        // if none available, get the master status
5351        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5352            if (ps.getIntentFilterVerificationInfo() != null) {
5353                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5354            }
5355        }
5356        return result;
5357    }
5358
5359    private ResolveInfo querySkipCurrentProfileIntents(
5360            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5361            int flags, int sourceUserId) {
5362        if (matchingFilters != null) {
5363            int size = matchingFilters.size();
5364            for (int i = 0; i < size; i ++) {
5365                CrossProfileIntentFilter filter = matchingFilters.get(i);
5366                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5367                    // Checking if there are activities in the target user that can handle the
5368                    // intent.
5369                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5370                            resolvedType, flags, sourceUserId);
5371                    if (resolveInfo != null) {
5372                        return resolveInfo;
5373                    }
5374                }
5375            }
5376        }
5377        return null;
5378    }
5379
5380    // Return matching ResolveInfo in target user if any.
5381    private ResolveInfo queryCrossProfileIntents(
5382            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5383            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5384        if (matchingFilters != null) {
5385            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5386            // match the same intent. For performance reasons, it is better not to
5387            // run queryIntent twice for the same userId
5388            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5389            int size = matchingFilters.size();
5390            for (int i = 0; i < size; i++) {
5391                CrossProfileIntentFilter filter = matchingFilters.get(i);
5392                int targetUserId = filter.getTargetUserId();
5393                boolean skipCurrentProfile =
5394                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5395                boolean skipCurrentProfileIfNoMatchFound =
5396                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5397                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5398                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5399                    // Checking if there are activities in the target user that can handle the
5400                    // intent.
5401                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5402                            resolvedType, flags, sourceUserId);
5403                    if (resolveInfo != null) return resolveInfo;
5404                    alreadyTriedUserIds.put(targetUserId, true);
5405                }
5406            }
5407        }
5408        return null;
5409    }
5410
5411    /**
5412     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5413     * will forward the intent to the filter's target user.
5414     * Otherwise, returns null.
5415     */
5416    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5417            String resolvedType, int flags, int sourceUserId) {
5418        int targetUserId = filter.getTargetUserId();
5419        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5420                resolvedType, flags, targetUserId);
5421        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5422            // If all the matches in the target profile are suspended, return null.
5423            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5424                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5425                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5426                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5427                            targetUserId);
5428                }
5429            }
5430        }
5431        return null;
5432    }
5433
5434    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5435            int sourceUserId, int targetUserId) {
5436        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5437        long ident = Binder.clearCallingIdentity();
5438        boolean targetIsProfile;
5439        try {
5440            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5441        } finally {
5442            Binder.restoreCallingIdentity(ident);
5443        }
5444        String className;
5445        if (targetIsProfile) {
5446            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5447        } else {
5448            className = FORWARD_INTENT_TO_PARENT;
5449        }
5450        ComponentName forwardingActivityComponentName = new ComponentName(
5451                mAndroidApplication.packageName, className);
5452        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5453                sourceUserId);
5454        if (!targetIsProfile) {
5455            forwardingActivityInfo.showUserIcon = targetUserId;
5456            forwardingResolveInfo.noResourceId = true;
5457        }
5458        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5459        forwardingResolveInfo.priority = 0;
5460        forwardingResolveInfo.preferredOrder = 0;
5461        forwardingResolveInfo.match = 0;
5462        forwardingResolveInfo.isDefault = true;
5463        forwardingResolveInfo.filter = filter;
5464        forwardingResolveInfo.targetUserId = targetUserId;
5465        return forwardingResolveInfo;
5466    }
5467
5468    @Override
5469    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5470            Intent[] specifics, String[] specificTypes, Intent intent,
5471            String resolvedType, int flags, int userId) {
5472        if (!sUserManager.exists(userId)) return Collections.emptyList();
5473        flags = updateFlagsForResolve(flags, userId, intent);
5474        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5475                false, "query intent activity options");
5476        final String resultsAction = intent.getAction();
5477
5478        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5479                | PackageManager.GET_RESOLVED_FILTER, userId);
5480
5481        if (DEBUG_INTENT_MATCHING) {
5482            Log.v(TAG, "Query " + intent + ": " + results);
5483        }
5484
5485        int specificsPos = 0;
5486        int N;
5487
5488        // todo: note that the algorithm used here is O(N^2).  This
5489        // isn't a problem in our current environment, but if we start running
5490        // into situations where we have more than 5 or 10 matches then this
5491        // should probably be changed to something smarter...
5492
5493        // First we go through and resolve each of the specific items
5494        // that were supplied, taking care of removing any corresponding
5495        // duplicate items in the generic resolve list.
5496        if (specifics != null) {
5497            for (int i=0; i<specifics.length; i++) {
5498                final Intent sintent = specifics[i];
5499                if (sintent == null) {
5500                    continue;
5501                }
5502
5503                if (DEBUG_INTENT_MATCHING) {
5504                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5505                }
5506
5507                String action = sintent.getAction();
5508                if (resultsAction != null && resultsAction.equals(action)) {
5509                    // If this action was explicitly requested, then don't
5510                    // remove things that have it.
5511                    action = null;
5512                }
5513
5514                ResolveInfo ri = null;
5515                ActivityInfo ai = null;
5516
5517                ComponentName comp = sintent.getComponent();
5518                if (comp == null) {
5519                    ri = resolveIntent(
5520                        sintent,
5521                        specificTypes != null ? specificTypes[i] : null,
5522                            flags, userId);
5523                    if (ri == null) {
5524                        continue;
5525                    }
5526                    if (ri == mResolveInfo) {
5527                        // ACK!  Must do something better with this.
5528                    }
5529                    ai = ri.activityInfo;
5530                    comp = new ComponentName(ai.applicationInfo.packageName,
5531                            ai.name);
5532                } else {
5533                    ai = getActivityInfo(comp, flags, userId);
5534                    if (ai == null) {
5535                        continue;
5536                    }
5537                }
5538
5539                // Look for any generic query activities that are duplicates
5540                // of this specific one, and remove them from the results.
5541                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5542                N = results.size();
5543                int j;
5544                for (j=specificsPos; j<N; j++) {
5545                    ResolveInfo sri = results.get(j);
5546                    if ((sri.activityInfo.name.equals(comp.getClassName())
5547                            && sri.activityInfo.applicationInfo.packageName.equals(
5548                                    comp.getPackageName()))
5549                        || (action != null && sri.filter.matchAction(action))) {
5550                        results.remove(j);
5551                        if (DEBUG_INTENT_MATCHING) Log.v(
5552                            TAG, "Removing duplicate item from " + j
5553                            + " due to specific " + specificsPos);
5554                        if (ri == null) {
5555                            ri = sri;
5556                        }
5557                        j--;
5558                        N--;
5559                    }
5560                }
5561
5562                // Add this specific item to its proper place.
5563                if (ri == null) {
5564                    ri = new ResolveInfo();
5565                    ri.activityInfo = ai;
5566                }
5567                results.add(specificsPos, ri);
5568                ri.specificIndex = i;
5569                specificsPos++;
5570            }
5571        }
5572
5573        // Now we go through the remaining generic results and remove any
5574        // duplicate actions that are found here.
5575        N = results.size();
5576        for (int i=specificsPos; i<N-1; i++) {
5577            final ResolveInfo rii = results.get(i);
5578            if (rii.filter == null) {
5579                continue;
5580            }
5581
5582            // Iterate over all of the actions of this result's intent
5583            // filter...  typically this should be just one.
5584            final Iterator<String> it = rii.filter.actionsIterator();
5585            if (it == null) {
5586                continue;
5587            }
5588            while (it.hasNext()) {
5589                final String action = it.next();
5590                if (resultsAction != null && resultsAction.equals(action)) {
5591                    // If this action was explicitly requested, then don't
5592                    // remove things that have it.
5593                    continue;
5594                }
5595                for (int j=i+1; j<N; j++) {
5596                    final ResolveInfo rij = results.get(j);
5597                    if (rij.filter != null && rij.filter.hasAction(action)) {
5598                        results.remove(j);
5599                        if (DEBUG_INTENT_MATCHING) Log.v(
5600                            TAG, "Removing duplicate item from " + j
5601                            + " due to action " + action + " at " + i);
5602                        j--;
5603                        N--;
5604                    }
5605                }
5606            }
5607
5608            // If the caller didn't request filter information, drop it now
5609            // so we don't have to marshall/unmarshall it.
5610            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5611                rii.filter = null;
5612            }
5613        }
5614
5615        // Filter out the caller activity if so requested.
5616        if (caller != null) {
5617            N = results.size();
5618            for (int i=0; i<N; i++) {
5619                ActivityInfo ainfo = results.get(i).activityInfo;
5620                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5621                        && caller.getClassName().equals(ainfo.name)) {
5622                    results.remove(i);
5623                    break;
5624                }
5625            }
5626        }
5627
5628        // If the caller didn't request filter information,
5629        // drop them now so we don't have to
5630        // marshall/unmarshall it.
5631        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5632            N = results.size();
5633            for (int i=0; i<N; i++) {
5634                results.get(i).filter = null;
5635            }
5636        }
5637
5638        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5639        return results;
5640    }
5641
5642    @Override
5643    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5644            int userId) {
5645        if (!sUserManager.exists(userId)) return Collections.emptyList();
5646        flags = updateFlagsForResolve(flags, userId, intent);
5647        ComponentName comp = intent.getComponent();
5648        if (comp == null) {
5649            if (intent.getSelector() != null) {
5650                intent = intent.getSelector();
5651                comp = intent.getComponent();
5652            }
5653        }
5654        if (comp != null) {
5655            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5656            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5657            if (ai != null) {
5658                ResolveInfo ri = new ResolveInfo();
5659                ri.activityInfo = ai;
5660                list.add(ri);
5661            }
5662            return list;
5663        }
5664
5665        // reader
5666        synchronized (mPackages) {
5667            String pkgName = intent.getPackage();
5668            if (pkgName == null) {
5669                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5670            }
5671            final PackageParser.Package pkg = mPackages.get(pkgName);
5672            if (pkg != null) {
5673                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5674                        userId);
5675            }
5676            return null;
5677        }
5678    }
5679
5680    @Override
5681    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5682        if (!sUserManager.exists(userId)) return null;
5683        flags = updateFlagsForResolve(flags, userId, intent);
5684        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5685        if (query != null) {
5686            if (query.size() >= 1) {
5687                // If there is more than one service with the same priority,
5688                // just arbitrarily pick the first one.
5689                return query.get(0);
5690            }
5691        }
5692        return null;
5693    }
5694
5695    @Override
5696    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5697            int userId) {
5698        if (!sUserManager.exists(userId)) return Collections.emptyList();
5699        flags = updateFlagsForResolve(flags, userId, intent);
5700        ComponentName comp = intent.getComponent();
5701        if (comp == null) {
5702            if (intent.getSelector() != null) {
5703                intent = intent.getSelector();
5704                comp = intent.getComponent();
5705            }
5706        }
5707        if (comp != null) {
5708            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5709            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5710            if (si != null) {
5711                final ResolveInfo ri = new ResolveInfo();
5712                ri.serviceInfo = si;
5713                list.add(ri);
5714            }
5715            return list;
5716        }
5717
5718        // reader
5719        synchronized (mPackages) {
5720            String pkgName = intent.getPackage();
5721            if (pkgName == null) {
5722                return mServices.queryIntent(intent, resolvedType, flags, userId);
5723            }
5724            final PackageParser.Package pkg = mPackages.get(pkgName);
5725            if (pkg != null) {
5726                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5727                        userId);
5728            }
5729            return null;
5730        }
5731    }
5732
5733    @Override
5734    public List<ResolveInfo> queryIntentContentProviders(
5735            Intent intent, String resolvedType, int flags, int userId) {
5736        if (!sUserManager.exists(userId)) return Collections.emptyList();
5737        flags = updateFlagsForResolve(flags, userId, intent);
5738        ComponentName comp = intent.getComponent();
5739        if (comp == null) {
5740            if (intent.getSelector() != null) {
5741                intent = intent.getSelector();
5742                comp = intent.getComponent();
5743            }
5744        }
5745        if (comp != null) {
5746            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5747            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5748            if (pi != null) {
5749                final ResolveInfo ri = new ResolveInfo();
5750                ri.providerInfo = pi;
5751                list.add(ri);
5752            }
5753            return list;
5754        }
5755
5756        // reader
5757        synchronized (mPackages) {
5758            String pkgName = intent.getPackage();
5759            if (pkgName == null) {
5760                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5761            }
5762            final PackageParser.Package pkg = mPackages.get(pkgName);
5763            if (pkg != null) {
5764                return mProviders.queryIntentForPackage(
5765                        intent, resolvedType, flags, pkg.providers, userId);
5766            }
5767            return null;
5768        }
5769    }
5770
5771    @Override
5772    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5773        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5774        flags = updateFlagsForPackage(flags, userId, null);
5775        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5776        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5777
5778        // writer
5779        synchronized (mPackages) {
5780            ArrayList<PackageInfo> list;
5781            if (listUninstalled) {
5782                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5783                for (PackageSetting ps : mSettings.mPackages.values()) {
5784                    PackageInfo pi;
5785                    if (ps.pkg != null) {
5786                        pi = generatePackageInfo(ps.pkg, flags, userId);
5787                    } else {
5788                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5789                    }
5790                    if (pi != null) {
5791                        list.add(pi);
5792                    }
5793                }
5794            } else {
5795                list = new ArrayList<PackageInfo>(mPackages.size());
5796                for (PackageParser.Package p : mPackages.values()) {
5797                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5798                    if (pi != null) {
5799                        list.add(pi);
5800                    }
5801                }
5802            }
5803
5804            return new ParceledListSlice<PackageInfo>(list);
5805        }
5806    }
5807
5808    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5809            String[] permissions, boolean[] tmp, int flags, int userId) {
5810        int numMatch = 0;
5811        final PermissionsState permissionsState = ps.getPermissionsState();
5812        for (int i=0; i<permissions.length; i++) {
5813            final String permission = permissions[i];
5814            if (permissionsState.hasPermission(permission, userId)) {
5815                tmp[i] = true;
5816                numMatch++;
5817            } else {
5818                tmp[i] = false;
5819            }
5820        }
5821        if (numMatch == 0) {
5822            return;
5823        }
5824        PackageInfo pi;
5825        if (ps.pkg != null) {
5826            pi = generatePackageInfo(ps.pkg, flags, userId);
5827        } else {
5828            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5829        }
5830        // The above might return null in cases of uninstalled apps or install-state
5831        // skew across users/profiles.
5832        if (pi != null) {
5833            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5834                if (numMatch == permissions.length) {
5835                    pi.requestedPermissions = permissions;
5836                } else {
5837                    pi.requestedPermissions = new String[numMatch];
5838                    numMatch = 0;
5839                    for (int i=0; i<permissions.length; i++) {
5840                        if (tmp[i]) {
5841                            pi.requestedPermissions[numMatch] = permissions[i];
5842                            numMatch++;
5843                        }
5844                    }
5845                }
5846            }
5847            list.add(pi);
5848        }
5849    }
5850
5851    @Override
5852    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5853            String[] permissions, int flags, int userId) {
5854        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5855        flags = updateFlagsForPackage(flags, userId, permissions);
5856        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5857
5858        // writer
5859        synchronized (mPackages) {
5860            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5861            boolean[] tmpBools = new boolean[permissions.length];
5862            if (listUninstalled) {
5863                for (PackageSetting ps : mSettings.mPackages.values()) {
5864                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5865                }
5866            } else {
5867                for (PackageParser.Package pkg : mPackages.values()) {
5868                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5869                    if (ps != null) {
5870                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5871                                userId);
5872                    }
5873                }
5874            }
5875
5876            return new ParceledListSlice<PackageInfo>(list);
5877        }
5878    }
5879
5880    @Override
5881    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5882        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5883        flags = updateFlagsForApplication(flags, userId, null);
5884        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5885
5886        // writer
5887        synchronized (mPackages) {
5888            ArrayList<ApplicationInfo> list;
5889            if (listUninstalled) {
5890                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5891                for (PackageSetting ps : mSettings.mPackages.values()) {
5892                    ApplicationInfo ai;
5893                    if (ps.pkg != null) {
5894                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5895                                ps.readUserState(userId), userId);
5896                    } else {
5897                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5898                    }
5899                    if (ai != null) {
5900                        list.add(ai);
5901                    }
5902                }
5903            } else {
5904                list = new ArrayList<ApplicationInfo>(mPackages.size());
5905                for (PackageParser.Package p : mPackages.values()) {
5906                    if (p.mExtras != null) {
5907                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5908                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5909                        if (ai != null) {
5910                            list.add(ai);
5911                        }
5912                    }
5913                }
5914            }
5915
5916            return new ParceledListSlice<ApplicationInfo>(list);
5917        }
5918    }
5919
5920    @Override
5921    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5922        if (DISABLE_EPHEMERAL_APPS) {
5923            return null;
5924        }
5925
5926        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5927                "getEphemeralApplications");
5928        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5929                "getEphemeralApplications");
5930        synchronized (mPackages) {
5931            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5932                    .getEphemeralApplicationsLPw(userId);
5933            if (ephemeralApps != null) {
5934                return new ParceledListSlice<>(ephemeralApps);
5935            }
5936        }
5937        return null;
5938    }
5939
5940    @Override
5941    public boolean isEphemeralApplication(String packageName, int userId) {
5942        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5943                "isEphemeral");
5944        if (DISABLE_EPHEMERAL_APPS) {
5945            return false;
5946        }
5947
5948        if (!isCallerSameApp(packageName)) {
5949            return false;
5950        }
5951        synchronized (mPackages) {
5952            PackageParser.Package pkg = mPackages.get(packageName);
5953            if (pkg != null) {
5954                return pkg.applicationInfo.isEphemeralApp();
5955            }
5956        }
5957        return false;
5958    }
5959
5960    @Override
5961    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5962        if (DISABLE_EPHEMERAL_APPS) {
5963            return null;
5964        }
5965
5966        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5967                "getCookie");
5968        if (!isCallerSameApp(packageName)) {
5969            return null;
5970        }
5971        synchronized (mPackages) {
5972            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5973                    packageName, userId);
5974        }
5975    }
5976
5977    @Override
5978    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5979        if (DISABLE_EPHEMERAL_APPS) {
5980            return true;
5981        }
5982
5983        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5984                "setCookie");
5985        if (!isCallerSameApp(packageName)) {
5986            return false;
5987        }
5988        synchronized (mPackages) {
5989            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5990                    packageName, cookie, userId);
5991        }
5992    }
5993
5994    @Override
5995    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5996        if (DISABLE_EPHEMERAL_APPS) {
5997            return null;
5998        }
5999
6000        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6001                "getEphemeralApplicationIcon");
6002        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6003                "getEphemeralApplicationIcon");
6004        synchronized (mPackages) {
6005            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6006                    packageName, userId);
6007        }
6008    }
6009
6010    private boolean isCallerSameApp(String packageName) {
6011        PackageParser.Package pkg = mPackages.get(packageName);
6012        return pkg != null
6013                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6014    }
6015
6016    public List<ApplicationInfo> getPersistentApplications(int flags) {
6017        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6018
6019        // reader
6020        synchronized (mPackages) {
6021            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6022            final int userId = UserHandle.getCallingUserId();
6023            while (i.hasNext()) {
6024                final PackageParser.Package p = i.next();
6025                if (p.applicationInfo != null
6026                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6027                        && (!mSafeMode || isSystemApp(p))) {
6028                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6029                    if (ps != null) {
6030                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6031                                ps.readUserState(userId), userId);
6032                        if (ai != null) {
6033                            finalList.add(ai);
6034                        }
6035                    }
6036                }
6037            }
6038        }
6039
6040        return finalList;
6041    }
6042
6043    @Override
6044    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6045        if (!sUserManager.exists(userId)) return null;
6046        flags = updateFlagsForComponent(flags, userId, name);
6047        // reader
6048        synchronized (mPackages) {
6049            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6050            PackageSetting ps = provider != null
6051                    ? mSettings.mPackages.get(provider.owner.packageName)
6052                    : null;
6053            return ps != null
6054                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6055                    ? PackageParser.generateProviderInfo(provider, flags,
6056                            ps.readUserState(userId), userId)
6057                    : null;
6058        }
6059    }
6060
6061    /**
6062     * @deprecated
6063     */
6064    @Deprecated
6065    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6066        // reader
6067        synchronized (mPackages) {
6068            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6069                    .entrySet().iterator();
6070            final int userId = UserHandle.getCallingUserId();
6071            while (i.hasNext()) {
6072                Map.Entry<String, PackageParser.Provider> entry = i.next();
6073                PackageParser.Provider p = entry.getValue();
6074                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6075
6076                if (ps != null && p.syncable
6077                        && (!mSafeMode || (p.info.applicationInfo.flags
6078                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6079                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6080                            ps.readUserState(userId), userId);
6081                    if (info != null) {
6082                        outNames.add(entry.getKey());
6083                        outInfo.add(info);
6084                    }
6085                }
6086            }
6087        }
6088    }
6089
6090    @Override
6091    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6092            int uid, int flags) {
6093        final int userId = processName != null ? UserHandle.getUserId(uid)
6094                : UserHandle.getCallingUserId();
6095        if (!sUserManager.exists(userId)) return null;
6096        flags = updateFlagsForComponent(flags, userId, processName);
6097
6098        ArrayList<ProviderInfo> finalList = null;
6099        // reader
6100        synchronized (mPackages) {
6101            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6102            while (i.hasNext()) {
6103                final PackageParser.Provider p = i.next();
6104                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6105                if (ps != null && p.info.authority != null
6106                        && (processName == null
6107                                || (p.info.processName.equals(processName)
6108                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6109                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6110                    if (finalList == null) {
6111                        finalList = new ArrayList<ProviderInfo>(3);
6112                    }
6113                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6114                            ps.readUserState(userId), userId);
6115                    if (info != null) {
6116                        finalList.add(info);
6117                    }
6118                }
6119            }
6120        }
6121
6122        if (finalList != null) {
6123            Collections.sort(finalList, mProviderInitOrderSorter);
6124            return new ParceledListSlice<ProviderInfo>(finalList);
6125        }
6126
6127        return null;
6128    }
6129
6130    @Override
6131    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6132        // reader
6133        synchronized (mPackages) {
6134            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6135            return PackageParser.generateInstrumentationInfo(i, flags);
6136        }
6137    }
6138
6139    @Override
6140    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6141            int flags) {
6142        ArrayList<InstrumentationInfo> finalList =
6143            new ArrayList<InstrumentationInfo>();
6144
6145        // reader
6146        synchronized (mPackages) {
6147            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6148            while (i.hasNext()) {
6149                final PackageParser.Instrumentation p = i.next();
6150                if (targetPackage == null
6151                        || targetPackage.equals(p.info.targetPackage)) {
6152                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6153                            flags);
6154                    if (ii != null) {
6155                        finalList.add(ii);
6156                    }
6157                }
6158            }
6159        }
6160
6161        return finalList;
6162    }
6163
6164    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6165        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6166        if (overlays == null) {
6167            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6168            return;
6169        }
6170        for (PackageParser.Package opkg : overlays.values()) {
6171            // Not much to do if idmap fails: we already logged the error
6172            // and we certainly don't want to abort installation of pkg simply
6173            // because an overlay didn't fit properly. For these reasons,
6174            // ignore the return value of createIdmapForPackagePairLI.
6175            createIdmapForPackagePairLI(pkg, opkg);
6176        }
6177    }
6178
6179    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6180            PackageParser.Package opkg) {
6181        if (!opkg.mTrustedOverlay) {
6182            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6183                    opkg.baseCodePath + ": overlay not trusted");
6184            return false;
6185        }
6186        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6187        if (overlaySet == null) {
6188            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6189                    opkg.baseCodePath + " but target package has no known overlays");
6190            return false;
6191        }
6192        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6193        // TODO: generate idmap for split APKs
6194        try {
6195            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6196        } catch (InstallerException e) {
6197            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6198                    + opkg.baseCodePath);
6199            return false;
6200        }
6201        PackageParser.Package[] overlayArray =
6202            overlaySet.values().toArray(new PackageParser.Package[0]);
6203        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6204            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6205                return p1.mOverlayPriority - p2.mOverlayPriority;
6206            }
6207        };
6208        Arrays.sort(overlayArray, cmp);
6209
6210        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6211        int i = 0;
6212        for (PackageParser.Package p : overlayArray) {
6213            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6214        }
6215        return true;
6216    }
6217
6218    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6220        try {
6221            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6222        } finally {
6223            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6224        }
6225    }
6226
6227    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6228        final File[] files = dir.listFiles();
6229        if (ArrayUtils.isEmpty(files)) {
6230            Log.d(TAG, "No files in app dir " + dir);
6231            return;
6232        }
6233
6234        if (DEBUG_PACKAGE_SCANNING) {
6235            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6236                    + " flags=0x" + Integer.toHexString(parseFlags));
6237        }
6238
6239        for (File file : files) {
6240            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6241                    && !PackageInstallerService.isStageName(file.getName());
6242            if (!isPackage) {
6243                // Ignore entries which are not packages
6244                continue;
6245            }
6246            try {
6247                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6248                        scanFlags, currentTime, null);
6249            } catch (PackageManagerException e) {
6250                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6251
6252                // Delete invalid userdata apps
6253                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6254                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6255                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6256                    removeCodePathLI(file);
6257                }
6258            }
6259        }
6260    }
6261
6262    private static File getSettingsProblemFile() {
6263        File dataDir = Environment.getDataDirectory();
6264        File systemDir = new File(dataDir, "system");
6265        File fname = new File(systemDir, "uiderrors.txt");
6266        return fname;
6267    }
6268
6269    static void reportSettingsProblem(int priority, String msg) {
6270        logCriticalInfo(priority, msg);
6271    }
6272
6273    static void logCriticalInfo(int priority, String msg) {
6274        Slog.println(priority, TAG, msg);
6275        EventLogTags.writePmCriticalInfo(msg);
6276        try {
6277            File fname = getSettingsProblemFile();
6278            FileOutputStream out = new FileOutputStream(fname, true);
6279            PrintWriter pw = new FastPrintWriter(out);
6280            SimpleDateFormat formatter = new SimpleDateFormat();
6281            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6282            pw.println(dateString + ": " + msg);
6283            pw.close();
6284            FileUtils.setPermissions(
6285                    fname.toString(),
6286                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6287                    -1, -1);
6288        } catch (java.io.IOException e) {
6289        }
6290    }
6291
6292    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6293            int parseFlags) throws PackageManagerException {
6294        if (ps != null
6295                && ps.codePath.equals(srcFile)
6296                && ps.timeStamp == srcFile.lastModified()
6297                && !isCompatSignatureUpdateNeeded(pkg)
6298                && !isRecoverSignatureUpdateNeeded(pkg)) {
6299            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6300            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6301            ArraySet<PublicKey> signingKs;
6302            synchronized (mPackages) {
6303                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6304            }
6305            if (ps.signatures.mSignatures != null
6306                    && ps.signatures.mSignatures.length != 0
6307                    && signingKs != null) {
6308                // Optimization: reuse the existing cached certificates
6309                // if the package appears to be unchanged.
6310                pkg.mSignatures = ps.signatures.mSignatures;
6311                pkg.mSigningKeys = signingKs;
6312                return;
6313            }
6314
6315            Slog.w(TAG, "PackageSetting for " + ps.name
6316                    + " is missing signatures.  Collecting certs again to recover them.");
6317        } else {
6318            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6319        }
6320
6321        try {
6322            PackageParser.collectCertificates(pkg, parseFlags);
6323        } catch (PackageParserException e) {
6324            throw PackageManagerException.from(e);
6325        }
6326    }
6327
6328    /**
6329     *  Traces a package scan.
6330     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6331     */
6332    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6333            long currentTime, UserHandle user) throws PackageManagerException {
6334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6335        try {
6336            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6337        } finally {
6338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6339        }
6340    }
6341
6342    /**
6343     *  Scans a package and returns the newly parsed package.
6344     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6345     */
6346    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6347            long currentTime, UserHandle user) throws PackageManagerException {
6348        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6349        parseFlags |= mDefParseFlags;
6350        PackageParser pp = new PackageParser();
6351        pp.setSeparateProcesses(mSeparateProcesses);
6352        pp.setOnlyCoreApps(mOnlyCore);
6353        pp.setDisplayMetrics(mMetrics);
6354
6355        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6356            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6357        }
6358
6359        final PackageParser.Package pkg;
6360        try {
6361            pkg = pp.parsePackage(scanFile, parseFlags);
6362        } catch (PackageParserException e) {
6363            throw PackageManagerException.from(e);
6364        }
6365
6366        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6367    }
6368
6369    /**
6370     *  Scans a package and returns the newly parsed package.
6371     *  @throws PackageManagerException on a parse error.
6372     */
6373    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6374            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6375            throws PackageManagerException {
6376        // If the package has children and this is the first dive in the function
6377        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6378        // packages (parent and children) would be successfully scanned before the
6379        // actual scan since scanning mutates internal state and we want to atomically
6380        // install the package and its children.
6381        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6382            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6383                scanFlags |= SCAN_CHECK_ONLY;
6384            }
6385        } else {
6386            scanFlags &= ~SCAN_CHECK_ONLY;
6387        }
6388
6389        // Scan the parent
6390        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6391                scanFlags, currentTime, user);
6392
6393        // Scan the children
6394        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6395        for (int i = 0; i < childCount; i++) {
6396            PackageParser.Package childPackage = pkg.childPackages.get(i);
6397            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6398                    currentTime, user);
6399        }
6400
6401
6402        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6403            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6404        }
6405
6406        return scannedPkg;
6407    }
6408
6409    /**
6410     *  Scans a package and returns the newly parsed package.
6411     *  @throws PackageManagerException on a parse error.
6412     */
6413    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6414            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6415            throws PackageManagerException {
6416        PackageSetting ps = null;
6417        PackageSetting updatedPkg;
6418        // reader
6419        synchronized (mPackages) {
6420            // Look to see if we already know about this package.
6421            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6422            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6423                // This package has been renamed to its original name.  Let's
6424                // use that.
6425                ps = mSettings.peekPackageLPr(oldName);
6426            }
6427            // If there was no original package, see one for the real package name.
6428            if (ps == null) {
6429                ps = mSettings.peekPackageLPr(pkg.packageName);
6430            }
6431            // Check to see if this package could be hiding/updating a system
6432            // package.  Must look for it either under the original or real
6433            // package name depending on our state.
6434            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6435            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6436
6437            // If this is a package we don't know about on the system partition, we
6438            // may need to remove disabled child packages on the system partition
6439            // or may need to not add child packages if the parent apk is updated
6440            // on the data partition and no longer defines this child package.
6441            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6442                // If this is a parent package for an updated system app and this system
6443                // app got an OTA update which no longer defines some of the child packages
6444                // we have to prune them from the disabled system packages.
6445                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6446                if (disabledPs != null) {
6447                    final int scannedChildCount = (pkg.childPackages != null)
6448                            ? pkg.childPackages.size() : 0;
6449                    final int disabledChildCount = disabledPs.childPackageNames != null
6450                            ? disabledPs.childPackageNames.size() : 0;
6451                    for (int i = 0; i < disabledChildCount; i++) {
6452                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6453                        boolean disabledPackageAvailable = false;
6454                        for (int j = 0; j < scannedChildCount; j++) {
6455                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6456                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6457                                disabledPackageAvailable = true;
6458                                break;
6459                            }
6460                         }
6461                         if (!disabledPackageAvailable) {
6462                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6463                         }
6464                    }
6465                }
6466            }
6467        }
6468
6469        boolean updatedPkgBetter = false;
6470        // First check if this is a system package that may involve an update
6471        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6472            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6473            // it needs to drop FLAG_PRIVILEGED.
6474            if (locationIsPrivileged(scanFile)) {
6475                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6476            } else {
6477                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6478            }
6479
6480            if (ps != null && !ps.codePath.equals(scanFile)) {
6481                // The path has changed from what was last scanned...  check the
6482                // version of the new path against what we have stored to determine
6483                // what to do.
6484                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6485                if (pkg.mVersionCode <= ps.versionCode) {
6486                    // The system package has been updated and the code path does not match
6487                    // Ignore entry. Skip it.
6488                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6489                            + " ignored: updated version " + ps.versionCode
6490                            + " better than this " + pkg.mVersionCode);
6491                    if (!updatedPkg.codePath.equals(scanFile)) {
6492                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6493                                + ps.name + " changing from " + updatedPkg.codePathString
6494                                + " to " + scanFile);
6495                        updatedPkg.codePath = scanFile;
6496                        updatedPkg.codePathString = scanFile.toString();
6497                        updatedPkg.resourcePath = scanFile;
6498                        updatedPkg.resourcePathString = scanFile.toString();
6499                    }
6500                    updatedPkg.pkg = pkg;
6501                    updatedPkg.versionCode = pkg.mVersionCode;
6502
6503                    // Update the disabled system child packages to point to the package too.
6504                    final int childCount = updatedPkg.childPackageNames != null
6505                            ? updatedPkg.childPackageNames.size() : 0;
6506                    for (int i = 0; i < childCount; i++) {
6507                        String childPackageName = updatedPkg.childPackageNames.get(i);
6508                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6509                                childPackageName);
6510                        if (updatedChildPkg != null) {
6511                            updatedChildPkg.pkg = pkg;
6512                            updatedChildPkg.versionCode = pkg.mVersionCode;
6513                        }
6514                    }
6515
6516                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6517                            + scanFile + " ignored: updated version " + ps.versionCode
6518                            + " better than this " + pkg.mVersionCode);
6519                } else {
6520                    // The current app on the system partition is better than
6521                    // what we have updated to on the data partition; switch
6522                    // back to the system partition version.
6523                    // At this point, its safely assumed that package installation for
6524                    // apps in system partition will go through. If not there won't be a working
6525                    // version of the app
6526                    // writer
6527                    synchronized (mPackages) {
6528                        // Just remove the loaded entries from package lists.
6529                        mPackages.remove(ps.name);
6530                    }
6531
6532                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6533                            + " reverting from " + ps.codePathString
6534                            + ": new version " + pkg.mVersionCode
6535                            + " better than installed " + ps.versionCode);
6536
6537                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6538                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6539                    synchronized (mInstallLock) {
6540                        args.cleanUpResourcesLI();
6541                    }
6542                    synchronized (mPackages) {
6543                        mSettings.enableSystemPackageLPw(ps.name);
6544                    }
6545                    updatedPkgBetter = true;
6546                }
6547            }
6548        }
6549
6550        if (updatedPkg != null) {
6551            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6552            // initially
6553            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6554
6555            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6556            // flag set initially
6557            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6558                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6559            }
6560        }
6561
6562        // Verify certificates against what was last scanned
6563        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6564
6565        /*
6566         * A new system app appeared, but we already had a non-system one of the
6567         * same name installed earlier.
6568         */
6569        boolean shouldHideSystemApp = false;
6570        if (updatedPkg == null && ps != null
6571                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6572            /*
6573             * Check to make sure the signatures match first. If they don't,
6574             * wipe the installed application and its data.
6575             */
6576            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6577                    != PackageManager.SIGNATURE_MATCH) {
6578                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6579                        + " signatures don't match existing userdata copy; removing");
6580                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null);
6581                ps = null;
6582            } else {
6583                /*
6584                 * If the newly-added system app is an older version than the
6585                 * already installed version, hide it. It will be scanned later
6586                 * and re-added like an update.
6587                 */
6588                if (pkg.mVersionCode <= ps.versionCode) {
6589                    shouldHideSystemApp = true;
6590                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6591                            + " but new version " + pkg.mVersionCode + " better than installed "
6592                            + ps.versionCode + "; hiding system");
6593                } else {
6594                    /*
6595                     * The newly found system app is a newer version that the
6596                     * one previously installed. Simply remove the
6597                     * already-installed application and replace it with our own
6598                     * while keeping the application data.
6599                     */
6600                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6601                            + " reverting from " + ps.codePathString + ": new version "
6602                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6603                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6604                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6605                    synchronized (mInstallLock) {
6606                        args.cleanUpResourcesLI();
6607                    }
6608                }
6609            }
6610        }
6611
6612        // The apk is forward locked (not public) if its code and resources
6613        // are kept in different files. (except for app in either system or
6614        // vendor path).
6615        // TODO grab this value from PackageSettings
6616        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6617            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6618                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6619            }
6620        }
6621
6622        // TODO: extend to support forward-locked splits
6623        String resourcePath = null;
6624        String baseResourcePath = null;
6625        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6626            if (ps != null && ps.resourcePathString != null) {
6627                resourcePath = ps.resourcePathString;
6628                baseResourcePath = ps.resourcePathString;
6629            } else {
6630                // Should not happen at all. Just log an error.
6631                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6632            }
6633        } else {
6634            resourcePath = pkg.codePath;
6635            baseResourcePath = pkg.baseCodePath;
6636        }
6637
6638        // Set application objects path explicitly.
6639        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6640        pkg.setApplicationInfoCodePath(pkg.codePath);
6641        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6642        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6643        pkg.setApplicationInfoResourcePath(resourcePath);
6644        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6645        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6646
6647        // Note that we invoke the following method only if we are about to unpack an application
6648        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6649                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6650
6651        /*
6652         * If the system app should be overridden by a previously installed
6653         * data, hide the system app now and let the /data/app scan pick it up
6654         * again.
6655         */
6656        if (shouldHideSystemApp) {
6657            synchronized (mPackages) {
6658                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6659            }
6660        }
6661
6662        return scannedPkg;
6663    }
6664
6665    private static String fixProcessName(String defProcessName,
6666            String processName, int uid) {
6667        if (processName == null) {
6668            return defProcessName;
6669        }
6670        return processName;
6671    }
6672
6673    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6674            throws PackageManagerException {
6675        if (pkgSetting.signatures.mSignatures != null) {
6676            // Already existing package. Make sure signatures match
6677            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6678                    == PackageManager.SIGNATURE_MATCH;
6679            if (!match) {
6680                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6681                        == PackageManager.SIGNATURE_MATCH;
6682            }
6683            if (!match) {
6684                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6685                        == PackageManager.SIGNATURE_MATCH;
6686            }
6687            if (!match) {
6688                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6689                        + pkg.packageName + " signatures do not match the "
6690                        + "previously installed version; ignoring!");
6691            }
6692        }
6693
6694        // Check for shared user signatures
6695        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6696            // Already existing package. Make sure signatures match
6697            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6698                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6699            if (!match) {
6700                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6701                        == PackageManager.SIGNATURE_MATCH;
6702            }
6703            if (!match) {
6704                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6705                        == PackageManager.SIGNATURE_MATCH;
6706            }
6707            if (!match) {
6708                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6709                        "Package " + pkg.packageName
6710                        + " has no signatures that match those in shared user "
6711                        + pkgSetting.sharedUser.name + "; ignoring!");
6712            }
6713        }
6714    }
6715
6716    /**
6717     * Enforces that only the system UID or root's UID can call a method exposed
6718     * via Binder.
6719     *
6720     * @param message used as message if SecurityException is thrown
6721     * @throws SecurityException if the caller is not system or root
6722     */
6723    private static final void enforceSystemOrRoot(String message) {
6724        final int uid = Binder.getCallingUid();
6725        if (uid != Process.SYSTEM_UID && uid != 0) {
6726            throw new SecurityException(message);
6727        }
6728    }
6729
6730    @Override
6731    public void performFstrimIfNeeded() {
6732        enforceSystemOrRoot("Only the system can request fstrim");
6733
6734        // Before everything else, see whether we need to fstrim.
6735        try {
6736            IMountService ms = PackageHelper.getMountService();
6737            if (ms != null) {
6738                final boolean isUpgrade = isUpgrade();
6739                boolean doTrim = isUpgrade;
6740                if (doTrim) {
6741                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6742                } else {
6743                    final long interval = android.provider.Settings.Global.getLong(
6744                            mContext.getContentResolver(),
6745                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6746                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6747                    if (interval > 0) {
6748                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6749                        if (timeSinceLast > interval) {
6750                            doTrim = true;
6751                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6752                                    + "; running immediately");
6753                        }
6754                    }
6755                }
6756                if (doTrim) {
6757                    if (!isFirstBoot()) {
6758                        try {
6759                            ActivityManagerNative.getDefault().showBootMessage(
6760                                    mContext.getResources().getString(
6761                                            R.string.android_upgrading_fstrim), true);
6762                        } catch (RemoteException e) {
6763                        }
6764                    }
6765                    ms.runMaintenance();
6766                }
6767            } else {
6768                Slog.e(TAG, "Mount service unavailable!");
6769            }
6770        } catch (RemoteException e) {
6771            // Can't happen; MountService is local
6772        }
6773    }
6774
6775    @Override
6776    public void extractPackagesIfNeeded() {
6777        enforceSystemOrRoot("Only the system can request package extraction");
6778
6779        // Extract pacakges only if profile-guided compilation is enabled because
6780        // otherwise BackgroundDexOptService will not dexopt them later.
6781        if (mUseJitProfiles) {
6782            List<PackageParser.Package> pkgs;
6783            synchronized (mPackages) {
6784                pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6785            }
6786            for (PackageParser.Package pkg : pkgs) {
6787                if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6788                    performDexOpt(pkg.packageName, null /* instructionSet */,
6789                             false /* useProfiles */, true /* extractOnly */, false /* force */);
6790                }
6791            }
6792        }
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    private 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                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8305                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8306                            pkg.applicationInfo.primaryCpuAbi = abi;
8307                        } else {
8308                            pkg.applicationInfo.secondaryCpuAbi = abi;
8309                        }
8310                    } else {
8311                        pkg.applicationInfo.primaryCpuAbi = abi;
8312                    }
8313                }
8314
8315            } else {
8316                String[] abiList = (cpuAbiOverride != null) ?
8317                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8318
8319                // Enable gross and lame hacks for apps that are built with old
8320                // SDK tools. We must scan their APKs for renderscript bitcode and
8321                // not launch them if it's present. Don't bother checking on devices
8322                // that don't have 64 bit support.
8323                boolean needsRenderScriptOverride = false;
8324                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8325                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8326                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8327                    needsRenderScriptOverride = true;
8328                }
8329
8330                final int copyRet;
8331                if (extractLibs) {
8332                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8333                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8334                } else {
8335                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8336                }
8337
8338                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8339                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8340                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8341                }
8342
8343                if (copyRet >= 0) {
8344                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8345                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8346                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8347                } else if (needsRenderScriptOverride) {
8348                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8349                }
8350            }
8351        } catch (IOException ioe) {
8352            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8353        } finally {
8354            IoUtils.closeQuietly(handle);
8355        }
8356
8357        // Now that we've calculated the ABIs and determined if it's an internal app,
8358        // we will go ahead and populate the nativeLibraryPath.
8359        setNativeLibraryPaths(pkg);
8360    }
8361
8362    /**
8363     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8364     * i.e, so that all packages can be run inside a single process if required.
8365     *
8366     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8367     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8368     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8369     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8370     * updating a package that belongs to a shared user.
8371     *
8372     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8373     * adds unnecessary complexity.
8374     */
8375    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8376            PackageParser.Package scannedPackage, boolean bootComplete) {
8377        String requiredInstructionSet = null;
8378        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8379            requiredInstructionSet = VMRuntime.getInstructionSet(
8380                     scannedPackage.applicationInfo.primaryCpuAbi);
8381        }
8382
8383        PackageSetting requirer = null;
8384        for (PackageSetting ps : packagesForUser) {
8385            // If packagesForUser contains scannedPackage, we skip it. This will happen
8386            // when scannedPackage is an update of an existing package. Without this check,
8387            // we will never be able to change the ABI of any package belonging to a shared
8388            // user, even if it's compatible with other packages.
8389            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8390                if (ps.primaryCpuAbiString == null) {
8391                    continue;
8392                }
8393
8394                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8395                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8396                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8397                    // this but there's not much we can do.
8398                    String errorMessage = "Instruction set mismatch, "
8399                            + ((requirer == null) ? "[caller]" : requirer)
8400                            + " requires " + requiredInstructionSet + " whereas " + ps
8401                            + " requires " + instructionSet;
8402                    Slog.w(TAG, errorMessage);
8403                }
8404
8405                if (requiredInstructionSet == null) {
8406                    requiredInstructionSet = instructionSet;
8407                    requirer = ps;
8408                }
8409            }
8410        }
8411
8412        if (requiredInstructionSet != null) {
8413            String adjustedAbi;
8414            if (requirer != null) {
8415                // requirer != null implies that either scannedPackage was null or that scannedPackage
8416                // did not require an ABI, in which case we have to adjust scannedPackage to match
8417                // the ABI of the set (which is the same as requirer's ABI)
8418                adjustedAbi = requirer.primaryCpuAbiString;
8419                if (scannedPackage != null) {
8420                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8421                }
8422            } else {
8423                // requirer == null implies that we're updating all ABIs in the set to
8424                // match scannedPackage.
8425                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8426            }
8427
8428            for (PackageSetting ps : packagesForUser) {
8429                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8430                    if (ps.primaryCpuAbiString != null) {
8431                        continue;
8432                    }
8433
8434                    ps.primaryCpuAbiString = adjustedAbi;
8435                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8436                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8437                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8438                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8439                                + " (requirer="
8440                                + (requirer == null ? "null" : requirer.pkg.packageName)
8441                                + ", scannedPackage="
8442                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8443                                + ")");
8444                        try {
8445                            mInstaller.rmdex(ps.codePathString,
8446                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8447                        } catch (InstallerException ignored) {
8448                        }
8449                    }
8450                }
8451            }
8452        }
8453    }
8454
8455    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8456        synchronized (mPackages) {
8457            mResolverReplaced = true;
8458            // Set up information for custom user intent resolution activity.
8459            mResolveActivity.applicationInfo = pkg.applicationInfo;
8460            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8461            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8462            mResolveActivity.processName = pkg.applicationInfo.packageName;
8463            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8464            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8465                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8466            mResolveActivity.theme = 0;
8467            mResolveActivity.exported = true;
8468            mResolveActivity.enabled = true;
8469            mResolveInfo.activityInfo = mResolveActivity;
8470            mResolveInfo.priority = 0;
8471            mResolveInfo.preferredOrder = 0;
8472            mResolveInfo.match = 0;
8473            mResolveComponentName = mCustomResolverComponentName;
8474            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8475                    mResolveComponentName);
8476        }
8477    }
8478
8479    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8480        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8481
8482        // Set up information for ephemeral installer activity
8483        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8484        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8485        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8486        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8487        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8488        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8489                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8490        mEphemeralInstallerActivity.theme = 0;
8491        mEphemeralInstallerActivity.exported = true;
8492        mEphemeralInstallerActivity.enabled = true;
8493        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8494        mEphemeralInstallerInfo.priority = 0;
8495        mEphemeralInstallerInfo.preferredOrder = 0;
8496        mEphemeralInstallerInfo.match = 0;
8497
8498        if (DEBUG_EPHEMERAL) {
8499            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8500        }
8501    }
8502
8503    private static String calculateBundledApkRoot(final String codePathString) {
8504        final File codePath = new File(codePathString);
8505        final File codeRoot;
8506        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8507            codeRoot = Environment.getRootDirectory();
8508        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8509            codeRoot = Environment.getOemDirectory();
8510        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8511            codeRoot = Environment.getVendorDirectory();
8512        } else {
8513            // Unrecognized code path; take its top real segment as the apk root:
8514            // e.g. /something/app/blah.apk => /something
8515            try {
8516                File f = codePath.getCanonicalFile();
8517                File parent = f.getParentFile();    // non-null because codePath is a file
8518                File tmp;
8519                while ((tmp = parent.getParentFile()) != null) {
8520                    f = parent;
8521                    parent = tmp;
8522                }
8523                codeRoot = f;
8524                Slog.w(TAG, "Unrecognized code path "
8525                        + codePath + " - using " + codeRoot);
8526            } catch (IOException e) {
8527                // Can't canonicalize the code path -- shenanigans?
8528                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8529                return Environment.getRootDirectory().getPath();
8530            }
8531        }
8532        return codeRoot.getPath();
8533    }
8534
8535    /**
8536     * Derive and set the location of native libraries for the given package,
8537     * which varies depending on where and how the package was installed.
8538     */
8539    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8540        final ApplicationInfo info = pkg.applicationInfo;
8541        final String codePath = pkg.codePath;
8542        final File codeFile = new File(codePath);
8543        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8544        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8545
8546        info.nativeLibraryRootDir = null;
8547        info.nativeLibraryRootRequiresIsa = false;
8548        info.nativeLibraryDir = null;
8549        info.secondaryNativeLibraryDir = null;
8550
8551        if (isApkFile(codeFile)) {
8552            // Monolithic install
8553            if (bundledApp) {
8554                // If "/system/lib64/apkname" exists, assume that is the per-package
8555                // native library directory to use; otherwise use "/system/lib/apkname".
8556                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8557                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8558                        getPrimaryInstructionSet(info));
8559
8560                // This is a bundled system app so choose the path based on the ABI.
8561                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8562                // is just the default path.
8563                final String apkName = deriveCodePathName(codePath);
8564                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8565                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8566                        apkName).getAbsolutePath();
8567
8568                if (info.secondaryCpuAbi != null) {
8569                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8570                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8571                            secondaryLibDir, apkName).getAbsolutePath();
8572                }
8573            } else if (asecApp) {
8574                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8575                        .getAbsolutePath();
8576            } else {
8577                final String apkName = deriveCodePathName(codePath);
8578                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8579                        .getAbsolutePath();
8580            }
8581
8582            info.nativeLibraryRootRequiresIsa = false;
8583            info.nativeLibraryDir = info.nativeLibraryRootDir;
8584        } else {
8585            // Cluster install
8586            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8587            info.nativeLibraryRootRequiresIsa = true;
8588
8589            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8590                    getPrimaryInstructionSet(info)).getAbsolutePath();
8591
8592            if (info.secondaryCpuAbi != null) {
8593                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8594                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8595            }
8596        }
8597    }
8598
8599    /**
8600     * Calculate the abis and roots for a bundled app. These can uniquely
8601     * be determined from the contents of the system partition, i.e whether
8602     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8603     * of this information, and instead assume that the system was built
8604     * sensibly.
8605     */
8606    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8607                                           PackageSetting pkgSetting) {
8608        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8609
8610        // If "/system/lib64/apkname" exists, assume that is the per-package
8611        // native library directory to use; otherwise use "/system/lib/apkname".
8612        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8613        setBundledAppAbi(pkg, apkRoot, apkName);
8614        // pkgSetting might be null during rescan following uninstall of updates
8615        // to a bundled app, so accommodate that possibility.  The settings in
8616        // that case will be established later from the parsed package.
8617        //
8618        // If the settings aren't null, sync them up with what we've just derived.
8619        // note that apkRoot isn't stored in the package settings.
8620        if (pkgSetting != null) {
8621            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8622            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8623        }
8624    }
8625
8626    /**
8627     * Deduces the ABI of a bundled app and sets the relevant fields on the
8628     * parsed pkg object.
8629     *
8630     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8631     *        under which system libraries are installed.
8632     * @param apkName the name of the installed package.
8633     */
8634    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8635        final File codeFile = new File(pkg.codePath);
8636
8637        final boolean has64BitLibs;
8638        final boolean has32BitLibs;
8639        if (isApkFile(codeFile)) {
8640            // Monolithic install
8641            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8642            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8643        } else {
8644            // Cluster install
8645            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8646            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8647                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8648                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8649                has64BitLibs = (new File(rootDir, isa)).exists();
8650            } else {
8651                has64BitLibs = false;
8652            }
8653            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8654                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8655                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8656                has32BitLibs = (new File(rootDir, isa)).exists();
8657            } else {
8658                has32BitLibs = false;
8659            }
8660        }
8661
8662        if (has64BitLibs && !has32BitLibs) {
8663            // The package has 64 bit libs, but not 32 bit libs. Its primary
8664            // ABI should be 64 bit. We can safely assume here that the bundled
8665            // native libraries correspond to the most preferred ABI in the list.
8666
8667            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8668            pkg.applicationInfo.secondaryCpuAbi = null;
8669        } else if (has32BitLibs && !has64BitLibs) {
8670            // The package has 32 bit libs but not 64 bit libs. Its primary
8671            // ABI should be 32 bit.
8672
8673            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8674            pkg.applicationInfo.secondaryCpuAbi = null;
8675        } else if (has32BitLibs && has64BitLibs) {
8676            // The application has both 64 and 32 bit bundled libraries. We check
8677            // here that the app declares multiArch support, and warn if it doesn't.
8678            //
8679            // We will be lenient here and record both ABIs. The primary will be the
8680            // ABI that's higher on the list, i.e, a device that's configured to prefer
8681            // 64 bit apps will see a 64 bit primary ABI,
8682
8683            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8684                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8685            }
8686
8687            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8688                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8689                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8690            } else {
8691                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8692                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8693            }
8694        } else {
8695            pkg.applicationInfo.primaryCpuAbi = null;
8696            pkg.applicationInfo.secondaryCpuAbi = null;
8697        }
8698    }
8699
8700    private void killPackage(PackageParser.Package pkg, String reason) {
8701        // Kill the parent package
8702        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8703        // Kill the child packages
8704        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8705        for (int i = 0; i < childCount; i++) {
8706            PackageParser.Package childPkg = pkg.childPackages.get(i);
8707            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8708        }
8709    }
8710
8711    private void killApplication(String pkgName, int appId, String reason) {
8712        // Request the ActivityManager to kill the process(only for existing packages)
8713        // so that we do not end up in a confused state while the user is still using the older
8714        // version of the application while the new one gets installed.
8715        IActivityManager am = ActivityManagerNative.getDefault();
8716        if (am != null) {
8717            try {
8718                am.killApplicationWithAppId(pkgName, appId, reason);
8719            } catch (RemoteException e) {
8720            }
8721        }
8722    }
8723
8724    private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) {
8725        // Remove the parent package setting
8726        PackageSetting ps = (PackageSetting) pkg.mExtras;
8727        if (ps != null) {
8728            removePackageSettingLI(ps, chatty);
8729        }
8730        // Remove the child package setting
8731        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8732        for (int i = 0; i < childCount; i++) {
8733            PackageParser.Package childPkg = pkg.childPackages.get(i);
8734            ps = (PackageSetting) childPkg.mExtras;
8735            if (ps != null) {
8736                removePackageSettingLI(ps, chatty);
8737            }
8738        }
8739    }
8740
8741    void removePackageSettingLI(PackageSetting ps, boolean chatty) {
8742        if (DEBUG_INSTALL) {
8743            if (chatty)
8744                Log.d(TAG, "Removing package " + ps.name);
8745        }
8746
8747        // writer
8748        synchronized (mPackages) {
8749            mPackages.remove(ps.name);
8750            final PackageParser.Package pkg = ps.pkg;
8751            if (pkg != null) {
8752                cleanPackageDataStructuresLILPw(pkg, chatty);
8753            }
8754        }
8755    }
8756
8757    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8758        if (DEBUG_INSTALL) {
8759            if (chatty)
8760                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8761        }
8762
8763        // writer
8764        synchronized (mPackages) {
8765            // Remove the parent package
8766            mPackages.remove(pkg.applicationInfo.packageName);
8767            cleanPackageDataStructuresLILPw(pkg, chatty);
8768
8769            // Remove the child packages
8770            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8771            for (int i = 0; i < childCount; i++) {
8772                PackageParser.Package childPkg = pkg.childPackages.get(i);
8773                mPackages.remove(childPkg.applicationInfo.packageName);
8774                cleanPackageDataStructuresLILPw(childPkg, chatty);
8775            }
8776        }
8777    }
8778
8779    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8780        int N = pkg.providers.size();
8781        StringBuilder r = null;
8782        int i;
8783        for (i=0; i<N; i++) {
8784            PackageParser.Provider p = pkg.providers.get(i);
8785            mProviders.removeProvider(p);
8786            if (p.info.authority == null) {
8787
8788                /* There was another ContentProvider with this authority when
8789                 * this app was installed so this authority is null,
8790                 * Ignore it as we don't have to unregister the provider.
8791                 */
8792                continue;
8793            }
8794            String names[] = p.info.authority.split(";");
8795            for (int j = 0; j < names.length; j++) {
8796                if (mProvidersByAuthority.get(names[j]) == p) {
8797                    mProvidersByAuthority.remove(names[j]);
8798                    if (DEBUG_REMOVE) {
8799                        if (chatty)
8800                            Log.d(TAG, "Unregistered content provider: " + names[j]
8801                                    + ", className = " + p.info.name + ", isSyncable = "
8802                                    + p.info.isSyncable);
8803                    }
8804                }
8805            }
8806            if (DEBUG_REMOVE && chatty) {
8807                if (r == null) {
8808                    r = new StringBuilder(256);
8809                } else {
8810                    r.append(' ');
8811                }
8812                r.append(p.info.name);
8813            }
8814        }
8815        if (r != null) {
8816            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8817        }
8818
8819        N = pkg.services.size();
8820        r = null;
8821        for (i=0; i<N; i++) {
8822            PackageParser.Service s = pkg.services.get(i);
8823            mServices.removeService(s);
8824            if (chatty) {
8825                if (r == null) {
8826                    r = new StringBuilder(256);
8827                } else {
8828                    r.append(' ');
8829                }
8830                r.append(s.info.name);
8831            }
8832        }
8833        if (r != null) {
8834            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8835        }
8836
8837        N = pkg.receivers.size();
8838        r = null;
8839        for (i=0; i<N; i++) {
8840            PackageParser.Activity a = pkg.receivers.get(i);
8841            mReceivers.removeActivity(a, "receiver");
8842            if (DEBUG_REMOVE && chatty) {
8843                if (r == null) {
8844                    r = new StringBuilder(256);
8845                } else {
8846                    r.append(' ');
8847                }
8848                r.append(a.info.name);
8849            }
8850        }
8851        if (r != null) {
8852            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8853        }
8854
8855        N = pkg.activities.size();
8856        r = null;
8857        for (i=0; i<N; i++) {
8858            PackageParser.Activity a = pkg.activities.get(i);
8859            mActivities.removeActivity(a, "activity");
8860            if (DEBUG_REMOVE && chatty) {
8861                if (r == null) {
8862                    r = new StringBuilder(256);
8863                } else {
8864                    r.append(' ');
8865                }
8866                r.append(a.info.name);
8867            }
8868        }
8869        if (r != null) {
8870            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8871        }
8872
8873        N = pkg.permissions.size();
8874        r = null;
8875        for (i=0; i<N; i++) {
8876            PackageParser.Permission p = pkg.permissions.get(i);
8877            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8878            if (bp == null) {
8879                bp = mSettings.mPermissionTrees.get(p.info.name);
8880            }
8881            if (bp != null && bp.perm == p) {
8882                bp.perm = null;
8883                if (DEBUG_REMOVE && chatty) {
8884                    if (r == null) {
8885                        r = new StringBuilder(256);
8886                    } else {
8887                        r.append(' ');
8888                    }
8889                    r.append(p.info.name);
8890                }
8891            }
8892            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8893                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8894                if (appOpPkgs != null) {
8895                    appOpPkgs.remove(pkg.packageName);
8896                }
8897            }
8898        }
8899        if (r != null) {
8900            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8901        }
8902
8903        N = pkg.requestedPermissions.size();
8904        r = null;
8905        for (i=0; i<N; i++) {
8906            String perm = pkg.requestedPermissions.get(i);
8907            BasePermission bp = mSettings.mPermissions.get(perm);
8908            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8909                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8910                if (appOpPkgs != null) {
8911                    appOpPkgs.remove(pkg.packageName);
8912                    if (appOpPkgs.isEmpty()) {
8913                        mAppOpPermissionPackages.remove(perm);
8914                    }
8915                }
8916            }
8917        }
8918        if (r != null) {
8919            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8920        }
8921
8922        N = pkg.instrumentation.size();
8923        r = null;
8924        for (i=0; i<N; i++) {
8925            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8926            mInstrumentation.remove(a.getComponentName());
8927            if (DEBUG_REMOVE && chatty) {
8928                if (r == null) {
8929                    r = new StringBuilder(256);
8930                } else {
8931                    r.append(' ');
8932                }
8933                r.append(a.info.name);
8934            }
8935        }
8936        if (r != null) {
8937            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8938        }
8939
8940        r = null;
8941        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8942            // Only system apps can hold shared libraries.
8943            if (pkg.libraryNames != null) {
8944                for (i=0; i<pkg.libraryNames.size(); i++) {
8945                    String name = pkg.libraryNames.get(i);
8946                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8947                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8948                        mSharedLibraries.remove(name);
8949                        if (DEBUG_REMOVE && chatty) {
8950                            if (r == null) {
8951                                r = new StringBuilder(256);
8952                            } else {
8953                                r.append(' ');
8954                            }
8955                            r.append(name);
8956                        }
8957                    }
8958                }
8959            }
8960        }
8961        if (r != null) {
8962            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8963        }
8964    }
8965
8966    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8967        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8968            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8969                return true;
8970            }
8971        }
8972        return false;
8973    }
8974
8975    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8976    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8977    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8978
8979    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
8980        // Update the parent permissions
8981        updatePermissionsLPw(pkg.packageName, pkg, flags);
8982        // Update the child permissions
8983        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8984        for (int i = 0; i < childCount; i++) {
8985            PackageParser.Package childPkg = pkg.childPackages.get(i);
8986            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
8987        }
8988    }
8989
8990    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8991            int flags) {
8992        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8993        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8994    }
8995
8996    private void updatePermissionsLPw(String changingPkg,
8997            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8998        // Make sure there are no dangling permission trees.
8999        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9000        while (it.hasNext()) {
9001            final BasePermission bp = it.next();
9002            if (bp.packageSetting == null) {
9003                // We may not yet have parsed the package, so just see if
9004                // we still know about its settings.
9005                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9006            }
9007            if (bp.packageSetting == null) {
9008                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9009                        + " from package " + bp.sourcePackage);
9010                it.remove();
9011            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9012                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9013                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9014                            + " from package " + bp.sourcePackage);
9015                    flags |= UPDATE_PERMISSIONS_ALL;
9016                    it.remove();
9017                }
9018            }
9019        }
9020
9021        // Make sure all dynamic permissions have been assigned to a package,
9022        // and make sure there are no dangling permissions.
9023        it = mSettings.mPermissions.values().iterator();
9024        while (it.hasNext()) {
9025            final BasePermission bp = it.next();
9026            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9027                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9028                        + bp.name + " pkg=" + bp.sourcePackage
9029                        + " info=" + bp.pendingInfo);
9030                if (bp.packageSetting == null && bp.pendingInfo != null) {
9031                    final BasePermission tree = findPermissionTreeLP(bp.name);
9032                    if (tree != null && tree.perm != null) {
9033                        bp.packageSetting = tree.packageSetting;
9034                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9035                                new PermissionInfo(bp.pendingInfo));
9036                        bp.perm.info.packageName = tree.perm.info.packageName;
9037                        bp.perm.info.name = bp.name;
9038                        bp.uid = tree.uid;
9039                    }
9040                }
9041            }
9042            if (bp.packageSetting == null) {
9043                // We may not yet have parsed the package, so just see if
9044                // we still know about its settings.
9045                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9046            }
9047            if (bp.packageSetting == null) {
9048                Slog.w(TAG, "Removing dangling permission: " + bp.name
9049                        + " from package " + bp.sourcePackage);
9050                it.remove();
9051            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9052                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9053                    Slog.i(TAG, "Removing old permission: " + bp.name
9054                            + " from package " + bp.sourcePackage);
9055                    flags |= UPDATE_PERMISSIONS_ALL;
9056                    it.remove();
9057                }
9058            }
9059        }
9060
9061        // Now update the permissions for all packages, in particular
9062        // replace the granted permissions of the system packages.
9063        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9064            for (PackageParser.Package pkg : mPackages.values()) {
9065                if (pkg != pkgInfo) {
9066                    // Only replace for packages on requested volume
9067                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9068                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9069                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9070                    grantPermissionsLPw(pkg, replace, changingPkg);
9071                }
9072            }
9073        }
9074
9075        if (pkgInfo != null) {
9076            // Only replace for packages on requested volume
9077            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9078            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9079                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9080            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9081        }
9082    }
9083
9084    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9085            String packageOfInterest) {
9086        // IMPORTANT: There are two types of permissions: install and runtime.
9087        // Install time permissions are granted when the app is installed to
9088        // all device users and users added in the future. Runtime permissions
9089        // are granted at runtime explicitly to specific users. Normal and signature
9090        // protected permissions are install time permissions. Dangerous permissions
9091        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9092        // otherwise they are runtime permissions. This function does not manage
9093        // runtime permissions except for the case an app targeting Lollipop MR1
9094        // being upgraded to target a newer SDK, in which case dangerous permissions
9095        // are transformed from install time to runtime ones.
9096
9097        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9098        if (ps == null) {
9099            return;
9100        }
9101
9102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9103
9104        PermissionsState permissionsState = ps.getPermissionsState();
9105        PermissionsState origPermissions = permissionsState;
9106
9107        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9108
9109        boolean runtimePermissionsRevoked = false;
9110        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9111
9112        boolean changedInstallPermission = false;
9113
9114        if (replace) {
9115            ps.installPermissionsFixed = false;
9116            if (!ps.isSharedUser()) {
9117                origPermissions = new PermissionsState(permissionsState);
9118                permissionsState.reset();
9119            } else {
9120                // We need to know only about runtime permission changes since the
9121                // calling code always writes the install permissions state but
9122                // the runtime ones are written only if changed. The only cases of
9123                // changed runtime permissions here are promotion of an install to
9124                // runtime and revocation of a runtime from a shared user.
9125                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9126                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9127                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9128                    runtimePermissionsRevoked = true;
9129                }
9130            }
9131        }
9132
9133        permissionsState.setGlobalGids(mGlobalGids);
9134
9135        final int N = pkg.requestedPermissions.size();
9136        for (int i=0; i<N; i++) {
9137            final String name = pkg.requestedPermissions.get(i);
9138            final BasePermission bp = mSettings.mPermissions.get(name);
9139
9140            if (DEBUG_INSTALL) {
9141                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9142            }
9143
9144            if (bp == null || bp.packageSetting == null) {
9145                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9146                    Slog.w(TAG, "Unknown permission " + name
9147                            + " in package " + pkg.packageName);
9148                }
9149                continue;
9150            }
9151
9152            final String perm = bp.name;
9153            boolean allowedSig = false;
9154            int grant = GRANT_DENIED;
9155
9156            // Keep track of app op permissions.
9157            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9158                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9159                if (pkgs == null) {
9160                    pkgs = new ArraySet<>();
9161                    mAppOpPermissionPackages.put(bp.name, pkgs);
9162                }
9163                pkgs.add(pkg.packageName);
9164            }
9165
9166            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9167            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9168                    >= Build.VERSION_CODES.M;
9169            switch (level) {
9170                case PermissionInfo.PROTECTION_NORMAL: {
9171                    // For all apps normal permissions are install time ones.
9172                    grant = GRANT_INSTALL;
9173                } break;
9174
9175                case PermissionInfo.PROTECTION_DANGEROUS: {
9176                    // If a permission review is required for legacy apps we represent
9177                    // their permissions as always granted runtime ones since we need
9178                    // to keep the review required permission flag per user while an
9179                    // install permission's state is shared across all users.
9180                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9181                        // For legacy apps dangerous permissions are install time ones.
9182                        grant = GRANT_INSTALL;
9183                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9184                        // For legacy apps that became modern, install becomes runtime.
9185                        grant = GRANT_UPGRADE;
9186                    } else if (mPromoteSystemApps
9187                            && isSystemApp(ps)
9188                            && mExistingSystemPackages.contains(ps.name)) {
9189                        // For legacy system apps, install becomes runtime.
9190                        // We cannot check hasInstallPermission() for system apps since those
9191                        // permissions were granted implicitly and not persisted pre-M.
9192                        grant = GRANT_UPGRADE;
9193                    } else {
9194                        // For modern apps keep runtime permissions unchanged.
9195                        grant = GRANT_RUNTIME;
9196                    }
9197                } break;
9198
9199                case PermissionInfo.PROTECTION_SIGNATURE: {
9200                    // For all apps signature permissions are install time ones.
9201                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9202                    if (allowedSig) {
9203                        grant = GRANT_INSTALL;
9204                    }
9205                } break;
9206            }
9207
9208            if (DEBUG_INSTALL) {
9209                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9210            }
9211
9212            if (grant != GRANT_DENIED) {
9213                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9214                    // If this is an existing, non-system package, then
9215                    // we can't add any new permissions to it.
9216                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9217                        // Except...  if this is a permission that was added
9218                        // to the platform (note: need to only do this when
9219                        // updating the platform).
9220                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9221                            grant = GRANT_DENIED;
9222                        }
9223                    }
9224                }
9225
9226                switch (grant) {
9227                    case GRANT_INSTALL: {
9228                        // Revoke this as runtime permission to handle the case of
9229                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9230                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9231                            if (origPermissions.getRuntimePermissionState(
9232                                    bp.name, userId) != null) {
9233                                // Revoke the runtime permission and clear the flags.
9234                                origPermissions.revokeRuntimePermission(bp, userId);
9235                                origPermissions.updatePermissionFlags(bp, userId,
9236                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9237                                // If we revoked a permission permission, we have to write.
9238                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9239                                        changedRuntimePermissionUserIds, userId);
9240                            }
9241                        }
9242                        // Grant an install permission.
9243                        if (permissionsState.grantInstallPermission(bp) !=
9244                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9245                            changedInstallPermission = true;
9246                        }
9247                    } break;
9248
9249                    case GRANT_RUNTIME: {
9250                        // Grant previously granted runtime permissions.
9251                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9252                            PermissionState permissionState = origPermissions
9253                                    .getRuntimePermissionState(bp.name, userId);
9254                            int flags = permissionState != null
9255                                    ? permissionState.getFlags() : 0;
9256                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9257                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9258                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9259                                    // If we cannot put the permission as it was, we have to write.
9260                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9261                                            changedRuntimePermissionUserIds, userId);
9262                                }
9263                                // If the app supports runtime permissions no need for a review.
9264                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9265                                        && appSupportsRuntimePermissions
9266                                        && (flags & PackageManager
9267                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9268                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9269                                    // Since we changed the flags, we have to write.
9270                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9271                                            changedRuntimePermissionUserIds, userId);
9272                                }
9273                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9274                                    && !appSupportsRuntimePermissions) {
9275                                // For legacy apps that need a permission review, every new
9276                                // runtime permission is granted but it is pending a review.
9277                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9278                                    permissionsState.grantRuntimePermission(bp, userId);
9279                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9280                                    // We changed the permission and flags, hence have to write.
9281                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9282                                            changedRuntimePermissionUserIds, userId);
9283                                }
9284                            }
9285                            // Propagate the permission flags.
9286                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9287                        }
9288                    } break;
9289
9290                    case GRANT_UPGRADE: {
9291                        // Grant runtime permissions for a previously held install permission.
9292                        PermissionState permissionState = origPermissions
9293                                .getInstallPermissionState(bp.name);
9294                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9295
9296                        if (origPermissions.revokeInstallPermission(bp)
9297                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9298                            // We will be transferring the permission flags, so clear them.
9299                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9300                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9301                            changedInstallPermission = true;
9302                        }
9303
9304                        // If the permission is not to be promoted to runtime we ignore it and
9305                        // also its other flags as they are not applicable to install permissions.
9306                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9307                            for (int userId : currentUserIds) {
9308                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9309                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9310                                    // Transfer the permission flags.
9311                                    permissionsState.updatePermissionFlags(bp, userId,
9312                                            flags, flags);
9313                                    // If we granted the permission, we have to write.
9314                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9315                                            changedRuntimePermissionUserIds, userId);
9316                                }
9317                            }
9318                        }
9319                    } break;
9320
9321                    default: {
9322                        if (packageOfInterest == null
9323                                || packageOfInterest.equals(pkg.packageName)) {
9324                            Slog.w(TAG, "Not granting permission " + perm
9325                                    + " to package " + pkg.packageName
9326                                    + " because it was previously installed without");
9327                        }
9328                    } break;
9329                }
9330            } else {
9331                if (permissionsState.revokeInstallPermission(bp) !=
9332                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9333                    // Also drop the permission flags.
9334                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9335                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9336                    changedInstallPermission = true;
9337                    Slog.i(TAG, "Un-granting permission " + perm
9338                            + " from package " + pkg.packageName
9339                            + " (protectionLevel=" + bp.protectionLevel
9340                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9341                            + ")");
9342                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9343                    // Don't print warning for app op permissions, since it is fine for them
9344                    // not to be granted, there is a UI for the user to decide.
9345                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9346                        Slog.w(TAG, "Not granting permission " + perm
9347                                + " to package " + pkg.packageName
9348                                + " (protectionLevel=" + bp.protectionLevel
9349                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9350                                + ")");
9351                    }
9352                }
9353            }
9354        }
9355
9356        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9357                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9358            // This is the first that we have heard about this package, so the
9359            // permissions we have now selected are fixed until explicitly
9360            // changed.
9361            ps.installPermissionsFixed = true;
9362        }
9363
9364        // Persist the runtime permissions state for users with changes. If permissions
9365        // were revoked because no app in the shared user declares them we have to
9366        // write synchronously to avoid losing runtime permissions state.
9367        for (int userId : changedRuntimePermissionUserIds) {
9368            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9369        }
9370
9371        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9372    }
9373
9374    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9375        boolean allowed = false;
9376        final int NP = PackageParser.NEW_PERMISSIONS.length;
9377        for (int ip=0; ip<NP; ip++) {
9378            final PackageParser.NewPermissionInfo npi
9379                    = PackageParser.NEW_PERMISSIONS[ip];
9380            if (npi.name.equals(perm)
9381                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9382                allowed = true;
9383                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9384                        + pkg.packageName);
9385                break;
9386            }
9387        }
9388        return allowed;
9389    }
9390
9391    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9392            BasePermission bp, PermissionsState origPermissions) {
9393        boolean allowed;
9394        allowed = (compareSignatures(
9395                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9396                        == PackageManager.SIGNATURE_MATCH)
9397                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9398                        == PackageManager.SIGNATURE_MATCH);
9399        if (!allowed && (bp.protectionLevel
9400                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9401            if (isSystemApp(pkg)) {
9402                // For updated system applications, a system permission
9403                // is granted only if it had been defined by the original application.
9404                if (pkg.isUpdatedSystemApp()) {
9405                    final PackageSetting sysPs = mSettings
9406                            .getDisabledSystemPkgLPr(pkg.packageName);
9407                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9408                        // If the original was granted this permission, we take
9409                        // that grant decision as read and propagate it to the
9410                        // update.
9411                        if (sysPs.isPrivileged()) {
9412                            allowed = true;
9413                        }
9414                    } else {
9415                        // The system apk may have been updated with an older
9416                        // version of the one on the data partition, but which
9417                        // granted a new system permission that it didn't have
9418                        // before.  In this case we do want to allow the app to
9419                        // now get the new permission if the ancestral apk is
9420                        // privileged to get it.
9421                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9422                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9423                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9424                                    allowed = true;
9425                                    break;
9426                                }
9427                            }
9428                        }
9429                        // Also if a privileged parent package on the system image or any of
9430                        // its children requested a privileged permission, the updated child
9431                        // packages can also get the permission.
9432                        if (pkg.parentPackage != null) {
9433                            final PackageSetting disabledSysParentPs = mSettings
9434                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9435                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9436                                    && disabledSysParentPs.isPrivileged()) {
9437                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9438                                    allowed = true;
9439                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9440                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9441                                    for (int i = 0; i < count; i++) {
9442                                        PackageParser.Package disabledSysChildPkg =
9443                                                disabledSysParentPs.pkg.childPackages.get(i);
9444                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9445                                                perm)) {
9446                                            allowed = true;
9447                                            break;
9448                                        }
9449                                    }
9450                                }
9451                            }
9452                        }
9453                    }
9454                } else {
9455                    allowed = isPrivilegedApp(pkg);
9456                }
9457            }
9458        }
9459        if (!allowed) {
9460            if (!allowed && (bp.protectionLevel
9461                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9462                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9463                // If this was a previously normal/dangerous permission that got moved
9464                // to a system permission as part of the runtime permission redesign, then
9465                // we still want to blindly grant it to old apps.
9466                allowed = true;
9467            }
9468            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9469                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9470                // If this permission is to be granted to the system installer and
9471                // this app is an installer, then it gets the permission.
9472                allowed = true;
9473            }
9474            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9475                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9476                // If this permission is to be granted to the system verifier and
9477                // this app is a verifier, then it gets the permission.
9478                allowed = true;
9479            }
9480            if (!allowed && (bp.protectionLevel
9481                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9482                    && isSystemApp(pkg)) {
9483                // Any pre-installed system app is allowed to get this permission.
9484                allowed = true;
9485            }
9486            if (!allowed && (bp.protectionLevel
9487                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9488                // For development permissions, a development permission
9489                // is granted only if it was already granted.
9490                allowed = origPermissions.hasInstallPermission(perm);
9491            }
9492        }
9493        return allowed;
9494    }
9495
9496    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9497        final int permCount = pkg.requestedPermissions.size();
9498        for (int j = 0; j < permCount; j++) {
9499            String requestedPermission = pkg.requestedPermissions.get(j);
9500            if (permission.equals(requestedPermission)) {
9501                return true;
9502            }
9503        }
9504        return false;
9505    }
9506
9507    final class ActivityIntentResolver
9508            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9510                boolean defaultOnly, int userId) {
9511            if (!sUserManager.exists(userId)) return null;
9512            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9513            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9514        }
9515
9516        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9517                int userId) {
9518            if (!sUserManager.exists(userId)) return null;
9519            mFlags = flags;
9520            return super.queryIntent(intent, resolvedType,
9521                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9522        }
9523
9524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9525                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9526            if (!sUserManager.exists(userId)) return null;
9527            if (packageActivities == null) {
9528                return null;
9529            }
9530            mFlags = flags;
9531            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9532            final int N = packageActivities.size();
9533            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9534                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9535
9536            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9537            for (int i = 0; i < N; ++i) {
9538                intentFilters = packageActivities.get(i).intents;
9539                if (intentFilters != null && intentFilters.size() > 0) {
9540                    PackageParser.ActivityIntentInfo[] array =
9541                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9542                    intentFilters.toArray(array);
9543                    listCut.add(array);
9544                }
9545            }
9546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9547        }
9548
9549        public final void addActivity(PackageParser.Activity a, String type) {
9550            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9551            mActivities.put(a.getComponentName(), a);
9552            if (DEBUG_SHOW_INFO)
9553                Log.v(
9554                TAG, "  " + type + " " +
9555                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9556            if (DEBUG_SHOW_INFO)
9557                Log.v(TAG, "    Class=" + a.info.name);
9558            final int NI = a.intents.size();
9559            for (int j=0; j<NI; j++) {
9560                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9561                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9562                    intent.setPriority(0);
9563                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9564                            + a.className + " with priority > 0, forcing to 0");
9565                }
9566                if (DEBUG_SHOW_INFO) {
9567                    Log.v(TAG, "    IntentFilter:");
9568                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9569                }
9570                if (!intent.debugCheck()) {
9571                    Log.w(TAG, "==> For Activity " + a.info.name);
9572                }
9573                addFilter(intent);
9574            }
9575        }
9576
9577        public final void removeActivity(PackageParser.Activity a, String type) {
9578            mActivities.remove(a.getComponentName());
9579            if (DEBUG_SHOW_INFO) {
9580                Log.v(TAG, "  " + type + " "
9581                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9582                                : a.info.name) + ":");
9583                Log.v(TAG, "    Class=" + a.info.name);
9584            }
9585            final int NI = a.intents.size();
9586            for (int j=0; j<NI; j++) {
9587                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9588                if (DEBUG_SHOW_INFO) {
9589                    Log.v(TAG, "    IntentFilter:");
9590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9591                }
9592                removeFilter(intent);
9593            }
9594        }
9595
9596        @Override
9597        protected boolean allowFilterResult(
9598                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9599            ActivityInfo filterAi = filter.activity.info;
9600            for (int i=dest.size()-1; i>=0; i--) {
9601                ActivityInfo destAi = dest.get(i).activityInfo;
9602                if (destAi.name == filterAi.name
9603                        && destAi.packageName == filterAi.packageName) {
9604                    return false;
9605                }
9606            }
9607            return true;
9608        }
9609
9610        @Override
9611        protected ActivityIntentInfo[] newArray(int size) {
9612            return new ActivityIntentInfo[size];
9613        }
9614
9615        @Override
9616        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9617            if (!sUserManager.exists(userId)) return true;
9618            PackageParser.Package p = filter.activity.owner;
9619            if (p != null) {
9620                PackageSetting ps = (PackageSetting)p.mExtras;
9621                if (ps != null) {
9622                    // System apps are never considered stopped for purposes of
9623                    // filtering, because there may be no way for the user to
9624                    // actually re-launch them.
9625                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9626                            && ps.getStopped(userId);
9627                }
9628            }
9629            return false;
9630        }
9631
9632        @Override
9633        protected boolean isPackageForFilter(String packageName,
9634                PackageParser.ActivityIntentInfo info) {
9635            return packageName.equals(info.activity.owner.packageName);
9636        }
9637
9638        @Override
9639        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9640                int match, int userId) {
9641            if (!sUserManager.exists(userId)) return null;
9642            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9643                return null;
9644            }
9645            final PackageParser.Activity activity = info.activity;
9646            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9647            if (ps == null) {
9648                return null;
9649            }
9650            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9651                    ps.readUserState(userId), userId);
9652            if (ai == null) {
9653                return null;
9654            }
9655            final ResolveInfo res = new ResolveInfo();
9656            res.activityInfo = ai;
9657            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9658                res.filter = info;
9659            }
9660            if (info != null) {
9661                res.handleAllWebDataURI = info.handleAllWebDataURI();
9662            }
9663            res.priority = info.getPriority();
9664            res.preferredOrder = activity.owner.mPreferredOrder;
9665            //System.out.println("Result: " + res.activityInfo.className +
9666            //                   " = " + res.priority);
9667            res.match = match;
9668            res.isDefault = info.hasDefault;
9669            res.labelRes = info.labelRes;
9670            res.nonLocalizedLabel = info.nonLocalizedLabel;
9671            if (userNeedsBadging(userId)) {
9672                res.noResourceId = true;
9673            } else {
9674                res.icon = info.icon;
9675            }
9676            res.iconResourceId = info.icon;
9677            res.system = res.activityInfo.applicationInfo.isSystemApp();
9678            return res;
9679        }
9680
9681        @Override
9682        protected void sortResults(List<ResolveInfo> results) {
9683            Collections.sort(results, mResolvePrioritySorter);
9684        }
9685
9686        @Override
9687        protected void dumpFilter(PrintWriter out, String prefix,
9688                PackageParser.ActivityIntentInfo filter) {
9689            out.print(prefix); out.print(
9690                    Integer.toHexString(System.identityHashCode(filter.activity)));
9691                    out.print(' ');
9692                    filter.activity.printComponentShortName(out);
9693                    out.print(" filter ");
9694                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9695        }
9696
9697        @Override
9698        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9699            return filter.activity;
9700        }
9701
9702        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9703            PackageParser.Activity activity = (PackageParser.Activity)label;
9704            out.print(prefix); out.print(
9705                    Integer.toHexString(System.identityHashCode(activity)));
9706                    out.print(' ');
9707                    activity.printComponentShortName(out);
9708            if (count > 1) {
9709                out.print(" ("); out.print(count); out.print(" filters)");
9710            }
9711            out.println();
9712        }
9713
9714//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9715//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9716//            final List<ResolveInfo> retList = Lists.newArrayList();
9717//            while (i.hasNext()) {
9718//                final ResolveInfo resolveInfo = i.next();
9719//                if (isEnabledLP(resolveInfo.activityInfo)) {
9720//                    retList.add(resolveInfo);
9721//                }
9722//            }
9723//            return retList;
9724//        }
9725
9726        // Keys are String (activity class name), values are Activity.
9727        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9728                = new ArrayMap<ComponentName, PackageParser.Activity>();
9729        private int mFlags;
9730    }
9731
9732    private final class ServiceIntentResolver
9733            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9735                boolean defaultOnly, int userId) {
9736            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9737            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9738        }
9739
9740        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9741                int userId) {
9742            if (!sUserManager.exists(userId)) return null;
9743            mFlags = flags;
9744            return super.queryIntent(intent, resolvedType,
9745                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9746        }
9747
9748        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9749                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9750            if (!sUserManager.exists(userId)) return null;
9751            if (packageServices == null) {
9752                return null;
9753            }
9754            mFlags = flags;
9755            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9756            final int N = packageServices.size();
9757            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9758                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9759
9760            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9761            for (int i = 0; i < N; ++i) {
9762                intentFilters = packageServices.get(i).intents;
9763                if (intentFilters != null && intentFilters.size() > 0) {
9764                    PackageParser.ServiceIntentInfo[] array =
9765                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9766                    intentFilters.toArray(array);
9767                    listCut.add(array);
9768                }
9769            }
9770            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9771        }
9772
9773        public final void addService(PackageParser.Service s) {
9774            mServices.put(s.getComponentName(), s);
9775            if (DEBUG_SHOW_INFO) {
9776                Log.v(TAG, "  "
9777                        + (s.info.nonLocalizedLabel != null
9778                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9779                Log.v(TAG, "    Class=" + s.info.name);
9780            }
9781            final int NI = s.intents.size();
9782            int j;
9783            for (j=0; j<NI; j++) {
9784                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9785                if (DEBUG_SHOW_INFO) {
9786                    Log.v(TAG, "    IntentFilter:");
9787                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9788                }
9789                if (!intent.debugCheck()) {
9790                    Log.w(TAG, "==> For Service " + s.info.name);
9791                }
9792                addFilter(intent);
9793            }
9794        }
9795
9796        public final void removeService(PackageParser.Service s) {
9797            mServices.remove(s.getComponentName());
9798            if (DEBUG_SHOW_INFO) {
9799                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9800                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9801                Log.v(TAG, "    Class=" + s.info.name);
9802            }
9803            final int NI = s.intents.size();
9804            int j;
9805            for (j=0; j<NI; j++) {
9806                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9807                if (DEBUG_SHOW_INFO) {
9808                    Log.v(TAG, "    IntentFilter:");
9809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9810                }
9811                removeFilter(intent);
9812            }
9813        }
9814
9815        @Override
9816        protected boolean allowFilterResult(
9817                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9818            ServiceInfo filterSi = filter.service.info;
9819            for (int i=dest.size()-1; i>=0; i--) {
9820                ServiceInfo destAi = dest.get(i).serviceInfo;
9821                if (destAi.name == filterSi.name
9822                        && destAi.packageName == filterSi.packageName) {
9823                    return false;
9824                }
9825            }
9826            return true;
9827        }
9828
9829        @Override
9830        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9831            return new PackageParser.ServiceIntentInfo[size];
9832        }
9833
9834        @Override
9835        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9836            if (!sUserManager.exists(userId)) return true;
9837            PackageParser.Package p = filter.service.owner;
9838            if (p != null) {
9839                PackageSetting ps = (PackageSetting)p.mExtras;
9840                if (ps != null) {
9841                    // System apps are never considered stopped for purposes of
9842                    // filtering, because there may be no way for the user to
9843                    // actually re-launch them.
9844                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9845                            && ps.getStopped(userId);
9846                }
9847            }
9848            return false;
9849        }
9850
9851        @Override
9852        protected boolean isPackageForFilter(String packageName,
9853                PackageParser.ServiceIntentInfo info) {
9854            return packageName.equals(info.service.owner.packageName);
9855        }
9856
9857        @Override
9858        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9859                int match, int userId) {
9860            if (!sUserManager.exists(userId)) return null;
9861            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9862            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9863                return null;
9864            }
9865            final PackageParser.Service service = info.service;
9866            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9867            if (ps == null) {
9868                return null;
9869            }
9870            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9871                    ps.readUserState(userId), userId);
9872            if (si == null) {
9873                return null;
9874            }
9875            final ResolveInfo res = new ResolveInfo();
9876            res.serviceInfo = si;
9877            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9878                res.filter = filter;
9879            }
9880            res.priority = info.getPriority();
9881            res.preferredOrder = service.owner.mPreferredOrder;
9882            res.match = match;
9883            res.isDefault = info.hasDefault;
9884            res.labelRes = info.labelRes;
9885            res.nonLocalizedLabel = info.nonLocalizedLabel;
9886            res.icon = info.icon;
9887            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9888            return res;
9889        }
9890
9891        @Override
9892        protected void sortResults(List<ResolveInfo> results) {
9893            Collections.sort(results, mResolvePrioritySorter);
9894        }
9895
9896        @Override
9897        protected void dumpFilter(PrintWriter out, String prefix,
9898                PackageParser.ServiceIntentInfo filter) {
9899            out.print(prefix); out.print(
9900                    Integer.toHexString(System.identityHashCode(filter.service)));
9901                    out.print(' ');
9902                    filter.service.printComponentShortName(out);
9903                    out.print(" filter ");
9904                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9905        }
9906
9907        @Override
9908        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9909            return filter.service;
9910        }
9911
9912        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9913            PackageParser.Service service = (PackageParser.Service)label;
9914            out.print(prefix); out.print(
9915                    Integer.toHexString(System.identityHashCode(service)));
9916                    out.print(' ');
9917                    service.printComponentShortName(out);
9918            if (count > 1) {
9919                out.print(" ("); out.print(count); out.print(" filters)");
9920            }
9921            out.println();
9922        }
9923
9924//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9925//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9926//            final List<ResolveInfo> retList = Lists.newArrayList();
9927//            while (i.hasNext()) {
9928//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9929//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9930//                    retList.add(resolveInfo);
9931//                }
9932//            }
9933//            return retList;
9934//        }
9935
9936        // Keys are String (activity class name), values are Activity.
9937        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9938                = new ArrayMap<ComponentName, PackageParser.Service>();
9939        private int mFlags;
9940    };
9941
9942    private final class ProviderIntentResolver
9943            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9944        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9945                boolean defaultOnly, int userId) {
9946            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9947            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9948        }
9949
9950        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9951                int userId) {
9952            if (!sUserManager.exists(userId))
9953                return null;
9954            mFlags = flags;
9955            return super.queryIntent(intent, resolvedType,
9956                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9957        }
9958
9959        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9960                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9961            if (!sUserManager.exists(userId))
9962                return null;
9963            if (packageProviders == null) {
9964                return null;
9965            }
9966            mFlags = flags;
9967            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9968            final int N = packageProviders.size();
9969            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9970                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9971
9972            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9973            for (int i = 0; i < N; ++i) {
9974                intentFilters = packageProviders.get(i).intents;
9975                if (intentFilters != null && intentFilters.size() > 0) {
9976                    PackageParser.ProviderIntentInfo[] array =
9977                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9978                    intentFilters.toArray(array);
9979                    listCut.add(array);
9980                }
9981            }
9982            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9983        }
9984
9985        public final void addProvider(PackageParser.Provider p) {
9986            if (mProviders.containsKey(p.getComponentName())) {
9987                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9988                return;
9989            }
9990
9991            mProviders.put(p.getComponentName(), p);
9992            if (DEBUG_SHOW_INFO) {
9993                Log.v(TAG, "  "
9994                        + (p.info.nonLocalizedLabel != null
9995                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9996                Log.v(TAG, "    Class=" + p.info.name);
9997            }
9998            final int NI = p.intents.size();
9999            int j;
10000            for (j = 0; j < NI; j++) {
10001                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10002                if (DEBUG_SHOW_INFO) {
10003                    Log.v(TAG, "    IntentFilter:");
10004                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10005                }
10006                if (!intent.debugCheck()) {
10007                    Log.w(TAG, "==> For Provider " + p.info.name);
10008                }
10009                addFilter(intent);
10010            }
10011        }
10012
10013        public final void removeProvider(PackageParser.Provider p) {
10014            mProviders.remove(p.getComponentName());
10015            if (DEBUG_SHOW_INFO) {
10016                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10017                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10018                Log.v(TAG, "    Class=" + p.info.name);
10019            }
10020            final int NI = p.intents.size();
10021            int j;
10022            for (j = 0; j < NI; j++) {
10023                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10024                if (DEBUG_SHOW_INFO) {
10025                    Log.v(TAG, "    IntentFilter:");
10026                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10027                }
10028                removeFilter(intent);
10029            }
10030        }
10031
10032        @Override
10033        protected boolean allowFilterResult(
10034                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10035            ProviderInfo filterPi = filter.provider.info;
10036            for (int i = dest.size() - 1; i >= 0; i--) {
10037                ProviderInfo destPi = dest.get(i).providerInfo;
10038                if (destPi.name == filterPi.name
10039                        && destPi.packageName == filterPi.packageName) {
10040                    return false;
10041                }
10042            }
10043            return true;
10044        }
10045
10046        @Override
10047        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10048            return new PackageParser.ProviderIntentInfo[size];
10049        }
10050
10051        @Override
10052        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10053            if (!sUserManager.exists(userId))
10054                return true;
10055            PackageParser.Package p = filter.provider.owner;
10056            if (p != null) {
10057                PackageSetting ps = (PackageSetting) p.mExtras;
10058                if (ps != null) {
10059                    // System apps are never considered stopped for purposes of
10060                    // filtering, because there may be no way for the user to
10061                    // actually re-launch them.
10062                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10063                            && ps.getStopped(userId);
10064                }
10065            }
10066            return false;
10067        }
10068
10069        @Override
10070        protected boolean isPackageForFilter(String packageName,
10071                PackageParser.ProviderIntentInfo info) {
10072            return packageName.equals(info.provider.owner.packageName);
10073        }
10074
10075        @Override
10076        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10077                int match, int userId) {
10078            if (!sUserManager.exists(userId))
10079                return null;
10080            final PackageParser.ProviderIntentInfo info = filter;
10081            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10082                return null;
10083            }
10084            final PackageParser.Provider provider = info.provider;
10085            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10086            if (ps == null) {
10087                return null;
10088            }
10089            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10090                    ps.readUserState(userId), userId);
10091            if (pi == null) {
10092                return null;
10093            }
10094            final ResolveInfo res = new ResolveInfo();
10095            res.providerInfo = pi;
10096            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10097                res.filter = filter;
10098            }
10099            res.priority = info.getPriority();
10100            res.preferredOrder = provider.owner.mPreferredOrder;
10101            res.match = match;
10102            res.isDefault = info.hasDefault;
10103            res.labelRes = info.labelRes;
10104            res.nonLocalizedLabel = info.nonLocalizedLabel;
10105            res.icon = info.icon;
10106            res.system = res.providerInfo.applicationInfo.isSystemApp();
10107            return res;
10108        }
10109
10110        @Override
10111        protected void sortResults(List<ResolveInfo> results) {
10112            Collections.sort(results, mResolvePrioritySorter);
10113        }
10114
10115        @Override
10116        protected void dumpFilter(PrintWriter out, String prefix,
10117                PackageParser.ProviderIntentInfo filter) {
10118            out.print(prefix);
10119            out.print(
10120                    Integer.toHexString(System.identityHashCode(filter.provider)));
10121            out.print(' ');
10122            filter.provider.printComponentShortName(out);
10123            out.print(" filter ");
10124            out.println(Integer.toHexString(System.identityHashCode(filter)));
10125        }
10126
10127        @Override
10128        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10129            return filter.provider;
10130        }
10131
10132        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10133            PackageParser.Provider provider = (PackageParser.Provider)label;
10134            out.print(prefix); out.print(
10135                    Integer.toHexString(System.identityHashCode(provider)));
10136                    out.print(' ');
10137                    provider.printComponentShortName(out);
10138            if (count > 1) {
10139                out.print(" ("); out.print(count); out.print(" filters)");
10140            }
10141            out.println();
10142        }
10143
10144        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10145                = new ArrayMap<ComponentName, PackageParser.Provider>();
10146        private int mFlags;
10147    }
10148
10149    private static final class EphemeralIntentResolver
10150            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10151        @Override
10152        protected EphemeralResolveIntentInfo[] newArray(int size) {
10153            return new EphemeralResolveIntentInfo[size];
10154        }
10155
10156        @Override
10157        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10158            return true;
10159        }
10160
10161        @Override
10162        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10163                int userId) {
10164            if (!sUserManager.exists(userId)) {
10165                return null;
10166            }
10167            return info.getEphemeralResolveInfo();
10168        }
10169    }
10170
10171    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10172            new Comparator<ResolveInfo>() {
10173        public int compare(ResolveInfo r1, ResolveInfo r2) {
10174            int v1 = r1.priority;
10175            int v2 = r2.priority;
10176            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10177            if (v1 != v2) {
10178                return (v1 > v2) ? -1 : 1;
10179            }
10180            v1 = r1.preferredOrder;
10181            v2 = r2.preferredOrder;
10182            if (v1 != v2) {
10183                return (v1 > v2) ? -1 : 1;
10184            }
10185            if (r1.isDefault != r2.isDefault) {
10186                return r1.isDefault ? -1 : 1;
10187            }
10188            v1 = r1.match;
10189            v2 = r2.match;
10190            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10191            if (v1 != v2) {
10192                return (v1 > v2) ? -1 : 1;
10193            }
10194            if (r1.system != r2.system) {
10195                return r1.system ? -1 : 1;
10196            }
10197            if (r1.activityInfo != null) {
10198                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10199            }
10200            if (r1.serviceInfo != null) {
10201                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10202            }
10203            if (r1.providerInfo != null) {
10204                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10205            }
10206            return 0;
10207        }
10208    };
10209
10210    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10211            new Comparator<ProviderInfo>() {
10212        public int compare(ProviderInfo p1, ProviderInfo p2) {
10213            final int v1 = p1.initOrder;
10214            final int v2 = p2.initOrder;
10215            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10216        }
10217    };
10218
10219    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10220            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10221            final int[] userIds) {
10222        mHandler.post(new Runnable() {
10223            @Override
10224            public void run() {
10225                try {
10226                    final IActivityManager am = ActivityManagerNative.getDefault();
10227                    if (am == null) return;
10228                    final int[] resolvedUserIds;
10229                    if (userIds == null) {
10230                        resolvedUserIds = am.getRunningUserIds();
10231                    } else {
10232                        resolvedUserIds = userIds;
10233                    }
10234                    for (int id : resolvedUserIds) {
10235                        final Intent intent = new Intent(action,
10236                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10237                        if (extras != null) {
10238                            intent.putExtras(extras);
10239                        }
10240                        if (targetPkg != null) {
10241                            intent.setPackage(targetPkg);
10242                        }
10243                        // Modify the UID when posting to other users
10244                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10245                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10246                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10247                            intent.putExtra(Intent.EXTRA_UID, uid);
10248                        }
10249                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10250                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10251                        if (DEBUG_BROADCASTS) {
10252                            RuntimeException here = new RuntimeException("here");
10253                            here.fillInStackTrace();
10254                            Slog.d(TAG, "Sending to user " + id + ": "
10255                                    + intent.toShortString(false, true, false, false)
10256                                    + " " + intent.getExtras(), here);
10257                        }
10258                        am.broadcastIntent(null, intent, null, finishedReceiver,
10259                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10260                                null, finishedReceiver != null, false, id);
10261                    }
10262                } catch (RemoteException ex) {
10263                }
10264            }
10265        });
10266    }
10267
10268    /**
10269     * Check if the external storage media is available. This is true if there
10270     * is a mounted external storage medium or if the external storage is
10271     * emulated.
10272     */
10273    private boolean isExternalMediaAvailable() {
10274        return mMediaMounted || Environment.isExternalStorageEmulated();
10275    }
10276
10277    @Override
10278    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10279        // writer
10280        synchronized (mPackages) {
10281            if (!isExternalMediaAvailable()) {
10282                // If the external storage is no longer mounted at this point,
10283                // the caller may not have been able to delete all of this
10284                // packages files and can not delete any more.  Bail.
10285                return null;
10286            }
10287            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10288            if (lastPackage != null) {
10289                pkgs.remove(lastPackage);
10290            }
10291            if (pkgs.size() > 0) {
10292                return pkgs.get(0);
10293            }
10294        }
10295        return null;
10296    }
10297
10298    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10299        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10300                userId, andCode ? 1 : 0, packageName);
10301        if (mSystemReady) {
10302            msg.sendToTarget();
10303        } else {
10304            if (mPostSystemReadyMessages == null) {
10305                mPostSystemReadyMessages = new ArrayList<>();
10306            }
10307            mPostSystemReadyMessages.add(msg);
10308        }
10309    }
10310
10311    void startCleaningPackages() {
10312        // reader
10313        synchronized (mPackages) {
10314            if (!isExternalMediaAvailable()) {
10315                return;
10316            }
10317            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10318                return;
10319            }
10320        }
10321        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10322        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10323        IActivityManager am = ActivityManagerNative.getDefault();
10324        if (am != null) {
10325            try {
10326                am.startService(null, intent, null, mContext.getOpPackageName(),
10327                        UserHandle.USER_SYSTEM);
10328            } catch (RemoteException e) {
10329            }
10330        }
10331    }
10332
10333    @Override
10334    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10335            int installFlags, String installerPackageName, VerificationParams verificationParams,
10336            String packageAbiOverride) {
10337        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10338                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10339    }
10340
10341    @Override
10342    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10343            int installFlags, String installerPackageName, VerificationParams verificationParams,
10344            String packageAbiOverride, int userId) {
10345        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10346
10347        final int callingUid = Binder.getCallingUid();
10348        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10349
10350        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10351            try {
10352                if (observer != null) {
10353                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10354                }
10355            } catch (RemoteException re) {
10356            }
10357            return;
10358        }
10359
10360        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10361            installFlags |= PackageManager.INSTALL_FROM_ADB;
10362
10363        } else {
10364            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10365            // about installerPackageName.
10366
10367            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10368            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10369        }
10370
10371        UserHandle user;
10372        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10373            user = UserHandle.ALL;
10374        } else {
10375            user = new UserHandle(userId);
10376        }
10377
10378        // Only system components can circumvent runtime permissions when installing.
10379        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10380                && mContext.checkCallingOrSelfPermission(Manifest.permission
10381                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10382            throw new SecurityException("You need the "
10383                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10384                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10385        }
10386
10387        verificationParams.setInstallerUid(callingUid);
10388
10389        final File originFile = new File(originPath);
10390        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10391
10392        final Message msg = mHandler.obtainMessage(INIT_COPY);
10393        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10394                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10395        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10396        msg.obj = params;
10397
10398        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10399                System.identityHashCode(msg.obj));
10400        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10401                System.identityHashCode(msg.obj));
10402
10403        mHandler.sendMessage(msg);
10404    }
10405
10406    void installStage(String packageName, File stagedDir, String stagedCid,
10407            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10408            String installerPackageName, int installerUid, UserHandle user) {
10409        if (DEBUG_EPHEMERAL) {
10410            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10411                Slog.d(TAG, "Ephemeral install of " + packageName);
10412            }
10413        }
10414        final VerificationParams verifParams = new VerificationParams(
10415                null, sessionParams.originatingUri, sessionParams.referrerUri,
10416                sessionParams.originatingUid);
10417        verifParams.setInstallerUid(installerUid);
10418
10419        final OriginInfo origin;
10420        if (stagedDir != null) {
10421            origin = OriginInfo.fromStagedFile(stagedDir);
10422        } else {
10423            origin = OriginInfo.fromStagedContainer(stagedCid);
10424        }
10425
10426        final Message msg = mHandler.obtainMessage(INIT_COPY);
10427        final InstallParams params = new InstallParams(origin, null, observer,
10428                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10429                verifParams, user, sessionParams.abiOverride,
10430                sessionParams.grantedRuntimePermissions);
10431        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10432        msg.obj = params;
10433
10434        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10435                System.identityHashCode(msg.obj));
10436        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10437                System.identityHashCode(msg.obj));
10438
10439        mHandler.sendMessage(msg);
10440    }
10441
10442    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10443        Bundle extras = new Bundle(1);
10444        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10445
10446        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10447                packageName, extras, 0, null, null, new int[] {userId});
10448        try {
10449            IActivityManager am = ActivityManagerNative.getDefault();
10450            final boolean isSystem =
10451                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10452            if (isSystem && am.isUserRunning(userId, 0)) {
10453                // The just-installed/enabled app is bundled on the system, so presumed
10454                // to be able to run automatically without needing an explicit launch.
10455                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10456                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10457                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10458                        .setPackage(packageName);
10459                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10460                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10461            }
10462        } catch (RemoteException e) {
10463            // shouldn't happen
10464            Slog.w(TAG, "Unable to bootstrap installed package", e);
10465        }
10466    }
10467
10468    @Override
10469    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10470            int userId) {
10471        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10472        PackageSetting pkgSetting;
10473        final int uid = Binder.getCallingUid();
10474        enforceCrossUserPermission(uid, userId, true, true,
10475                "setApplicationHiddenSetting for user " + userId);
10476
10477        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10478            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10479            return false;
10480        }
10481
10482        long callingId = Binder.clearCallingIdentity();
10483        try {
10484            boolean sendAdded = false;
10485            boolean sendRemoved = false;
10486            // writer
10487            synchronized (mPackages) {
10488                pkgSetting = mSettings.mPackages.get(packageName);
10489                if (pkgSetting == null) {
10490                    return false;
10491                }
10492                if (pkgSetting.getHidden(userId) != hidden) {
10493                    pkgSetting.setHidden(hidden, userId);
10494                    mSettings.writePackageRestrictionsLPr(userId);
10495                    if (hidden) {
10496                        sendRemoved = true;
10497                    } else {
10498                        sendAdded = true;
10499                    }
10500                }
10501            }
10502            if (sendAdded) {
10503                sendPackageAddedForUser(packageName, pkgSetting, userId);
10504                return true;
10505            }
10506            if (sendRemoved) {
10507                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10508                        "hiding pkg");
10509                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10510                return true;
10511            }
10512        } finally {
10513            Binder.restoreCallingIdentity(callingId);
10514        }
10515        return false;
10516    }
10517
10518    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10519            int userId) {
10520        final PackageRemovedInfo info = new PackageRemovedInfo();
10521        info.removedPackage = packageName;
10522        info.removedUsers = new int[] {userId};
10523        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10524        info.sendBroadcast(false, false, false);
10525    }
10526
10527    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10528        if (pkgList.length > 0) {
10529            Bundle extras = new Bundle(1);
10530            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10531
10532            sendPackageBroadcast(
10533                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10534                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10535                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10536                    new int[] {userId});
10537        }
10538    }
10539
10540    /**
10541     * Returns true if application is not found or there was an error. Otherwise it returns
10542     * the hidden state of the package for the given user.
10543     */
10544    @Override
10545    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10546        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10547        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10548                false, "getApplicationHidden for user " + userId);
10549        PackageSetting pkgSetting;
10550        long callingId = Binder.clearCallingIdentity();
10551        try {
10552            // writer
10553            synchronized (mPackages) {
10554                pkgSetting = mSettings.mPackages.get(packageName);
10555                if (pkgSetting == null) {
10556                    return true;
10557                }
10558                return pkgSetting.getHidden(userId);
10559            }
10560        } finally {
10561            Binder.restoreCallingIdentity(callingId);
10562        }
10563    }
10564
10565    /**
10566     * @hide
10567     */
10568    @Override
10569    public int installExistingPackageAsUser(String packageName, int userId) {
10570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10571                null);
10572        PackageSetting pkgSetting;
10573        final int uid = Binder.getCallingUid();
10574        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10575                + userId);
10576        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10577            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10578        }
10579
10580        long callingId = Binder.clearCallingIdentity();
10581        try {
10582            boolean installed = false;
10583
10584            // writer
10585            synchronized (mPackages) {
10586                pkgSetting = mSettings.mPackages.get(packageName);
10587                if (pkgSetting == null) {
10588                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10589                }
10590                if (!pkgSetting.getInstalled(userId)) {
10591                    pkgSetting.setInstalled(true, userId);
10592                    pkgSetting.setHidden(false, userId);
10593                    mSettings.writePackageRestrictionsLPr(userId);
10594                    if (pkgSetting.pkg != null) {
10595                        prepareAppDataAfterInstall(pkgSetting.pkg);
10596                    }
10597                    installed = true;
10598                }
10599            }
10600
10601            if (installed) {
10602                sendPackageAddedForUser(packageName, pkgSetting, userId);
10603            }
10604        } finally {
10605            Binder.restoreCallingIdentity(callingId);
10606        }
10607
10608        return PackageManager.INSTALL_SUCCEEDED;
10609    }
10610
10611    boolean isUserRestricted(int userId, String restrictionKey) {
10612        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10613        if (restrictions.getBoolean(restrictionKey, false)) {
10614            Log.w(TAG, "User is restricted: " + restrictionKey);
10615            return true;
10616        }
10617        return false;
10618    }
10619
10620    @Override
10621    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10622        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10624                "setPackageSuspended for user " + userId);
10625
10626        // TODO: investigate and add more restrictions for suspending crucial packages.
10627        if (isPackageDeviceAdmin(packageName, userId)) {
10628            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10629                    + "\": has active device admin");
10630            return false;
10631        }
10632
10633        long callingId = Binder.clearCallingIdentity();
10634        try {
10635            boolean changed = false;
10636            boolean success = false;
10637            int appId = -1;
10638            synchronized (mPackages) {
10639                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10640                if (pkgSetting != null) {
10641                    if (pkgSetting.getSuspended(userId) != suspended) {
10642                        pkgSetting.setSuspended(suspended, userId);
10643                        mSettings.writePackageRestrictionsLPr(userId);
10644                        appId = pkgSetting.appId;
10645                        changed = true;
10646                    }
10647                    success = true;
10648                }
10649            }
10650
10651            if (changed) {
10652                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10653                if (suspended) {
10654                    killApplication(packageName, UserHandle.getUid(userId, appId),
10655                            "suspending package");
10656                }
10657            }
10658            return success;
10659        } finally {
10660            Binder.restoreCallingIdentity(callingId);
10661        }
10662    }
10663
10664    @Override
10665    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10666        mContext.enforceCallingOrSelfPermission(
10667                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10668                "Only package verification agents can verify applications");
10669
10670        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10671        final PackageVerificationResponse response = new PackageVerificationResponse(
10672                verificationCode, Binder.getCallingUid());
10673        msg.arg1 = id;
10674        msg.obj = response;
10675        mHandler.sendMessage(msg);
10676    }
10677
10678    @Override
10679    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10680            long millisecondsToDelay) {
10681        mContext.enforceCallingOrSelfPermission(
10682                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10683                "Only package verification agents can extend verification timeouts");
10684
10685        final PackageVerificationState state = mPendingVerification.get(id);
10686        final PackageVerificationResponse response = new PackageVerificationResponse(
10687                verificationCodeAtTimeout, Binder.getCallingUid());
10688
10689        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10690            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10691        }
10692        if (millisecondsToDelay < 0) {
10693            millisecondsToDelay = 0;
10694        }
10695        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10696                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10697            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10698        }
10699
10700        if ((state != null) && !state.timeoutExtended()) {
10701            state.extendTimeout();
10702
10703            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10704            msg.arg1 = id;
10705            msg.obj = response;
10706            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10707        }
10708    }
10709
10710    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10711            int verificationCode, UserHandle user) {
10712        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10713        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10714        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10715        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10716        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10717
10718        mContext.sendBroadcastAsUser(intent, user,
10719                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10720    }
10721
10722    private ComponentName matchComponentForVerifier(String packageName,
10723            List<ResolveInfo> receivers) {
10724        ActivityInfo targetReceiver = null;
10725
10726        final int NR = receivers.size();
10727        for (int i = 0; i < NR; i++) {
10728            final ResolveInfo info = receivers.get(i);
10729            if (info.activityInfo == null) {
10730                continue;
10731            }
10732
10733            if (packageName.equals(info.activityInfo.packageName)) {
10734                targetReceiver = info.activityInfo;
10735                break;
10736            }
10737        }
10738
10739        if (targetReceiver == null) {
10740            return null;
10741        }
10742
10743        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10744    }
10745
10746    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10747            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10748        if (pkgInfo.verifiers.length == 0) {
10749            return null;
10750        }
10751
10752        final int N = pkgInfo.verifiers.length;
10753        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10754        for (int i = 0; i < N; i++) {
10755            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10756
10757            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10758                    receivers);
10759            if (comp == null) {
10760                continue;
10761            }
10762
10763            final int verifierUid = getUidForVerifier(verifierInfo);
10764            if (verifierUid == -1) {
10765                continue;
10766            }
10767
10768            if (DEBUG_VERIFY) {
10769                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10770                        + " with the correct signature");
10771            }
10772            sufficientVerifiers.add(comp);
10773            verificationState.addSufficientVerifier(verifierUid);
10774        }
10775
10776        return sufficientVerifiers;
10777    }
10778
10779    private int getUidForVerifier(VerifierInfo verifierInfo) {
10780        synchronized (mPackages) {
10781            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10782            if (pkg == null) {
10783                return -1;
10784            } else if (pkg.mSignatures.length != 1) {
10785                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10786                        + " has more than one signature; ignoring");
10787                return -1;
10788            }
10789
10790            /*
10791             * If the public key of the package's signature does not match
10792             * our expected public key, then this is a different package and
10793             * we should skip.
10794             */
10795
10796            final byte[] expectedPublicKey;
10797            try {
10798                final Signature verifierSig = pkg.mSignatures[0];
10799                final PublicKey publicKey = verifierSig.getPublicKey();
10800                expectedPublicKey = publicKey.getEncoded();
10801            } catch (CertificateException e) {
10802                return -1;
10803            }
10804
10805            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10806
10807            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10808                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10809                        + " does not have the expected public key; ignoring");
10810                return -1;
10811            }
10812
10813            return pkg.applicationInfo.uid;
10814        }
10815    }
10816
10817    @Override
10818    public void finishPackageInstall(int token) {
10819        enforceSystemOrRoot("Only the system is allowed to finish installs");
10820
10821        if (DEBUG_INSTALL) {
10822            Slog.v(TAG, "BM finishing package install for " + token);
10823        }
10824        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10825
10826        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10827        mHandler.sendMessage(msg);
10828    }
10829
10830    /**
10831     * Get the verification agent timeout.
10832     *
10833     * @return verification timeout in milliseconds
10834     */
10835    private long getVerificationTimeout() {
10836        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10837                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10838                DEFAULT_VERIFICATION_TIMEOUT);
10839    }
10840
10841    /**
10842     * Get the default verification agent response code.
10843     *
10844     * @return default verification response code
10845     */
10846    private int getDefaultVerificationResponse() {
10847        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10848                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10849                DEFAULT_VERIFICATION_RESPONSE);
10850    }
10851
10852    /**
10853     * Check whether or not package verification has been enabled.
10854     *
10855     * @return true if verification should be performed
10856     */
10857    private boolean isVerificationEnabled(int userId, int installFlags) {
10858        if (!DEFAULT_VERIFY_ENABLE) {
10859            return false;
10860        }
10861        // Ephemeral apps don't get the full verification treatment
10862        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10863            if (DEBUG_EPHEMERAL) {
10864                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10865            }
10866            return false;
10867        }
10868
10869        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10870
10871        // Check if installing from ADB
10872        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10873            // Do not run verification in a test harness environment
10874            if (ActivityManager.isRunningInTestHarness()) {
10875                return false;
10876            }
10877            if (ensureVerifyAppsEnabled) {
10878                return true;
10879            }
10880            // Check if the developer does not want package verification for ADB installs
10881            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10882                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10883                return false;
10884            }
10885        }
10886
10887        if (ensureVerifyAppsEnabled) {
10888            return true;
10889        }
10890
10891        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10892                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10893    }
10894
10895    @Override
10896    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10897            throws RemoteException {
10898        mContext.enforceCallingOrSelfPermission(
10899                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10900                "Only intentfilter verification agents can verify applications");
10901
10902        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10903        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10904                Binder.getCallingUid(), verificationCode, failedDomains);
10905        msg.arg1 = id;
10906        msg.obj = response;
10907        mHandler.sendMessage(msg);
10908    }
10909
10910    @Override
10911    public int getIntentVerificationStatus(String packageName, int userId) {
10912        synchronized (mPackages) {
10913            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10914        }
10915    }
10916
10917    @Override
10918    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10919        mContext.enforceCallingOrSelfPermission(
10920                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10921
10922        boolean result = false;
10923        synchronized (mPackages) {
10924            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10925        }
10926        if (result) {
10927            scheduleWritePackageRestrictionsLocked(userId);
10928        }
10929        return result;
10930    }
10931
10932    @Override
10933    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10934        synchronized (mPackages) {
10935            return mSettings.getIntentFilterVerificationsLPr(packageName);
10936        }
10937    }
10938
10939    @Override
10940    public List<IntentFilter> getAllIntentFilters(String packageName) {
10941        if (TextUtils.isEmpty(packageName)) {
10942            return Collections.<IntentFilter>emptyList();
10943        }
10944        synchronized (mPackages) {
10945            PackageParser.Package pkg = mPackages.get(packageName);
10946            if (pkg == null || pkg.activities == null) {
10947                return Collections.<IntentFilter>emptyList();
10948            }
10949            final int count = pkg.activities.size();
10950            ArrayList<IntentFilter> result = new ArrayList<>();
10951            for (int n=0; n<count; n++) {
10952                PackageParser.Activity activity = pkg.activities.get(n);
10953                if (activity.intents != null && activity.intents.size() > 0) {
10954                    result.addAll(activity.intents);
10955                }
10956            }
10957            return result;
10958        }
10959    }
10960
10961    @Override
10962    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10963        mContext.enforceCallingOrSelfPermission(
10964                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10965
10966        synchronized (mPackages) {
10967            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10968            if (packageName != null) {
10969                result |= updateIntentVerificationStatus(packageName,
10970                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10971                        userId);
10972                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10973                        packageName, userId);
10974            }
10975            return result;
10976        }
10977    }
10978
10979    @Override
10980    public String getDefaultBrowserPackageName(int userId) {
10981        synchronized (mPackages) {
10982            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10983        }
10984    }
10985
10986    /**
10987     * Get the "allow unknown sources" setting.
10988     *
10989     * @return the current "allow unknown sources" setting
10990     */
10991    private int getUnknownSourcesSettings() {
10992        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10993                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10994                -1);
10995    }
10996
10997    @Override
10998    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10999        final int uid = Binder.getCallingUid();
11000        // writer
11001        synchronized (mPackages) {
11002            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11003            if (targetPackageSetting == null) {
11004                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11005            }
11006
11007            PackageSetting installerPackageSetting;
11008            if (installerPackageName != null) {
11009                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11010                if (installerPackageSetting == null) {
11011                    throw new IllegalArgumentException("Unknown installer package: "
11012                            + installerPackageName);
11013                }
11014            } else {
11015                installerPackageSetting = null;
11016            }
11017
11018            Signature[] callerSignature;
11019            Object obj = mSettings.getUserIdLPr(uid);
11020            if (obj != null) {
11021                if (obj instanceof SharedUserSetting) {
11022                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11023                } else if (obj instanceof PackageSetting) {
11024                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11025                } else {
11026                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11027                }
11028            } else {
11029                throw new SecurityException("Unknown calling UID: " + uid);
11030            }
11031
11032            // Verify: can't set installerPackageName to a package that is
11033            // not signed with the same cert as the caller.
11034            if (installerPackageSetting != null) {
11035                if (compareSignatures(callerSignature,
11036                        installerPackageSetting.signatures.mSignatures)
11037                        != PackageManager.SIGNATURE_MATCH) {
11038                    throw new SecurityException(
11039                            "Caller does not have same cert as new installer package "
11040                            + installerPackageName);
11041                }
11042            }
11043
11044            // Verify: if target already has an installer package, it must
11045            // be signed with the same cert as the caller.
11046            if (targetPackageSetting.installerPackageName != null) {
11047                PackageSetting setting = mSettings.mPackages.get(
11048                        targetPackageSetting.installerPackageName);
11049                // If the currently set package isn't valid, then it's always
11050                // okay to change it.
11051                if (setting != null) {
11052                    if (compareSignatures(callerSignature,
11053                            setting.signatures.mSignatures)
11054                            != PackageManager.SIGNATURE_MATCH) {
11055                        throw new SecurityException(
11056                                "Caller does not have same cert as old installer package "
11057                                + targetPackageSetting.installerPackageName);
11058                    }
11059                }
11060            }
11061
11062            // Okay!
11063            targetPackageSetting.installerPackageName = installerPackageName;
11064            scheduleWriteSettingsLocked();
11065        }
11066    }
11067
11068    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11069        // Queue up an async operation since the package installation may take a little while.
11070        mHandler.post(new Runnable() {
11071            public void run() {
11072                mHandler.removeCallbacks(this);
11073                 // Result object to be returned
11074                PackageInstalledInfo res = new PackageInstalledInfo();
11075                res.returnCode = currentStatus;
11076                res.uid = -1;
11077                res.pkg = null;
11078                res.removedInfo = new PackageRemovedInfo();
11079                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11080                    args.doPreInstall(res.returnCode);
11081                    synchronized (mInstallLock) {
11082                        installPackageTracedLI(args, res);
11083                    }
11084                    args.doPostInstall(res.returnCode, res.uid);
11085                }
11086
11087                // A restore should be performed at this point if (a) the install
11088                // succeeded, (b) the operation is not an update, and (c) the new
11089                // package has not opted out of backup participation.
11090                final boolean update = res.removedInfo.removedPackage != null;
11091                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11092                boolean doRestore = !update
11093                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11094
11095                // Set up the post-install work request bookkeeping.  This will be used
11096                // and cleaned up by the post-install event handling regardless of whether
11097                // there's a restore pass performed.  Token values are >= 1.
11098                int token;
11099                if (mNextInstallToken < 0) mNextInstallToken = 1;
11100                token = mNextInstallToken++;
11101
11102                PostInstallData data = new PostInstallData(args, res);
11103                mRunningInstalls.put(token, data);
11104                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11105
11106                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11107                    // Pass responsibility to the Backup Manager.  It will perform a
11108                    // restore if appropriate, then pass responsibility back to the
11109                    // Package Manager to run the post-install observer callbacks
11110                    // and broadcasts.
11111                    IBackupManager bm = IBackupManager.Stub.asInterface(
11112                            ServiceManager.getService(Context.BACKUP_SERVICE));
11113                    if (bm != null) {
11114                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11115                                + " to BM for possible restore");
11116                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11117                        try {
11118                            // TODO: http://b/22388012
11119                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11120                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11121                            } else {
11122                                doRestore = false;
11123                            }
11124                        } catch (RemoteException e) {
11125                            // can't happen; the backup manager is local
11126                        } catch (Exception e) {
11127                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11128                            doRestore = false;
11129                        }
11130                    } else {
11131                        Slog.e(TAG, "Backup Manager not found!");
11132                        doRestore = false;
11133                    }
11134                }
11135
11136                if (!doRestore) {
11137                    // No restore possible, or the Backup Manager was mysteriously not
11138                    // available -- just fire the post-install work request directly.
11139                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11140
11141                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11142
11143                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11144                    mHandler.sendMessage(msg);
11145                }
11146            }
11147        });
11148    }
11149
11150    private abstract class HandlerParams {
11151        private static final int MAX_RETRIES = 4;
11152
11153        /**
11154         * Number of times startCopy() has been attempted and had a non-fatal
11155         * error.
11156         */
11157        private int mRetries = 0;
11158
11159        /** User handle for the user requesting the information or installation. */
11160        private final UserHandle mUser;
11161        String traceMethod;
11162        int traceCookie;
11163
11164        HandlerParams(UserHandle user) {
11165            mUser = user;
11166        }
11167
11168        UserHandle getUser() {
11169            return mUser;
11170        }
11171
11172        HandlerParams setTraceMethod(String traceMethod) {
11173            this.traceMethod = traceMethod;
11174            return this;
11175        }
11176
11177        HandlerParams setTraceCookie(int traceCookie) {
11178            this.traceCookie = traceCookie;
11179            return this;
11180        }
11181
11182        final boolean startCopy() {
11183            boolean res;
11184            try {
11185                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11186
11187                if (++mRetries > MAX_RETRIES) {
11188                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11189                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11190                    handleServiceError();
11191                    return false;
11192                } else {
11193                    handleStartCopy();
11194                    res = true;
11195                }
11196            } catch (RemoteException e) {
11197                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11198                mHandler.sendEmptyMessage(MCS_RECONNECT);
11199                res = false;
11200            }
11201            handleReturnCode();
11202            return res;
11203        }
11204
11205        final void serviceError() {
11206            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11207            handleServiceError();
11208            handleReturnCode();
11209        }
11210
11211        abstract void handleStartCopy() throws RemoteException;
11212        abstract void handleServiceError();
11213        abstract void handleReturnCode();
11214    }
11215
11216    class MeasureParams extends HandlerParams {
11217        private final PackageStats mStats;
11218        private boolean mSuccess;
11219
11220        private final IPackageStatsObserver mObserver;
11221
11222        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11223            super(new UserHandle(stats.userHandle));
11224            mObserver = observer;
11225            mStats = stats;
11226        }
11227
11228        @Override
11229        public String toString() {
11230            return "MeasureParams{"
11231                + Integer.toHexString(System.identityHashCode(this))
11232                + " " + mStats.packageName + "}";
11233        }
11234
11235        @Override
11236        void handleStartCopy() throws RemoteException {
11237            synchronized (mInstallLock) {
11238                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11239            }
11240
11241            if (mSuccess) {
11242                final boolean mounted;
11243                if (Environment.isExternalStorageEmulated()) {
11244                    mounted = true;
11245                } else {
11246                    final String status = Environment.getExternalStorageState();
11247                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11248                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11249                }
11250
11251                if (mounted) {
11252                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11253
11254                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11255                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11256
11257                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11258                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11259
11260                    // Always subtract cache size, since it's a subdirectory
11261                    mStats.externalDataSize -= mStats.externalCacheSize;
11262
11263                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11264                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11265
11266                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11267                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11268                }
11269            }
11270        }
11271
11272        @Override
11273        void handleReturnCode() {
11274            if (mObserver != null) {
11275                try {
11276                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11277                } catch (RemoteException e) {
11278                    Slog.i(TAG, "Observer no longer exists.");
11279                }
11280            }
11281        }
11282
11283        @Override
11284        void handleServiceError() {
11285            Slog.e(TAG, "Could not measure application " + mStats.packageName
11286                            + " external storage");
11287        }
11288    }
11289
11290    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11291            throws RemoteException {
11292        long result = 0;
11293        for (File path : paths) {
11294            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11295        }
11296        return result;
11297    }
11298
11299    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11300        for (File path : paths) {
11301            try {
11302                mcs.clearDirectory(path.getAbsolutePath());
11303            } catch (RemoteException e) {
11304            }
11305        }
11306    }
11307
11308    static class OriginInfo {
11309        /**
11310         * Location where install is coming from, before it has been
11311         * copied/renamed into place. This could be a single monolithic APK
11312         * file, or a cluster directory. This location may be untrusted.
11313         */
11314        final File file;
11315        final String cid;
11316
11317        /**
11318         * Flag indicating that {@link #file} or {@link #cid} has already been
11319         * staged, meaning downstream users don't need to defensively copy the
11320         * contents.
11321         */
11322        final boolean staged;
11323
11324        /**
11325         * Flag indicating that {@link #file} or {@link #cid} is an already
11326         * installed app that is being moved.
11327         */
11328        final boolean existing;
11329
11330        final String resolvedPath;
11331        final File resolvedFile;
11332
11333        static OriginInfo fromNothing() {
11334            return new OriginInfo(null, null, false, false);
11335        }
11336
11337        static OriginInfo fromUntrustedFile(File file) {
11338            return new OriginInfo(file, null, false, false);
11339        }
11340
11341        static OriginInfo fromExistingFile(File file) {
11342            return new OriginInfo(file, null, false, true);
11343        }
11344
11345        static OriginInfo fromStagedFile(File file) {
11346            return new OriginInfo(file, null, true, false);
11347        }
11348
11349        static OriginInfo fromStagedContainer(String cid) {
11350            return new OriginInfo(null, cid, true, false);
11351        }
11352
11353        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11354            this.file = file;
11355            this.cid = cid;
11356            this.staged = staged;
11357            this.existing = existing;
11358
11359            if (cid != null) {
11360                resolvedPath = PackageHelper.getSdDir(cid);
11361                resolvedFile = new File(resolvedPath);
11362            } else if (file != null) {
11363                resolvedPath = file.getAbsolutePath();
11364                resolvedFile = file;
11365            } else {
11366                resolvedPath = null;
11367                resolvedFile = null;
11368            }
11369        }
11370    }
11371
11372    static class MoveInfo {
11373        final int moveId;
11374        final String fromUuid;
11375        final String toUuid;
11376        final String packageName;
11377        final String dataAppName;
11378        final int appId;
11379        final String seinfo;
11380        final int targetSdkVersion;
11381
11382        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11383                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11384            this.moveId = moveId;
11385            this.fromUuid = fromUuid;
11386            this.toUuid = toUuid;
11387            this.packageName = packageName;
11388            this.dataAppName = dataAppName;
11389            this.appId = appId;
11390            this.seinfo = seinfo;
11391            this.targetSdkVersion = targetSdkVersion;
11392        }
11393    }
11394
11395    class InstallParams extends HandlerParams {
11396        final OriginInfo origin;
11397        final MoveInfo move;
11398        final IPackageInstallObserver2 observer;
11399        int installFlags;
11400        final String installerPackageName;
11401        final String volumeUuid;
11402        final VerificationParams verificationParams;
11403        private InstallArgs mArgs;
11404        private int mRet;
11405        final String packageAbiOverride;
11406        final String[] grantedRuntimePermissions;
11407
11408        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11409                int installFlags, String installerPackageName, String volumeUuid,
11410                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11411                String[] grantedPermissions) {
11412            super(user);
11413            this.origin = origin;
11414            this.move = move;
11415            this.observer = observer;
11416            this.installFlags = installFlags;
11417            this.installerPackageName = installerPackageName;
11418            this.volumeUuid = volumeUuid;
11419            this.verificationParams = verificationParams;
11420            this.packageAbiOverride = packageAbiOverride;
11421            this.grantedRuntimePermissions = grantedPermissions;
11422        }
11423
11424        @Override
11425        public String toString() {
11426            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11427                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11428        }
11429
11430        private int installLocationPolicy(PackageInfoLite pkgLite) {
11431            String packageName = pkgLite.packageName;
11432            int installLocation = pkgLite.installLocation;
11433            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11434            // reader
11435            synchronized (mPackages) {
11436                PackageParser.Package pkg = mPackages.get(packageName);
11437                if (pkg != null) {
11438                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11439                        // Check for downgrading.
11440                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11441                            try {
11442                                checkDowngrade(pkg, pkgLite);
11443                            } catch (PackageManagerException e) {
11444                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11445                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11446                            }
11447                        }
11448                        // Check for updated system application.
11449                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11450                            if (onSd) {
11451                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11452                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11453                            }
11454                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11455                        } else {
11456                            if (onSd) {
11457                                // Install flag overrides everything.
11458                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11459                            }
11460                            // If current upgrade specifies particular preference
11461                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11462                                // Application explicitly specified internal.
11463                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11464                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11465                                // App explictly prefers external. Let policy decide
11466                            } else {
11467                                // Prefer previous location
11468                                if (isExternal(pkg)) {
11469                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11470                                }
11471                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11472                            }
11473                        }
11474                    } else {
11475                        // Invalid install. Return error code
11476                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11477                    }
11478                }
11479            }
11480            // All the special cases have been taken care of.
11481            // Return result based on recommended install location.
11482            if (onSd) {
11483                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11484            }
11485            return pkgLite.recommendedInstallLocation;
11486        }
11487
11488        /*
11489         * Invoke remote method to get package information and install
11490         * location values. Override install location based on default
11491         * policy if needed and then create install arguments based
11492         * on the install location.
11493         */
11494        public void handleStartCopy() throws RemoteException {
11495            int ret = PackageManager.INSTALL_SUCCEEDED;
11496
11497            // If we're already staged, we've firmly committed to an install location
11498            if (origin.staged) {
11499                if (origin.file != null) {
11500                    installFlags |= PackageManager.INSTALL_INTERNAL;
11501                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11502                } else if (origin.cid != null) {
11503                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11504                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11505                } else {
11506                    throw new IllegalStateException("Invalid stage location");
11507                }
11508            }
11509
11510            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11511            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11512            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11513            PackageInfoLite pkgLite = null;
11514
11515            if (onInt && onSd) {
11516                // Check if both bits are set.
11517                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11518                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11519            } else if (onSd && ephemeral) {
11520                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11521                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11522            } else {
11523                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11524                        packageAbiOverride);
11525
11526                if (DEBUG_EPHEMERAL && ephemeral) {
11527                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11528                }
11529
11530                /*
11531                 * If we have too little free space, try to free cache
11532                 * before giving up.
11533                 */
11534                if (!origin.staged && pkgLite.recommendedInstallLocation
11535                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11536                    // TODO: focus freeing disk space on the target device
11537                    final StorageManager storage = StorageManager.from(mContext);
11538                    final long lowThreshold = storage.getStorageLowBytes(
11539                            Environment.getDataDirectory());
11540
11541                    final long sizeBytes = mContainerService.calculateInstalledSize(
11542                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11543
11544                    try {
11545                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11546                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11547                                installFlags, packageAbiOverride);
11548                    } catch (InstallerException e) {
11549                        Slog.w(TAG, "Failed to free cache", e);
11550                    }
11551
11552                    /*
11553                     * The cache free must have deleted the file we
11554                     * downloaded to install.
11555                     *
11556                     * TODO: fix the "freeCache" call to not delete
11557                     *       the file we care about.
11558                     */
11559                    if (pkgLite.recommendedInstallLocation
11560                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11561                        pkgLite.recommendedInstallLocation
11562                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11563                    }
11564                }
11565            }
11566
11567            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11568                int loc = pkgLite.recommendedInstallLocation;
11569                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11570                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11571                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11572                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11573                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11574                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11575                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11576                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11577                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11578                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11579                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11580                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11581                } else {
11582                    // Override with defaults if needed.
11583                    loc = installLocationPolicy(pkgLite);
11584                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11585                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11586                    } else if (!onSd && !onInt) {
11587                        // Override install location with flags
11588                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11589                            // Set the flag to install on external media.
11590                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11591                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11592                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11593                            if (DEBUG_EPHEMERAL) {
11594                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11595                            }
11596                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11597                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11598                                    |PackageManager.INSTALL_INTERNAL);
11599                        } else {
11600                            // Make sure the flag for installing on external
11601                            // media is unset
11602                            installFlags |= PackageManager.INSTALL_INTERNAL;
11603                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11604                        }
11605                    }
11606                }
11607            }
11608
11609            final InstallArgs args = createInstallArgs(this);
11610            mArgs = args;
11611
11612            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11613                // TODO: http://b/22976637
11614                // Apps installed for "all" users use the device owner to verify the app
11615                UserHandle verifierUser = getUser();
11616                if (verifierUser == UserHandle.ALL) {
11617                    verifierUser = UserHandle.SYSTEM;
11618                }
11619
11620                /*
11621                 * Determine if we have any installed package verifiers. If we
11622                 * do, then we'll defer to them to verify the packages.
11623                 */
11624                final int requiredUid = mRequiredVerifierPackage == null ? -1
11625                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11626                                verifierUser.getIdentifier());
11627                if (!origin.existing && requiredUid != -1
11628                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11629                    final Intent verification = new Intent(
11630                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11631                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11632                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11633                            PACKAGE_MIME_TYPE);
11634                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11635
11636                    // Query all live verifiers based on current user state
11637                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11638                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11639
11640                    if (DEBUG_VERIFY) {
11641                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11642                                + verification.toString() + " with " + pkgLite.verifiers.length
11643                                + " optional verifiers");
11644                    }
11645
11646                    final int verificationId = mPendingVerificationToken++;
11647
11648                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11649
11650                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11651                            installerPackageName);
11652
11653                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11654                            installFlags);
11655
11656                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11657                            pkgLite.packageName);
11658
11659                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11660                            pkgLite.versionCode);
11661
11662                    if (verificationParams != null) {
11663                        if (verificationParams.getVerificationURI() != null) {
11664                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11665                                 verificationParams.getVerificationURI());
11666                        }
11667                        if (verificationParams.getOriginatingURI() != null) {
11668                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11669                                  verificationParams.getOriginatingURI());
11670                        }
11671                        if (verificationParams.getReferrer() != null) {
11672                            verification.putExtra(Intent.EXTRA_REFERRER,
11673                                  verificationParams.getReferrer());
11674                        }
11675                        if (verificationParams.getOriginatingUid() >= 0) {
11676                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11677                                  verificationParams.getOriginatingUid());
11678                        }
11679                        if (verificationParams.getInstallerUid() >= 0) {
11680                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11681                                  verificationParams.getInstallerUid());
11682                        }
11683                    }
11684
11685                    final PackageVerificationState verificationState = new PackageVerificationState(
11686                            requiredUid, args);
11687
11688                    mPendingVerification.append(verificationId, verificationState);
11689
11690                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11691                            receivers, verificationState);
11692
11693                    /*
11694                     * If any sufficient verifiers were listed in the package
11695                     * manifest, attempt to ask them.
11696                     */
11697                    if (sufficientVerifiers != null) {
11698                        final int N = sufficientVerifiers.size();
11699                        if (N == 0) {
11700                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11701                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11702                        } else {
11703                            for (int i = 0; i < N; i++) {
11704                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11705
11706                                final Intent sufficientIntent = new Intent(verification);
11707                                sufficientIntent.setComponent(verifierComponent);
11708                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11709                            }
11710                        }
11711                    }
11712
11713                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11714                            mRequiredVerifierPackage, receivers);
11715                    if (ret == PackageManager.INSTALL_SUCCEEDED
11716                            && mRequiredVerifierPackage != null) {
11717                        Trace.asyncTraceBegin(
11718                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11719                        /*
11720                         * Send the intent to the required verification agent,
11721                         * but only start the verification timeout after the
11722                         * target BroadcastReceivers have run.
11723                         */
11724                        verification.setComponent(requiredVerifierComponent);
11725                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11726                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11727                                new BroadcastReceiver() {
11728                                    @Override
11729                                    public void onReceive(Context context, Intent intent) {
11730                                        final Message msg = mHandler
11731                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11732                                        msg.arg1 = verificationId;
11733                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11734                                    }
11735                                }, null, 0, null, null);
11736
11737                        /*
11738                         * We don't want the copy to proceed until verification
11739                         * succeeds, so null out this field.
11740                         */
11741                        mArgs = null;
11742                    }
11743                } else {
11744                    /*
11745                     * No package verification is enabled, so immediately start
11746                     * the remote call to initiate copy using temporary file.
11747                     */
11748                    ret = args.copyApk(mContainerService, true);
11749                }
11750            }
11751
11752            mRet = ret;
11753        }
11754
11755        @Override
11756        void handleReturnCode() {
11757            // If mArgs is null, then MCS couldn't be reached. When it
11758            // reconnects, it will try again to install. At that point, this
11759            // will succeed.
11760            if (mArgs != null) {
11761                processPendingInstall(mArgs, mRet);
11762            }
11763        }
11764
11765        @Override
11766        void handleServiceError() {
11767            mArgs = createInstallArgs(this);
11768            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11769        }
11770
11771        public boolean isForwardLocked() {
11772            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11773        }
11774    }
11775
11776    /**
11777     * Used during creation of InstallArgs
11778     *
11779     * @param installFlags package installation flags
11780     * @return true if should be installed on external storage
11781     */
11782    private static boolean installOnExternalAsec(int installFlags) {
11783        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11784            return false;
11785        }
11786        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11787            return true;
11788        }
11789        return false;
11790    }
11791
11792    /**
11793     * Used during creation of InstallArgs
11794     *
11795     * @param installFlags package installation flags
11796     * @return true if should be installed as forward locked
11797     */
11798    private static boolean installForwardLocked(int installFlags) {
11799        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11800    }
11801
11802    private InstallArgs createInstallArgs(InstallParams params) {
11803        if (params.move != null) {
11804            return new MoveInstallArgs(params);
11805        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11806            return new AsecInstallArgs(params);
11807        } else {
11808            return new FileInstallArgs(params);
11809        }
11810    }
11811
11812    /**
11813     * Create args that describe an existing installed package. Typically used
11814     * when cleaning up old installs, or used as a move source.
11815     */
11816    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11817            String resourcePath, String[] instructionSets) {
11818        final boolean isInAsec;
11819        if (installOnExternalAsec(installFlags)) {
11820            /* Apps on SD card are always in ASEC containers. */
11821            isInAsec = true;
11822        } else if (installForwardLocked(installFlags)
11823                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11824            /*
11825             * Forward-locked apps are only in ASEC containers if they're the
11826             * new style
11827             */
11828            isInAsec = true;
11829        } else {
11830            isInAsec = false;
11831        }
11832
11833        if (isInAsec) {
11834            return new AsecInstallArgs(codePath, instructionSets,
11835                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11836        } else {
11837            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11838        }
11839    }
11840
11841    static abstract class InstallArgs {
11842        /** @see InstallParams#origin */
11843        final OriginInfo origin;
11844        /** @see InstallParams#move */
11845        final MoveInfo move;
11846
11847        final IPackageInstallObserver2 observer;
11848        // Always refers to PackageManager flags only
11849        final int installFlags;
11850        final String installerPackageName;
11851        final String volumeUuid;
11852        final UserHandle user;
11853        final String abiOverride;
11854        final String[] installGrantPermissions;
11855        /** If non-null, drop an async trace when the install completes */
11856        final String traceMethod;
11857        final int traceCookie;
11858
11859        // The list of instruction sets supported by this app. This is currently
11860        // only used during the rmdex() phase to clean up resources. We can get rid of this
11861        // if we move dex files under the common app path.
11862        /* nullable */ String[] instructionSets;
11863
11864        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11865                int installFlags, String installerPackageName, String volumeUuid,
11866                UserHandle user, String[] instructionSets,
11867                String abiOverride, String[] installGrantPermissions,
11868                String traceMethod, int traceCookie) {
11869            this.origin = origin;
11870            this.move = move;
11871            this.installFlags = installFlags;
11872            this.observer = observer;
11873            this.installerPackageName = installerPackageName;
11874            this.volumeUuid = volumeUuid;
11875            this.user = user;
11876            this.instructionSets = instructionSets;
11877            this.abiOverride = abiOverride;
11878            this.installGrantPermissions = installGrantPermissions;
11879            this.traceMethod = traceMethod;
11880            this.traceCookie = traceCookie;
11881        }
11882
11883        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11884        abstract int doPreInstall(int status);
11885
11886        /**
11887         * Rename package into final resting place. All paths on the given
11888         * scanned package should be updated to reflect the rename.
11889         */
11890        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11891        abstract int doPostInstall(int status, int uid);
11892
11893        /** @see PackageSettingBase#codePathString */
11894        abstract String getCodePath();
11895        /** @see PackageSettingBase#resourcePathString */
11896        abstract String getResourcePath();
11897
11898        // Need installer lock especially for dex file removal.
11899        abstract void cleanUpResourcesLI();
11900        abstract boolean doPostDeleteLI(boolean delete);
11901
11902        /**
11903         * Called before the source arguments are copied. This is used mostly
11904         * for MoveParams when it needs to read the source file to put it in the
11905         * destination.
11906         */
11907        int doPreCopy() {
11908            return PackageManager.INSTALL_SUCCEEDED;
11909        }
11910
11911        /**
11912         * Called after the source arguments are copied. This is used mostly for
11913         * MoveParams when it needs to read the source file to put it in the
11914         * destination.
11915         *
11916         * @return
11917         */
11918        int doPostCopy(int uid) {
11919            return PackageManager.INSTALL_SUCCEEDED;
11920        }
11921
11922        protected boolean isFwdLocked() {
11923            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11924        }
11925
11926        protected boolean isExternalAsec() {
11927            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11928        }
11929
11930        protected boolean isEphemeral() {
11931            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11932        }
11933
11934        UserHandle getUser() {
11935            return user;
11936        }
11937    }
11938
11939    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11940        if (!allCodePaths.isEmpty()) {
11941            if (instructionSets == null) {
11942                throw new IllegalStateException("instructionSet == null");
11943            }
11944            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11945            for (String codePath : allCodePaths) {
11946                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11947                    try {
11948                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11949                    } catch (InstallerException ignored) {
11950                    }
11951                }
11952            }
11953        }
11954    }
11955
11956    /**
11957     * Logic to handle installation of non-ASEC applications, including copying
11958     * and renaming logic.
11959     */
11960    class FileInstallArgs extends InstallArgs {
11961        private File codeFile;
11962        private File resourceFile;
11963
11964        // Example topology:
11965        // /data/app/com.example/base.apk
11966        // /data/app/com.example/split_foo.apk
11967        // /data/app/com.example/lib/arm/libfoo.so
11968        // /data/app/com.example/lib/arm64/libfoo.so
11969        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11970
11971        /** New install */
11972        FileInstallArgs(InstallParams params) {
11973            super(params.origin, params.move, params.observer, params.installFlags,
11974                    params.installerPackageName, params.volumeUuid,
11975                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11976                    params.grantedRuntimePermissions,
11977                    params.traceMethod, params.traceCookie);
11978            if (isFwdLocked()) {
11979                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11980            }
11981        }
11982
11983        /** Existing install */
11984        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11985            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11986                    null, null, null, 0);
11987            this.codeFile = (codePath != null) ? new File(codePath) : null;
11988            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11989        }
11990
11991        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11992            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11993            try {
11994                return doCopyApk(imcs, temp);
11995            } finally {
11996                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11997            }
11998        }
11999
12000        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12001            if (origin.staged) {
12002                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12003                codeFile = origin.file;
12004                resourceFile = origin.file;
12005                return PackageManager.INSTALL_SUCCEEDED;
12006            }
12007
12008            try {
12009                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12010                final File tempDir =
12011                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12012                codeFile = tempDir;
12013                resourceFile = tempDir;
12014            } catch (IOException e) {
12015                Slog.w(TAG, "Failed to create copy file: " + e);
12016                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12017            }
12018
12019            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12020                @Override
12021                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12022                    if (!FileUtils.isValidExtFilename(name)) {
12023                        throw new IllegalArgumentException("Invalid filename: " + name);
12024                    }
12025                    try {
12026                        final File file = new File(codeFile, name);
12027                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12028                                O_RDWR | O_CREAT, 0644);
12029                        Os.chmod(file.getAbsolutePath(), 0644);
12030                        return new ParcelFileDescriptor(fd);
12031                    } catch (ErrnoException e) {
12032                        throw new RemoteException("Failed to open: " + e.getMessage());
12033                    }
12034                }
12035            };
12036
12037            int ret = PackageManager.INSTALL_SUCCEEDED;
12038            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12039            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12040                Slog.e(TAG, "Failed to copy package");
12041                return ret;
12042            }
12043
12044            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12045            NativeLibraryHelper.Handle handle = null;
12046            try {
12047                handle = NativeLibraryHelper.Handle.create(codeFile);
12048                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12049                        abiOverride);
12050            } catch (IOException e) {
12051                Slog.e(TAG, "Copying native libraries failed", e);
12052                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12053            } finally {
12054                IoUtils.closeQuietly(handle);
12055            }
12056
12057            return ret;
12058        }
12059
12060        int doPreInstall(int status) {
12061            if (status != PackageManager.INSTALL_SUCCEEDED) {
12062                cleanUp();
12063            }
12064            return status;
12065        }
12066
12067        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12068            if (status != PackageManager.INSTALL_SUCCEEDED) {
12069                cleanUp();
12070                return false;
12071            }
12072
12073            final File targetDir = codeFile.getParentFile();
12074            final File beforeCodeFile = codeFile;
12075            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12076
12077            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12078            try {
12079                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12080            } catch (ErrnoException e) {
12081                Slog.w(TAG, "Failed to rename", e);
12082                return false;
12083            }
12084
12085            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12086                Slog.w(TAG, "Failed to restorecon");
12087                return false;
12088            }
12089
12090            // Reflect the rename internally
12091            codeFile = afterCodeFile;
12092            resourceFile = afterCodeFile;
12093
12094            // Reflect the rename in scanned details
12095            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12096            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12097                    afterCodeFile, pkg.baseCodePath));
12098            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12099                    afterCodeFile, pkg.splitCodePaths));
12100
12101            // Reflect the rename in app info
12102            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12103            pkg.setApplicationInfoCodePath(pkg.codePath);
12104            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12105            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12106            pkg.setApplicationInfoResourcePath(pkg.codePath);
12107            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12108            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12109
12110            return true;
12111        }
12112
12113        int doPostInstall(int status, int uid) {
12114            if (status != PackageManager.INSTALL_SUCCEEDED) {
12115                cleanUp();
12116            }
12117            return status;
12118        }
12119
12120        @Override
12121        String getCodePath() {
12122            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12123        }
12124
12125        @Override
12126        String getResourcePath() {
12127            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12128        }
12129
12130        private boolean cleanUp() {
12131            if (codeFile == null || !codeFile.exists()) {
12132                return false;
12133            }
12134
12135            removeCodePathLI(codeFile);
12136
12137            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12138                resourceFile.delete();
12139            }
12140
12141            return true;
12142        }
12143
12144        void cleanUpResourcesLI() {
12145            // Try enumerating all code paths before deleting
12146            List<String> allCodePaths = Collections.EMPTY_LIST;
12147            if (codeFile != null && codeFile.exists()) {
12148                try {
12149                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12150                    allCodePaths = pkg.getAllCodePaths();
12151                } catch (PackageParserException e) {
12152                    // Ignored; we tried our best
12153                }
12154            }
12155
12156            cleanUp();
12157            removeDexFiles(allCodePaths, instructionSets);
12158        }
12159
12160        boolean doPostDeleteLI(boolean delete) {
12161            // XXX err, shouldn't we respect the delete flag?
12162            cleanUpResourcesLI();
12163            return true;
12164        }
12165    }
12166
12167    private boolean isAsecExternal(String cid) {
12168        final String asecPath = PackageHelper.getSdFilesystem(cid);
12169        return !asecPath.startsWith(mAsecInternalPath);
12170    }
12171
12172    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12173            PackageManagerException {
12174        if (copyRet < 0) {
12175            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12176                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12177                throw new PackageManagerException(copyRet, message);
12178            }
12179        }
12180    }
12181
12182    /**
12183     * Extract the MountService "container ID" from the full code path of an
12184     * .apk.
12185     */
12186    static String cidFromCodePath(String fullCodePath) {
12187        int eidx = fullCodePath.lastIndexOf("/");
12188        String subStr1 = fullCodePath.substring(0, eidx);
12189        int sidx = subStr1.lastIndexOf("/");
12190        return subStr1.substring(sidx+1, eidx);
12191    }
12192
12193    /**
12194     * Logic to handle installation of ASEC applications, including copying and
12195     * renaming logic.
12196     */
12197    class AsecInstallArgs extends InstallArgs {
12198        static final String RES_FILE_NAME = "pkg.apk";
12199        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12200
12201        String cid;
12202        String packagePath;
12203        String resourcePath;
12204
12205        /** New install */
12206        AsecInstallArgs(InstallParams params) {
12207            super(params.origin, params.move, params.observer, params.installFlags,
12208                    params.installerPackageName, params.volumeUuid,
12209                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12210                    params.grantedRuntimePermissions,
12211                    params.traceMethod, params.traceCookie);
12212        }
12213
12214        /** Existing install */
12215        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12216                        boolean isExternal, boolean isForwardLocked) {
12217            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12218                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12219                    instructionSets, null, null, null, 0);
12220            // Hackily pretend we're still looking at a full code path
12221            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12222                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12223            }
12224
12225            // Extract cid from fullCodePath
12226            int eidx = fullCodePath.lastIndexOf("/");
12227            String subStr1 = fullCodePath.substring(0, eidx);
12228            int sidx = subStr1.lastIndexOf("/");
12229            cid = subStr1.substring(sidx+1, eidx);
12230            setMountPath(subStr1);
12231        }
12232
12233        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12234            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12235                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12236                    instructionSets, null, null, null, 0);
12237            this.cid = cid;
12238            setMountPath(PackageHelper.getSdDir(cid));
12239        }
12240
12241        void createCopyFile() {
12242            cid = mInstallerService.allocateExternalStageCidLegacy();
12243        }
12244
12245        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12246            if (origin.staged && origin.cid != null) {
12247                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12248                cid = origin.cid;
12249                setMountPath(PackageHelper.getSdDir(cid));
12250                return PackageManager.INSTALL_SUCCEEDED;
12251            }
12252
12253            if (temp) {
12254                createCopyFile();
12255            } else {
12256                /*
12257                 * Pre-emptively destroy the container since it's destroyed if
12258                 * copying fails due to it existing anyway.
12259                 */
12260                PackageHelper.destroySdDir(cid);
12261            }
12262
12263            final String newMountPath = imcs.copyPackageToContainer(
12264                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12265                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12266
12267            if (newMountPath != null) {
12268                setMountPath(newMountPath);
12269                return PackageManager.INSTALL_SUCCEEDED;
12270            } else {
12271                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12272            }
12273        }
12274
12275        @Override
12276        String getCodePath() {
12277            return packagePath;
12278        }
12279
12280        @Override
12281        String getResourcePath() {
12282            return resourcePath;
12283        }
12284
12285        int doPreInstall(int status) {
12286            if (status != PackageManager.INSTALL_SUCCEEDED) {
12287                // Destroy container
12288                PackageHelper.destroySdDir(cid);
12289            } else {
12290                boolean mounted = PackageHelper.isContainerMounted(cid);
12291                if (!mounted) {
12292                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12293                            Process.SYSTEM_UID);
12294                    if (newMountPath != null) {
12295                        setMountPath(newMountPath);
12296                    } else {
12297                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12298                    }
12299                }
12300            }
12301            return status;
12302        }
12303
12304        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12305            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12306            String newMountPath = null;
12307            if (PackageHelper.isContainerMounted(cid)) {
12308                // Unmount the container
12309                if (!PackageHelper.unMountSdDir(cid)) {
12310                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12311                    return false;
12312                }
12313            }
12314            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12315                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12316                        " which might be stale. Will try to clean up.");
12317                // Clean up the stale container and proceed to recreate.
12318                if (!PackageHelper.destroySdDir(newCacheId)) {
12319                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12320                    return false;
12321                }
12322                // Successfully cleaned up stale container. Try to rename again.
12323                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12324                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12325                            + " inspite of cleaning it up.");
12326                    return false;
12327                }
12328            }
12329            if (!PackageHelper.isContainerMounted(newCacheId)) {
12330                Slog.w(TAG, "Mounting container " + newCacheId);
12331                newMountPath = PackageHelper.mountSdDir(newCacheId,
12332                        getEncryptKey(), Process.SYSTEM_UID);
12333            } else {
12334                newMountPath = PackageHelper.getSdDir(newCacheId);
12335            }
12336            if (newMountPath == null) {
12337                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12338                return false;
12339            }
12340            Log.i(TAG, "Succesfully renamed " + cid +
12341                    " to " + newCacheId +
12342                    " at new path: " + newMountPath);
12343            cid = newCacheId;
12344
12345            final File beforeCodeFile = new File(packagePath);
12346            setMountPath(newMountPath);
12347            final File afterCodeFile = new File(packagePath);
12348
12349            // Reflect the rename in scanned details
12350            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12351            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12352                    afterCodeFile, pkg.baseCodePath));
12353            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12354                    afterCodeFile, pkg.splitCodePaths));
12355
12356            // Reflect the rename in app info
12357            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12358            pkg.setApplicationInfoCodePath(pkg.codePath);
12359            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12360            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12361            pkg.setApplicationInfoResourcePath(pkg.codePath);
12362            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12363            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12364
12365            return true;
12366        }
12367
12368        private void setMountPath(String mountPath) {
12369            final File mountFile = new File(mountPath);
12370
12371            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12372            if (monolithicFile.exists()) {
12373                packagePath = monolithicFile.getAbsolutePath();
12374                if (isFwdLocked()) {
12375                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12376                } else {
12377                    resourcePath = packagePath;
12378                }
12379            } else {
12380                packagePath = mountFile.getAbsolutePath();
12381                resourcePath = packagePath;
12382            }
12383        }
12384
12385        int doPostInstall(int status, int uid) {
12386            if (status != PackageManager.INSTALL_SUCCEEDED) {
12387                cleanUp();
12388            } else {
12389                final int groupOwner;
12390                final String protectedFile;
12391                if (isFwdLocked()) {
12392                    groupOwner = UserHandle.getSharedAppGid(uid);
12393                    protectedFile = RES_FILE_NAME;
12394                } else {
12395                    groupOwner = -1;
12396                    protectedFile = null;
12397                }
12398
12399                if (uid < Process.FIRST_APPLICATION_UID
12400                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12401                    Slog.e(TAG, "Failed to finalize " + cid);
12402                    PackageHelper.destroySdDir(cid);
12403                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12404                }
12405
12406                boolean mounted = PackageHelper.isContainerMounted(cid);
12407                if (!mounted) {
12408                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12409                }
12410            }
12411            return status;
12412        }
12413
12414        private void cleanUp() {
12415            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12416
12417            // Destroy secure container
12418            PackageHelper.destroySdDir(cid);
12419        }
12420
12421        private List<String> getAllCodePaths() {
12422            final File codeFile = new File(getCodePath());
12423            if (codeFile != null && codeFile.exists()) {
12424                try {
12425                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12426                    return pkg.getAllCodePaths();
12427                } catch (PackageParserException e) {
12428                    // Ignored; we tried our best
12429                }
12430            }
12431            return Collections.EMPTY_LIST;
12432        }
12433
12434        void cleanUpResourcesLI() {
12435            // Enumerate all code paths before deleting
12436            cleanUpResourcesLI(getAllCodePaths());
12437        }
12438
12439        private void cleanUpResourcesLI(List<String> allCodePaths) {
12440            cleanUp();
12441            removeDexFiles(allCodePaths, instructionSets);
12442        }
12443
12444        String getPackageName() {
12445            return getAsecPackageName(cid);
12446        }
12447
12448        boolean doPostDeleteLI(boolean delete) {
12449            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12450            final List<String> allCodePaths = getAllCodePaths();
12451            boolean mounted = PackageHelper.isContainerMounted(cid);
12452            if (mounted) {
12453                // Unmount first
12454                if (PackageHelper.unMountSdDir(cid)) {
12455                    mounted = false;
12456                }
12457            }
12458            if (!mounted && delete) {
12459                cleanUpResourcesLI(allCodePaths);
12460            }
12461            return !mounted;
12462        }
12463
12464        @Override
12465        int doPreCopy() {
12466            if (isFwdLocked()) {
12467                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12468                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12469                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12470                }
12471            }
12472
12473            return PackageManager.INSTALL_SUCCEEDED;
12474        }
12475
12476        @Override
12477        int doPostCopy(int uid) {
12478            if (isFwdLocked()) {
12479                if (uid < Process.FIRST_APPLICATION_UID
12480                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12481                                RES_FILE_NAME)) {
12482                    Slog.e(TAG, "Failed to finalize " + cid);
12483                    PackageHelper.destroySdDir(cid);
12484                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12485                }
12486            }
12487
12488            return PackageManager.INSTALL_SUCCEEDED;
12489        }
12490    }
12491
12492    /**
12493     * Logic to handle movement of existing installed applications.
12494     */
12495    class MoveInstallArgs extends InstallArgs {
12496        private File codeFile;
12497        private File resourceFile;
12498
12499        /** New install */
12500        MoveInstallArgs(InstallParams params) {
12501            super(params.origin, params.move, params.observer, params.installFlags,
12502                    params.installerPackageName, params.volumeUuid,
12503                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12504                    params.grantedRuntimePermissions,
12505                    params.traceMethod, params.traceCookie);
12506        }
12507
12508        int copyApk(IMediaContainerService imcs, boolean temp) {
12509            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12510                    + move.fromUuid + " to " + move.toUuid);
12511            synchronized (mInstaller) {
12512                try {
12513                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12514                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12515                } catch (InstallerException e) {
12516                    Slog.w(TAG, "Failed to move app", e);
12517                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12518                }
12519            }
12520
12521            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12522            resourceFile = codeFile;
12523            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12524
12525            return PackageManager.INSTALL_SUCCEEDED;
12526        }
12527
12528        int doPreInstall(int status) {
12529            if (status != PackageManager.INSTALL_SUCCEEDED) {
12530                cleanUp(move.toUuid);
12531            }
12532            return status;
12533        }
12534
12535        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12536            if (status != PackageManager.INSTALL_SUCCEEDED) {
12537                cleanUp(move.toUuid);
12538                return false;
12539            }
12540
12541            // Reflect the move in app info
12542            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12543            pkg.setApplicationInfoCodePath(pkg.codePath);
12544            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12545            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12546            pkg.setApplicationInfoResourcePath(pkg.codePath);
12547            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12548            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12549
12550            return true;
12551        }
12552
12553        int doPostInstall(int status, int uid) {
12554            if (status == PackageManager.INSTALL_SUCCEEDED) {
12555                cleanUp(move.fromUuid);
12556            } else {
12557                cleanUp(move.toUuid);
12558            }
12559            return status;
12560        }
12561
12562        @Override
12563        String getCodePath() {
12564            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12565        }
12566
12567        @Override
12568        String getResourcePath() {
12569            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12570        }
12571
12572        private boolean cleanUp(String volumeUuid) {
12573            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12574                    move.dataAppName);
12575            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12576            synchronized (mInstallLock) {
12577                // Clean up both app data and code
12578                removeDataDirsLI(volumeUuid, move.packageName);
12579                removeCodePathLI(codeFile);
12580            }
12581            return true;
12582        }
12583
12584        void cleanUpResourcesLI() {
12585            throw new UnsupportedOperationException();
12586        }
12587
12588        boolean doPostDeleteLI(boolean delete) {
12589            throw new UnsupportedOperationException();
12590        }
12591    }
12592
12593    static String getAsecPackageName(String packageCid) {
12594        int idx = packageCid.lastIndexOf("-");
12595        if (idx == -1) {
12596            return packageCid;
12597        }
12598        return packageCid.substring(0, idx);
12599    }
12600
12601    // Utility method used to create code paths based on package name and available index.
12602    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12603        String idxStr = "";
12604        int idx = 1;
12605        // Fall back to default value of idx=1 if prefix is not
12606        // part of oldCodePath
12607        if (oldCodePath != null) {
12608            String subStr = oldCodePath;
12609            // Drop the suffix right away
12610            if (suffix != null && subStr.endsWith(suffix)) {
12611                subStr = subStr.substring(0, subStr.length() - suffix.length());
12612            }
12613            // If oldCodePath already contains prefix find out the
12614            // ending index to either increment or decrement.
12615            int sidx = subStr.lastIndexOf(prefix);
12616            if (sidx != -1) {
12617                subStr = subStr.substring(sidx + prefix.length());
12618                if (subStr != null) {
12619                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12620                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12621                    }
12622                    try {
12623                        idx = Integer.parseInt(subStr);
12624                        if (idx <= 1) {
12625                            idx++;
12626                        } else {
12627                            idx--;
12628                        }
12629                    } catch(NumberFormatException e) {
12630                    }
12631                }
12632            }
12633        }
12634        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12635        return prefix + idxStr;
12636    }
12637
12638    private File getNextCodePath(File targetDir, String packageName) {
12639        int suffix = 1;
12640        File result;
12641        do {
12642            result = new File(targetDir, packageName + "-" + suffix);
12643            suffix++;
12644        } while (result.exists());
12645        return result;
12646    }
12647
12648    // Utility method that returns the relative package path with respect
12649    // to the installation directory. Like say for /data/data/com.test-1.apk
12650    // string com.test-1 is returned.
12651    static String deriveCodePathName(String codePath) {
12652        if (codePath == null) {
12653            return null;
12654        }
12655        final File codeFile = new File(codePath);
12656        final String name = codeFile.getName();
12657        if (codeFile.isDirectory()) {
12658            return name;
12659        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12660            final int lastDot = name.lastIndexOf('.');
12661            return name.substring(0, lastDot);
12662        } else {
12663            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12664            return null;
12665        }
12666    }
12667
12668    static class PackageInstalledInfo {
12669        String name;
12670        int uid;
12671        // The set of users that originally had this package installed.
12672        int[] origUsers;
12673        // The set of users that now have this package installed.
12674        int[] newUsers;
12675        PackageParser.Package pkg;
12676        int returnCode;
12677        String returnMsg;
12678        PackageRemovedInfo removedInfo;
12679
12680        public void setError(int code, String msg) {
12681            returnCode = code;
12682            returnMsg = msg;
12683            Slog.w(TAG, msg);
12684        }
12685
12686        public void setError(String msg, PackageParserException e) {
12687            returnCode = e.error;
12688            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12689            Slog.w(TAG, msg, e);
12690        }
12691
12692        public void setError(String msg, PackageManagerException e) {
12693            returnCode = e.error;
12694            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12695            Slog.w(TAG, msg, e);
12696        }
12697
12698        // In some error cases we want to convey more info back to the observer
12699        String origPackage;
12700        String origPermission;
12701    }
12702
12703    /*
12704     * Install a non-existing package.
12705     */
12706    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12707            UserHandle user, String installerPackageName, String volumeUuid,
12708            PackageInstalledInfo res) {
12709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12710
12711        // Remember this for later, in case we need to rollback this install
12712        String pkgName = pkg.packageName;
12713
12714        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12715
12716        synchronized(mPackages) {
12717            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12718                // A package with the same name is already installed, though
12719                // it has been renamed to an older name.  The package we
12720                // are trying to install should be installed as an update to
12721                // the existing one, but that has not been requested, so bail.
12722                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12723                        + " without first uninstalling package running as "
12724                        + mSettings.mRenamedPackages.get(pkgName));
12725                return;
12726            }
12727            if (mPackages.containsKey(pkgName)) {
12728                // Don't allow installation over an existing package with the same name.
12729                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12730                        + " without first uninstalling.");
12731                return;
12732            }
12733        }
12734
12735        try {
12736            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12737                    System.currentTimeMillis(), user);
12738
12739            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
12740
12741            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12742                prepareAppDataAfterInstall(newPackage);
12743
12744            } else {
12745                // Remove package from internal structures, but keep around any
12746                // data that might have already existed
12747                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12748                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12749            }
12750
12751        } catch (PackageManagerException e) {
12752            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12753        }
12754
12755        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12756    }
12757
12758    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12759        // Can't rotate keys during boot or if sharedUser.
12760        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12761                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12762            return false;
12763        }
12764        // app is using upgradeKeySets; make sure all are valid
12765        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12766        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12767        for (int i = 0; i < upgradeKeySets.length; i++) {
12768            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12769                Slog.wtf(TAG, "Package "
12770                         + (oldPs.name != null ? oldPs.name : "<null>")
12771                         + " contains upgrade-key-set reference to unknown key-set: "
12772                         + upgradeKeySets[i]
12773                         + " reverting to signatures check.");
12774                return false;
12775            }
12776        }
12777        return true;
12778    }
12779
12780    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12781        // Upgrade keysets are being used.  Determine if new package has a superset of the
12782        // required keys.
12783        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12784        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12785        for (int i = 0; i < upgradeKeySets.length; i++) {
12786            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12787            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12788                return true;
12789            }
12790        }
12791        return false;
12792    }
12793
12794    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12795            UserHandle user, String installerPackageName, String volumeUuid,
12796            PackageInstalledInfo res) {
12797        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12798
12799        final PackageParser.Package oldPackage;
12800        final String pkgName = pkg.packageName;
12801        final int[] allUsers;
12802        final boolean[] perUserInstalled;
12803
12804        // First find the old package info and check signatures
12805        synchronized(mPackages) {
12806            oldPackage = mPackages.get(pkgName);
12807            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12808            if (isEphemeral && !oldIsEphemeral) {
12809                // can't downgrade from full to ephemeral
12810                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12811                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12812                return;
12813            }
12814            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12815            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12816            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12817                if (!checkUpgradeKeySetLP(ps, pkg)) {
12818                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12819                            "New package not signed by keys specified by upgrade-keysets: "
12820                                    + pkgName);
12821                    return;
12822                }
12823            } else {
12824                // default to original signature matching
12825                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12826                        != PackageManager.SIGNATURE_MATCH) {
12827                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12828                            "New package has a different signature: " + pkgName);
12829                    return;
12830                }
12831            }
12832
12833            // In case of rollback, remember per-user/profile install state
12834            allUsers = sUserManager.getUserIds();
12835            perUserInstalled = new boolean[allUsers.length];
12836            for (int i = 0; i < allUsers.length; i++) {
12837                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12838            }
12839        }
12840
12841        boolean sysPkg = (isSystemApp(oldPackage));
12842        if (sysPkg) {
12843            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12844                    user, allUsers, perUserInstalled, installerPackageName, res);
12845        } else {
12846            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12847                    user, allUsers, perUserInstalled, installerPackageName, res);
12848        }
12849    }
12850
12851    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12852            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12853            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12854            PackageInstalledInfo res) {
12855        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12856                + deletedPackage);
12857
12858        String pkgName = deletedPackage.packageName;
12859        boolean deletedPkg = true;
12860        boolean addedPkg = false;
12861
12862        final long origUpdateTime = (pkg.mExtras != null)
12863                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
12864
12865        // First delete the existing package while retaining the data directory
12866        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12867                res.removedInfo, true, pkg)) {
12868            // If the existing package wasn't successfully deleted
12869            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12870            deletedPkg = false;
12871        } else {
12872            // Successfully deleted the old package; proceed with replace.
12873
12874            // If deleted package lived in a container, give users a chance to
12875            // relinquish resources before killing.
12876            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12877                if (DEBUG_INSTALL) {
12878                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12879                }
12880                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12881                final ArrayList<String> pkgList = new ArrayList<String>(1);
12882                pkgList.add(deletedPackage.applicationInfo.packageName);
12883                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12884            }
12885
12886            deleteCodeCacheDirsLI(pkg);
12887
12888            try {
12889                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12890                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12891                updateSettingsLI(newPackage, installerPackageName, allUsers,
12892                        perUserInstalled, res, user);
12893                prepareAppDataAfterInstall(newPackage);
12894                addedPkg = true;
12895            } catch (PackageManagerException e) {
12896                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12897            }
12898        }
12899
12900        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12901            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12902
12903            // Revert all internal state mutations and added folders for the failed install
12904            if (addedPkg) {
12905                deletePackageLI(pkgName, null, true, allUsers, perUserInstalled,
12906                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12907            }
12908
12909            // Restore the old package
12910            if (deletedPkg) {
12911                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12912                File restoreFile = new File(deletedPackage.codePath);
12913                // Parse old package
12914                boolean oldExternal = isExternal(deletedPackage);
12915                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12916                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12917                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12918                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12919                try {
12920                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12921                            null);
12922                } catch (PackageManagerException e) {
12923                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12924                            + e.getMessage());
12925                    return;
12926                }
12927
12928                synchronized (mPackages) {
12929                    // Ensure the installer package name up to date
12930                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
12931
12932                    // Update permissions for restored package
12933                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
12934
12935                    mSettings.writeLPr();
12936                }
12937
12938                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12939            }
12940        }
12941    }
12942
12943    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12944            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12945            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12946            PackageInstalledInfo res) {
12947        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12948                + ", old=" + deletedPackage);
12949
12950        final boolean disabledSystem;
12951
12952        // Set the system/privileged flags as needed
12953        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12954        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12955                != 0) {
12956            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12957        }
12958
12959        // Kill package processes including services, providers, etc.
12960        killPackage(deletedPackage, "replace sys pkg");
12961
12962        // Report the result for the parent package only
12963        res.removedInfo.uid = deletedPackage.applicationInfo.uid;
12964        res.removedInfo.removedPackage = deletedPackage.packageName;
12965
12966        // Remove existing system package
12967        removePackageSettingLI(deletedPackage, true);
12968
12969        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
12970        if (!disabledSystem) {
12971            // We didn't need to disable the .apk as a current system package,
12972            // which means we are replacing another update that is already
12973            // installed.  We need to make sure to delete the older one's .apk.
12974            res.removedInfo.args = createInstallArgsForExisting(0,
12975                    deletedPackage.applicationInfo.getCodePath(),
12976                    deletedPackage.applicationInfo.getResourcePath(),
12977                    getAppDexInstructionSets(deletedPackage.applicationInfo));
12978        } else {
12979            res.removedInfo.args = null;
12980        }
12981
12982        // Successfully disabled the old package. Now proceed with re-installation
12983        deleteCodeCacheDirsLI(pkg);
12984
12985        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12986        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
12987                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
12988
12989        PackageParser.Package newPackage = null;
12990        try {
12991            // Add the package to the internal data structures
12992            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12993
12994            // Set the update and install times
12995            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
12996            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
12997                    System.currentTimeMillis());
12998
12999            // Check for shared user id changes
13000            String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage);
13001            if (invalidPackageName != null) {
13002                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13003                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13004                                + " to " + invalidPackageName);
13005            }
13006
13007            // Update the package dynamic state if succeeded
13008            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13009                // Now that the install succeeded make sure we remove data
13010                // directories for any child package the update removed.
13011                final int deletedChildCount = (deletedPackage.childPackages != null)
13012                        ? deletedPackage.childPackages.size() : 0;
13013                final int newChildCount = (newPackage.childPackages != null)
13014                        ? newPackage.childPackages.size() : 0;
13015                for (int i = 0; i < deletedChildCount; i++) {
13016                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13017                    boolean childPackageDeleted = true;
13018                    for (int j = 0; j < newChildCount; j++) {
13019                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13020                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13021                            childPackageDeleted = false;
13022                            break;
13023                        }
13024                    }
13025                    if (childPackageDeleted) {
13026                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13027                                deletedChildPkg.packageName);
13028                        if (ps != null) {
13029                            removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false);
13030                        }
13031                    }
13032                }
13033
13034                updateSettingsLI(newPackage, installerPackageName, allUsers,
13035                        perUserInstalled, res, user);
13036                prepareAppDataAfterInstall(newPackage);
13037            }
13038        } catch (PackageManagerException e) {
13039            res.returnCode = INSTALL_FAILED_INTERNAL_ERROR;
13040            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13041        }
13042
13043        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13044            // Re installation failed. Restore old information
13045            // Remove new pkg information
13046            if (newPackage != null) {
13047                removeInstalledPackageLI(newPackage, true);
13048            }
13049            // Add back the old system package
13050            try {
13051                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13052            } catch (PackageManagerException e) {
13053                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13054            }
13055
13056            synchronized (mPackages) {
13057                if (disabledSystem) {
13058                    enableSystemPackageLPw(deletedPackage);
13059                }
13060
13061                // Ensure the installer package name up to date
13062                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13063
13064                // Update permissions for restored package
13065                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13066
13067                mSettings.writeLPr();
13068            }
13069
13070            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13071                    + " after failed upgrade");
13072        }
13073    }
13074
13075    /**
13076     * Checks whether the parent or any of the child packages have a change shared
13077     * user. For a package to be a valid update the shred users of the parent and
13078     * the children should match. We may later support changing child shared users.
13079     * @param oldPkg The updated package.
13080     * @param newPkg The update package.
13081     * @return The shared user that change between the versions.
13082     */
13083    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13084            PackageParser.Package newPkg) {
13085        // Check parent shared user
13086        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13087            return newPkg.packageName;
13088        }
13089        // Check child shared users
13090        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13091        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13092        for (int i = 0; i < newChildCount; i++) {
13093            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13094            // If this child was present, did it have the same shared user?
13095            for (int j = 0; j < oldChildCount; j++) {
13096                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13097                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13098                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13099                    return newChildPkg.packageName;
13100                }
13101            }
13102        }
13103        return null;
13104    }
13105
13106    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13107        // Remove the lib path for the parent package
13108        PackageSetting ps = (PackageSetting) pkg.mExtras;
13109        if (ps != null) {
13110            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13111        }
13112        // Remove the lib path for the child packages
13113        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13114        for (int i = 0; i < childCount; i++) {
13115            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13116            if (ps != null) {
13117                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13118            }
13119        }
13120    }
13121
13122    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13123        // Enable the parent package
13124        mSettings.enableSystemPackageLPw(pkg.packageName);
13125        // Enable the child packages
13126        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13127        for (int i = 0; i < childCount; i++) {
13128            PackageParser.Package childPkg = pkg.childPackages.get(i);
13129            mSettings.enableSystemPackageLPw(childPkg.packageName);
13130        }
13131    }
13132
13133    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13134            PackageParser.Package newPkg) {
13135        // Disable the parent package (parent always replaced)
13136        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13137        // Disable the child packages
13138        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13139        for (int i = 0; i < childCount; i++) {
13140            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13141            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13142            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13143        }
13144        return disabled;
13145    }
13146
13147    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13148            String installerPackageName) {
13149        // Enable the parent package
13150        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13151        // Enable the child packages
13152        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13153        for (int i = 0; i < childCount; i++) {
13154            PackageParser.Package childPkg = pkg.childPackages.get(i);
13155            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13156        }
13157    }
13158
13159    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13160        // Collect all used permissions in the UID
13161        ArraySet<String> usedPermissions = new ArraySet<>();
13162        final int packageCount = su.packages.size();
13163        for (int i = 0; i < packageCount; i++) {
13164            PackageSetting ps = su.packages.valueAt(i);
13165            if (ps.pkg == null) {
13166                continue;
13167            }
13168            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13169            for (int j = 0; j < requestedPermCount; j++) {
13170                String permission = ps.pkg.requestedPermissions.get(j);
13171                BasePermission bp = mSettings.mPermissions.get(permission);
13172                if (bp != null) {
13173                    usedPermissions.add(permission);
13174                }
13175            }
13176        }
13177
13178        PermissionsState permissionsState = su.getPermissionsState();
13179        // Prune install permissions
13180        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13181        final int installPermCount = installPermStates.size();
13182        for (int i = installPermCount - 1; i >= 0;  i--) {
13183            PermissionState permissionState = installPermStates.get(i);
13184            if (!usedPermissions.contains(permissionState.getName())) {
13185                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13186                if (bp != null) {
13187                    permissionsState.revokeInstallPermission(bp);
13188                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13189                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13190                }
13191            }
13192        }
13193
13194        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13195
13196        // Prune runtime permissions
13197        for (int userId : allUserIds) {
13198            List<PermissionState> runtimePermStates = permissionsState
13199                    .getRuntimePermissionStates(userId);
13200            final int runtimePermCount = runtimePermStates.size();
13201            for (int i = runtimePermCount - 1; i >= 0; i--) {
13202                PermissionState permissionState = runtimePermStates.get(i);
13203                if (!usedPermissions.contains(permissionState.getName())) {
13204                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13205                    if (bp != null) {
13206                        permissionsState.revokeRuntimePermission(bp, userId);
13207                        permissionsState.updatePermissionFlags(bp, userId,
13208                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13209                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13210                                runtimePermissionChangedUserIds, userId);
13211                    }
13212                }
13213            }
13214        }
13215
13216        return runtimePermissionChangedUserIds;
13217    }
13218
13219    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13220            int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) {
13221        // Update the parent package setting
13222        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled,
13223                res, user);
13224        // Update the child packages setting
13225        final int childCount = (newPackage.childPackages != null)
13226                ? newPackage.childPackages.size() : 0;
13227        for (int i = 0; i < childCount; i++) {
13228            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13229            updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled,
13230                    res, user);
13231        }
13232    }
13233
13234    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13235            String installerPackageName, int[] allUsers, boolean[] perUserInstalled,
13236            PackageInstalledInfo res, UserHandle user) {
13237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13238
13239        String pkgName = newPackage.packageName;
13240        synchronized (mPackages) {
13241            //write settings. the installStatus will be incomplete at this stage.
13242            //note that the new package setting would have already been
13243            //added to mPackages. It hasn't been persisted yet.
13244            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13245            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13246            mSettings.writeLPr();
13247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13248        }
13249
13250        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13251        synchronized (mPackages) {
13252            updatePermissionsLPw(newPackage.packageName, newPackage,
13253                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13254                            ? UPDATE_PERMISSIONS_ALL : 0));
13255            // For system-bundled packages, we assume that installing an upgraded version
13256            // of the package implies that the user actually wants to run that new code,
13257            // so we enable the package.
13258            PackageSetting ps = mSettings.mPackages.get(pkgName);
13259            if (ps != null) {
13260                if (isSystemApp(newPackage)) {
13261                    // NB: implicit assumption that system package upgrades apply to all users
13262                    if (DEBUG_INSTALL) {
13263                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13264                    }
13265                    if (res.origUsers != null) {
13266                        for (int userHandle : res.origUsers) {
13267                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13268                                    userHandle, installerPackageName);
13269                        }
13270                    }
13271                    // Also convey the prior install/uninstall state
13272                    if (allUsers != null && perUserInstalled != null) {
13273                        for (int i = 0; i < allUsers.length; i++) {
13274                            if (DEBUG_INSTALL) {
13275                                Slog.d(TAG, "    user " + allUsers[i]
13276                                        + " => " + perUserInstalled[i]);
13277                            }
13278                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
13279                        }
13280                        // these install state changes will be persisted in the
13281                        // upcoming call to mSettings.writeLPr().
13282                    }
13283                }
13284                // It's implied that when a user requests installation, they want the app to be
13285                // installed and enabled.
13286                int userId = user.getIdentifier();
13287                if (userId != UserHandle.USER_ALL) {
13288                    ps.setInstalled(true, userId);
13289                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13290                }
13291            }
13292            res.name = pkgName;
13293            res.uid = newPackage.applicationInfo.uid;
13294            res.pkg = newPackage;
13295            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13296            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13297            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13298            //to update install status
13299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13300            mSettings.writeLPr();
13301            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13302        }
13303
13304        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13305    }
13306
13307    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13308        try {
13309            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13310            installPackageLI(args, res);
13311        } finally {
13312            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13313        }
13314    }
13315
13316    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13317        final int installFlags = args.installFlags;
13318        final String installerPackageName = args.installerPackageName;
13319        final String volumeUuid = args.volumeUuid;
13320        final File tmpPackageFile = new File(args.getCodePath());
13321        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13322        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13323                || (args.volumeUuid != null));
13324        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13325        boolean replace = false;
13326        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13327        if (args.move != null) {
13328            // moving a complete application; perfom an initial scan on the new install location
13329            scanFlags |= SCAN_INITIAL;
13330        }
13331        // Result object to be returned
13332        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
13333
13334        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13335
13336        // Sanity check
13337        if (ephemeral && (forwardLocked || onExternal)) {
13338            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13339                    + " external=" + onExternal);
13340            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
13341            return;
13342        }
13343
13344        // Retrieve PackageSettings and parse package
13345        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13346                | PackageParser.PARSE_ENFORCE_CODE
13347                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13348                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13349                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13350        PackageParser pp = new PackageParser();
13351        pp.setSeparateProcesses(mSeparateProcesses);
13352        pp.setDisplayMetrics(mMetrics);
13353
13354        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13355        final PackageParser.Package pkg;
13356        try {
13357            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13358        } catch (PackageParserException e) {
13359            res.setError("Failed parse during installPackageLI", e);
13360            return;
13361        } finally {
13362            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13363        }
13364
13365        // If package doesn't declare API override, mark that we have an install
13366        // time CPU ABI override.
13367        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13368            pkg.cpuAbiOverride = args.abiOverride;
13369        }
13370
13371        String pkgName = res.name = pkg.packageName;
13372        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13373            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13374                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13375                return;
13376            }
13377        }
13378
13379        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13380        try {
13381            PackageParser.collectCertificates(pkg, parseFlags);
13382        } catch (PackageParserException e) {
13383            res.setError("Failed collect during installPackageLI", e);
13384            return;
13385        } finally {
13386            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13387        }
13388
13389        // Get rid of all references to package scan path via parser.
13390        pp = null;
13391        String oldCodePath = null;
13392        boolean systemApp = false;
13393        synchronized (mPackages) {
13394            // Check if installing already existing package
13395            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13396                String oldName = mSettings.mRenamedPackages.get(pkgName);
13397                if (pkg.mOriginalPackages != null
13398                        && pkg.mOriginalPackages.contains(oldName)
13399                        && mPackages.containsKey(oldName)) {
13400                    // This package is derived from an original package,
13401                    // and this device has been updating from that original
13402                    // name.  We must continue using the original name, so
13403                    // rename the new package here.
13404                    pkg.setPackageName(oldName);
13405                    pkgName = pkg.packageName;
13406                    replace = true;
13407                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13408                            + oldName + " pkgName=" + pkgName);
13409                } else if (mPackages.containsKey(pkgName)) {
13410                    // This package, under its official name, already exists
13411                    // on the device; we should replace it.
13412                    replace = true;
13413                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13414                }
13415
13416                // Child packages are installed through the parent package
13417                if (pkg.parentPackage != null) {
13418                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13419                            "Package " + pkg.packageName + " is child of package "
13420                                    + pkg.parentPackage.parentPackage + ". Child packages "
13421                                    + "can be updated only through the parent package.");
13422                    return;
13423                }
13424
13425                if (replace) {
13426                    // Prevent apps opting out from runtime permissions
13427                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13428                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13429                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13430                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13431                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13432                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13433                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13434                                        + " doesn't support runtime permissions but the old"
13435                                        + " target SDK " + oldTargetSdk + " does.");
13436                        return;
13437                    }
13438
13439                    // Prevent installing of child packages
13440                    if (oldPackage.parentPackage != null) {
13441                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13442                                "Package " + pkg.packageName + " is child of package "
13443                                        + oldPackage.parentPackage + ". Child packages "
13444                                        + "can be updated only through the parent package.");
13445                        return;
13446                    }
13447                }
13448            }
13449
13450            PackageSetting ps = mSettings.mPackages.get(pkgName);
13451            if (ps != null) {
13452                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13453
13454                // Quick sanity check that we're signed correctly if updating;
13455                // we'll check this again later when scanning, but we want to
13456                // bail early here before tripping over redefined permissions.
13457                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13458                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13459                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13460                                + pkg.packageName + " upgrade keys do not match the "
13461                                + "previously installed version");
13462                        return;
13463                    }
13464                } else {
13465                    try {
13466                        verifySignaturesLP(ps, pkg);
13467                    } catch (PackageManagerException e) {
13468                        res.setError(e.error, e.getMessage());
13469                        return;
13470                    }
13471                }
13472
13473                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13474                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13475                    systemApp = (ps.pkg.applicationInfo.flags &
13476                            ApplicationInfo.FLAG_SYSTEM) != 0;
13477                }
13478                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13479            }
13480
13481            // Check whether the newly-scanned package wants to define an already-defined perm
13482            int N = pkg.permissions.size();
13483            for (int i = N-1; i >= 0; i--) {
13484                PackageParser.Permission perm = pkg.permissions.get(i);
13485                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13486                if (bp != null) {
13487                    // If the defining package is signed with our cert, it's okay.  This
13488                    // also includes the "updating the same package" case, of course.
13489                    // "updating same package" could also involve key-rotation.
13490                    final boolean sigsOk;
13491                    if (bp.sourcePackage.equals(pkg.packageName)
13492                            && (bp.packageSetting instanceof PackageSetting)
13493                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13494                                    scanFlags))) {
13495                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13496                    } else {
13497                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13498                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13499                    }
13500                    if (!sigsOk) {
13501                        // If the owning package is the system itself, we log but allow
13502                        // install to proceed; we fail the install on all other permission
13503                        // redefinitions.
13504                        if (!bp.sourcePackage.equals("android")) {
13505                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13506                                    + pkg.packageName + " attempting to redeclare permission "
13507                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13508                            res.origPermission = perm.info.name;
13509                            res.origPackage = bp.sourcePackage;
13510                            return;
13511                        } else {
13512                            Slog.w(TAG, "Package " + pkg.packageName
13513                                    + " attempting to redeclare system permission "
13514                                    + perm.info.name + "; ignoring new declaration");
13515                            pkg.permissions.remove(i);
13516                        }
13517                    }
13518                }
13519            }
13520        }
13521
13522        if (systemApp) {
13523            if (onExternal) {
13524                // Abort update; system app can't be replaced with app on sdcard
13525                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13526                        "Cannot install updates to system apps on sdcard");
13527                return;
13528            } else if (ephemeral) {
13529                // Abort update; system app can't be replaced with an ephemeral app
13530                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13531                        "Cannot update a system app with an ephemeral app");
13532                return;
13533            }
13534        }
13535
13536        if (args.move != null) {
13537            // We did an in-place move, so dex is ready to roll
13538            scanFlags |= SCAN_NO_DEX;
13539            scanFlags |= SCAN_MOVE;
13540
13541            synchronized (mPackages) {
13542                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13543                if (ps == null) {
13544                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13545                            "Missing settings for moved package " + pkgName);
13546                }
13547
13548                // We moved the entire application as-is, so bring over the
13549                // previously derived ABI information.
13550                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13551                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13552            }
13553
13554        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13555            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13556            scanFlags |= SCAN_NO_DEX;
13557
13558            try {
13559                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13560                    args.abiOverride : pkg.cpuAbiOverride);
13561                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13562                        true /* extract libs */);
13563            } catch (PackageManagerException pme) {
13564                Slog.e(TAG, "Error deriving application ABI", pme);
13565                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13566                return;
13567            }
13568
13569            // Extract package to save the VM unzipping the APK in memory during
13570            // launch. Only do this if profile-guided compilation is enabled because
13571            // otherwise BackgroundDexOptService will not dexopt the package later.
13572            if (mUseJitProfiles) {
13573                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13574                // Do not run PackageDexOptimizer through the local performDexOpt
13575                // method because `pkg` is not in `mPackages` yet.
13576                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13577                        false /* useProfiles */, true /* extractOnly */);
13578                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13579                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13580                    String msg = "Extracking package failed for " + pkgName;
13581                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13582                    return;
13583                }
13584            }
13585        }
13586
13587        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13588            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13589            return;
13590        }
13591
13592        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13593
13594        if (replace) {
13595            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13596                    installerPackageName, volumeUuid, res);
13597        } else {
13598            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13599                    args.user, installerPackageName, volumeUuid, res);
13600        }
13601        synchronized (mPackages) {
13602            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13603            if (ps != null) {
13604                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13605            }
13606        }
13607    }
13608
13609    private void startIntentFilterVerifications(int userId, boolean replacing,
13610            PackageParser.Package pkg) {
13611        if (mIntentFilterVerifierComponent == null) {
13612            Slog.w(TAG, "No IntentFilter verification will not be done as "
13613                    + "there is no IntentFilterVerifier available!");
13614            return;
13615        }
13616
13617        final int verifierUid = getPackageUid(
13618                mIntentFilterVerifierComponent.getPackageName(),
13619                MATCH_DEBUG_TRIAGED_MISSING,
13620                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13621
13622        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13623        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13624        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13625        mHandler.sendMessage(msg);
13626    }
13627
13628    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13629            PackageParser.Package pkg) {
13630        int size = pkg.activities.size();
13631        if (size == 0) {
13632            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13633                    "No activity, so no need to verify any IntentFilter!");
13634            return;
13635        }
13636
13637        final boolean hasDomainURLs = hasDomainURLs(pkg);
13638        if (!hasDomainURLs) {
13639            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13640                    "No domain URLs, so no need to verify any IntentFilter!");
13641            return;
13642        }
13643
13644        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13645                + " if any IntentFilter from the " + size
13646                + " Activities needs verification ...");
13647
13648        int count = 0;
13649        final String packageName = pkg.packageName;
13650
13651        synchronized (mPackages) {
13652            // If this is a new install and we see that we've already run verification for this
13653            // package, we have nothing to do: it means the state was restored from backup.
13654            if (!replacing) {
13655                IntentFilterVerificationInfo ivi =
13656                        mSettings.getIntentFilterVerificationLPr(packageName);
13657                if (ivi != null) {
13658                    if (DEBUG_DOMAIN_VERIFICATION) {
13659                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13660                                + ivi.getStatusString());
13661                    }
13662                    return;
13663                }
13664            }
13665
13666            // If any filters need to be verified, then all need to be.
13667            boolean needToVerify = false;
13668            for (PackageParser.Activity a : pkg.activities) {
13669                for (ActivityIntentInfo filter : a.intents) {
13670                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13671                        if (DEBUG_DOMAIN_VERIFICATION) {
13672                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13673                        }
13674                        needToVerify = true;
13675                        break;
13676                    }
13677                }
13678            }
13679
13680            if (needToVerify) {
13681                final int verificationId = mIntentFilterVerificationToken++;
13682                for (PackageParser.Activity a : pkg.activities) {
13683                    for (ActivityIntentInfo filter : a.intents) {
13684                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13685                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13686                                    "Verification needed for IntentFilter:" + filter.toString());
13687                            mIntentFilterVerifier.addOneIntentFilterVerification(
13688                                    verifierUid, userId, verificationId, filter, packageName);
13689                            count++;
13690                        }
13691                    }
13692                }
13693            }
13694        }
13695
13696        if (count > 0) {
13697            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13698                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13699                    +  " for userId:" + userId);
13700            mIntentFilterVerifier.startVerifications(userId);
13701        } else {
13702            if (DEBUG_DOMAIN_VERIFICATION) {
13703                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13704            }
13705        }
13706    }
13707
13708    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13709        final ComponentName cn  = filter.activity.getComponentName();
13710        final String packageName = cn.getPackageName();
13711
13712        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13713                packageName);
13714        if (ivi == null) {
13715            return true;
13716        }
13717        int status = ivi.getStatus();
13718        switch (status) {
13719            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13720            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13721                return true;
13722
13723            default:
13724                // Nothing to do
13725                return false;
13726        }
13727    }
13728
13729    private static boolean isMultiArch(ApplicationInfo info) {
13730        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13731    }
13732
13733    private static boolean isExternal(PackageParser.Package pkg) {
13734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13735    }
13736
13737    private static boolean isExternal(PackageSetting ps) {
13738        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13739    }
13740
13741    private static boolean isEphemeral(PackageParser.Package pkg) {
13742        return pkg.applicationInfo.isEphemeralApp();
13743    }
13744
13745    private static boolean isEphemeral(PackageSetting ps) {
13746        return ps.pkg != null && isEphemeral(ps.pkg);
13747    }
13748
13749    private static boolean isSystemApp(PackageParser.Package pkg) {
13750        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13751    }
13752
13753    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13754        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13755    }
13756
13757    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13758        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13759    }
13760
13761    private static boolean isSystemApp(PackageSetting ps) {
13762        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13763    }
13764
13765    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13766        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13767    }
13768
13769    private int packageFlagsToInstallFlags(PackageSetting ps) {
13770        int installFlags = 0;
13771        if (isEphemeral(ps)) {
13772            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13773        }
13774        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13775            // This existing package was an external ASEC install when we have
13776            // the external flag without a UUID
13777            installFlags |= PackageManager.INSTALL_EXTERNAL;
13778        }
13779        if (ps.isForwardLocked()) {
13780            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13781        }
13782        return installFlags;
13783    }
13784
13785    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13786        if (isExternal(pkg)) {
13787            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13788                return StorageManager.UUID_PRIMARY_PHYSICAL;
13789            } else {
13790                return pkg.volumeUuid;
13791            }
13792        } else {
13793            return StorageManager.UUID_PRIVATE_INTERNAL;
13794        }
13795    }
13796
13797    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13798        if (isExternal(pkg)) {
13799            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13800                return mSettings.getExternalVersion();
13801            } else {
13802                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13803            }
13804        } else {
13805            return mSettings.getInternalVersion();
13806        }
13807    }
13808
13809    private void deleteTempPackageFiles() {
13810        final FilenameFilter filter = new FilenameFilter() {
13811            public boolean accept(File dir, String name) {
13812                return name.startsWith("vmdl") && name.endsWith(".tmp");
13813            }
13814        };
13815        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13816            file.delete();
13817        }
13818    }
13819
13820    @Override
13821    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13822            int flags) {
13823        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13824                flags);
13825    }
13826
13827    @Override
13828    public void deletePackage(final String packageName,
13829            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13830        mContext.enforceCallingOrSelfPermission(
13831                android.Manifest.permission.DELETE_PACKAGES, null);
13832        Preconditions.checkNotNull(packageName);
13833        Preconditions.checkNotNull(observer);
13834        final int uid = Binder.getCallingUid();
13835        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13836        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13837        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13838            mContext.enforceCallingOrSelfPermission(
13839                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13840                    "deletePackage for user " + userId);
13841        }
13842
13843        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13844            try {
13845                observer.onPackageDeleted(packageName,
13846                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13847            } catch (RemoteException re) {
13848            }
13849            return;
13850        }
13851
13852        for (int currentUserId : users) {
13853            if (getBlockUninstallForUser(packageName, currentUserId)) {
13854                try {
13855                    observer.onPackageDeleted(packageName,
13856                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13857                } catch (RemoteException re) {
13858                }
13859                return;
13860            }
13861        }
13862
13863        if (DEBUG_REMOVE) {
13864            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13865        }
13866        // Queue up an async operation since the package deletion may take a little while.
13867        mHandler.post(new Runnable() {
13868            public void run() {
13869                mHandler.removeCallbacks(this);
13870                final int returnCode = deletePackageX(packageName, userId, flags);
13871                try {
13872                    observer.onPackageDeleted(packageName, returnCode, null);
13873                } catch (RemoteException e) {
13874                    Log.i(TAG, "Observer no longer exists.");
13875                } //end catch
13876            } //end run
13877        });
13878    }
13879
13880    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13881        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13882                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13883        try {
13884            if (dpm != null) {
13885                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13886                        /* callingUserOnly =*/ false);
13887                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13888                        : deviceOwnerComponentName.getPackageName();
13889                // Does the package contains the device owner?
13890                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13891                // this check is probably not needed, since DO should be registered as a device
13892                // admin on some user too. (Original bug for this: b/17657954)
13893                if (packageName.equals(deviceOwnerPackageName)) {
13894                    return true;
13895                }
13896                // Does it contain a device admin for any user?
13897                int[] users;
13898                if (userId == UserHandle.USER_ALL) {
13899                    users = sUserManager.getUserIds();
13900                } else {
13901                    users = new int[]{userId};
13902                }
13903                for (int i = 0; i < users.length; ++i) {
13904                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13905                        return true;
13906                    }
13907                }
13908            }
13909        } catch (RemoteException e) {
13910        }
13911        return false;
13912    }
13913
13914    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13915        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13916    }
13917
13918    /**
13919     *  This method is an internal method that could be get invoked either
13920     *  to delete an installed package or to clean up a failed installation.
13921     *  After deleting an installed package, a broadcast is sent to notify any
13922     *  listeners that the package has been installed. For cleaning up a failed
13923     *  installation, the broadcast is not necessary since the package's
13924     *  installation wouldn't have sent the initial broadcast either
13925     *  The key steps in deleting a package are
13926     *  deleting the package information in internal structures like mPackages,
13927     *  deleting the packages base directories through installd
13928     *  updating mSettings to reflect current status
13929     *  persisting settings for later use
13930     *  sending a broadcast if necessary
13931     */
13932    private int deletePackageX(String packageName, int userId, int flags) {
13933        final PackageRemovedInfo info = new PackageRemovedInfo();
13934        final boolean res;
13935
13936        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13937                ? UserHandle.ALL : new UserHandle(userId);
13938
13939        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13940            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13941            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13942        }
13943
13944        boolean removedForAllUsers = false;
13945        boolean systemUpdate = false;
13946
13947        PackageParser.Package uninstalledPkg;
13948
13949        // for the uninstall-updates case and restricted profiles, remember the per-
13950        // userhandle installed state
13951        int[] allUsers;
13952        boolean[] perUserInstalled;
13953        synchronized (mPackages) {
13954            uninstalledPkg = mPackages.get(packageName);
13955            PackageSetting ps = mSettings.mPackages.get(packageName);
13956            allUsers = sUserManager.getUserIds();
13957            perUserInstalled = new boolean[allUsers.length];
13958            for (int i = 0; i < allUsers.length; i++) {
13959                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13960            }
13961        }
13962
13963        synchronized (mInstallLock) {
13964            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13965            res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled,
13966                    flags | REMOVE_CHATTY, info, true, null);
13967            systemUpdate = info.isRemovedPackageSystemUpdate;
13968            synchronized (mPackages) {
13969                if (res) {
13970                    if (!systemUpdate && mPackages.get(packageName) == null) {
13971                        removedForAllUsers = true;
13972                    }
13973                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13974                }
13975            }
13976            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13977                    + " removedForAllUsers=" + removedForAllUsers);
13978        }
13979
13980        if (res) {
13981            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13982
13983            // If the removed package was a system update, the old system package
13984            // was re-enabled; we need to broadcast this information
13985            if (systemUpdate) {
13986                Bundle extras = new Bundle(1);
13987                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13988                        ? info.removedAppId : info.uid);
13989                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13990
13991                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13992                        extras, 0, null, null, null);
13993                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13994                        extras, 0, null, null, null);
13995                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13996                        null, 0, packageName, null, null);
13997            }
13998        }
13999        // Force a gc here.
14000        Runtime.getRuntime().gc();
14001        // Delete the resources here after sending the broadcast to let
14002        // other processes clean up before deleting resources.
14003        if (info.args != null) {
14004            synchronized (mInstallLock) {
14005                info.args.doPostDeleteLI(true);
14006            }
14007        }
14008
14009        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14010    }
14011
14012    class PackageRemovedInfo {
14013        String removedPackage;
14014        int uid = -1;
14015        int removedAppId = -1;
14016        int[] removedUsers = null;
14017        boolean isRemovedPackageSystemUpdate = false;
14018        // Clean up resources deleted packages.
14019        InstallArgs args = null;
14020
14021        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
14022            Bundle extras = new Bundle(1);
14023            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14024            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
14025            if (replacing) {
14026                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14027            }
14028            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14029            if (removedPackage != null) {
14030                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14031                        extras, 0, null, null, removedUsers);
14032                if (fullRemove && !replacing) {
14033                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
14034                            extras, 0, null, null, removedUsers);
14035                }
14036            }
14037            if (removedAppId >= 0) {
14038                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14039                        removedUsers);
14040            }
14041        }
14042    }
14043
14044    /*
14045     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14046     * flag is not set, the data directory is removed as well.
14047     * make sure this flag is set for partially installed apps. If not its meaningless to
14048     * delete a partially installed application.
14049     */
14050    private void removePackageDataLI(PackageSetting ps,
14051            int[] allUserHandles, boolean[] perUserInstalled,
14052            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14053        String packageName = ps.name;
14054        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14055        removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0);
14056        // Retrieve object to delete permissions for shared user later on
14057        final PackageSetting deletedPs;
14058        // reader
14059        synchronized (mPackages) {
14060            deletedPs = mSettings.mPackages.get(packageName);
14061            if (outInfo != null) {
14062                outInfo.removedPackage = packageName;
14063                outInfo.removedUsers = deletedPs != null
14064                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14065                        : null;
14066            }
14067        }
14068        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14069            removeDataDirsLI(ps.volumeUuid, packageName);
14070            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14071        }
14072        // writer
14073        synchronized (mPackages) {
14074            if (deletedPs != null) {
14075                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14076                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14077                    clearDefaultBrowserIfNeeded(packageName);
14078                    if (outInfo != null) {
14079                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14080                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14081                    }
14082                    updatePermissionsLPw(deletedPs.name, null, 0);
14083                    if (deletedPs.sharedUser != null) {
14084                        // Remove permissions associated with package. Since runtime
14085                        // permissions are per user we have to kill the removed package
14086                        // or packages running under the shared user of the removed
14087                        // package if revoking the permissions requested only by the removed
14088                        // package is successful and this causes a change in gids.
14089                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14090                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14091                                    userId);
14092                            if (userIdToKill == UserHandle.USER_ALL
14093                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14094                                // If gids changed for this user, kill all affected packages.
14095                                mHandler.post(new Runnable() {
14096                                    @Override
14097                                    public void run() {
14098                                        // This has to happen with no lock held.
14099                                        killApplication(deletedPs.name, deletedPs.appId,
14100                                                KILL_APP_REASON_GIDS_CHANGED);
14101                                    }
14102                                });
14103                                break;
14104                            }
14105                        }
14106                    }
14107                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14108                }
14109                // make sure to preserve per-user disabled state if this removal was just
14110                // a downgrade of a system app to the factory package
14111                if (allUserHandles != null && perUserInstalled != null) {
14112                    if (DEBUG_REMOVE) {
14113                        Slog.d(TAG, "Propagating install state across downgrade");
14114                    }
14115                    for (int i = 0; i < allUserHandles.length; i++) {
14116                        if (DEBUG_REMOVE) {
14117                            Slog.d(TAG, "    user " + allUserHandles[i]
14118                                    + " => " + perUserInstalled[i]);
14119                        }
14120                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14121                    }
14122                }
14123            }
14124            // can downgrade to reader
14125            if (writeSettings) {
14126                // Save settings now
14127                mSettings.writeLPr();
14128            }
14129        }
14130        if (outInfo != null) {
14131            // A user ID was deleted here. Go through all users and remove it
14132            // from KeyStore.
14133            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14134        }
14135    }
14136
14137    static boolean locationIsPrivileged(File path) {
14138        try {
14139            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14140                    .getCanonicalPath();
14141            return path.getCanonicalPath().startsWith(privilegedAppDir);
14142        } catch (IOException e) {
14143            Slog.e(TAG, "Unable to access code path " + path);
14144        }
14145        return false;
14146    }
14147
14148    /*
14149     * Tries to delete system package.
14150     */
14151    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14152            PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled,
14153            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14154            PackageParser.Package replacingPackage) {
14155        if (deletedPkg.parentPackage != null) {
14156            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14157            return false;
14158        }
14159
14160        final boolean applyUserRestrictions
14161                = (allUserHandles != null) && (perUserInstalled != null);
14162        final PackageSetting disabledPs;
14163        // Confirm if the system package has been updated
14164        // An updated system app can be deleted. This will also have to restore
14165        // the system pkg from system partition
14166        // reader
14167        synchronized (mPackages) {
14168            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14169        }
14170
14171        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14172                + " disabledPs=" + disabledPs);
14173
14174        if (disabledPs == null) {
14175            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14176            return false;
14177        } else if (DEBUG_REMOVE) {
14178            Slog.d(TAG, "Deleting system pkg from data partition");
14179        }
14180
14181        if (DEBUG_REMOVE) {
14182            if (applyUserRestrictions) {
14183                Slog.d(TAG, "Remembering install states:");
14184                for (int i = 0; i < allUserHandles.length; i++) {
14185                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
14186                }
14187            }
14188        }
14189
14190        // Delete the updated package
14191        outInfo.isRemovedPackageSystemUpdate = true;
14192        if (disabledPs.versionCode < deletedPs.versionCode) {
14193            // Delete data for downgrades
14194            flags &= ~PackageManager.DELETE_KEEP_DATA;
14195        } else {
14196            // Preserve data by setting flag
14197            flags |= PackageManager.DELETE_KEEP_DATA;
14198        }
14199        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14200                perUserInstalled, outInfo, writeSettings, replacingPackage);
14201        if (!ret) {
14202            return false;
14203        }
14204
14205        // writer
14206        synchronized (mPackages) {
14207            // Reinstate the old system package
14208            enableSystemPackageLPw(disabledPs.pkg);
14209            // Remove any native libraries from the upgraded package.
14210            removeNativeBinariesLI(deletedPkg);
14211        }
14212
14213        // Install the system package
14214        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14215        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14216        if (locationIsPrivileged(disabledPs.codePath)) {
14217            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14218        }
14219
14220        final PackageParser.Package newPkg;
14221        try {
14222            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14223        } catch (PackageManagerException e) {
14224            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14225                    + e.getMessage());
14226            return false;
14227        }
14228
14229        prepareAppDataAfterInstall(newPkg);
14230
14231        // writer
14232        synchronized (mPackages) {
14233            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14234
14235            // Propagate the permissions state as we do not want to drop on the floor
14236            // runtime permissions. The update permissions method below will take
14237            // care of removing obsolete permissions and grant install permissions.
14238            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14239            updatePermissionsLPw(newPkg.packageName, newPkg,
14240                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14241
14242            if (applyUserRestrictions) {
14243                if (DEBUG_REMOVE) {
14244                    Slog.d(TAG, "Propagating install state across reinstall");
14245                }
14246                for (int i = 0; i < allUserHandles.length; i++) {
14247                    if (DEBUG_REMOVE) {
14248                        Slog.d(TAG, "    user " + allUserHandles[i]
14249                                + " => " + perUserInstalled[i]);
14250                    }
14251                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
14252
14253                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
14254                }
14255                // Regardless of writeSettings we need to ensure that this restriction
14256                // state propagation is persisted
14257                mSettings.writeAllUsersPackageRestrictionsLPr();
14258            }
14259            // can downgrade to reader here
14260            if (writeSettings) {
14261                mSettings.writeLPr();
14262            }
14263        }
14264        return true;
14265    }
14266
14267    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14268            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14269            boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings,
14270            PackageParser.Package replacingPackage) {
14271        PackageSetting ps = null;
14272
14273        synchronized (mPackages) {
14274            pkg = mPackages.get(pkg.packageName);
14275            if (pkg == null) {
14276                return false;
14277            }
14278
14279            ps = mSettings.mPackages.get(pkg.packageName);
14280            if (ps == null) {
14281                return false;
14282            }
14283
14284            if (outInfo != null) {
14285                outInfo.uid = ps.appId;
14286            }
14287        }
14288
14289        // Delete package data from internal structures and also remove data if flag is set
14290        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags,
14291                    writeSettings);
14292
14293        // Delete the child packages data
14294        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14295        for (int i = 0; i < childCount; i++) {
14296            PackageSetting childPs;
14297            synchronized (mPackages) {
14298                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14299            }
14300            if (childPs != null) {
14301                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14302                        && (replacingPackage != null
14303                        && !replacingPackage.hasChildPackage(childPs.name))
14304                        ? flags & ~DELETE_KEEP_DATA : flags;
14305                removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo,
14306                        deleteFlags, writeSettings);
14307            }
14308        }
14309
14310        // Delete application code and resources only for parent packages
14311        if (ps.pkg.parentPackage == null) {
14312                if (deleteCodeAndResources && (outInfo != null)) {
14313                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14314                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14315                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14316            }
14317        }
14318
14319        return true;
14320    }
14321
14322    @Override
14323    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14324            int userId) {
14325        mContext.enforceCallingOrSelfPermission(
14326                android.Manifest.permission.DELETE_PACKAGES, null);
14327        synchronized (mPackages) {
14328            PackageSetting ps = mSettings.mPackages.get(packageName);
14329            if (ps == null) {
14330                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14331                return false;
14332            }
14333            if (!ps.getInstalled(userId)) {
14334                // Can't block uninstall for an app that is not installed or enabled.
14335                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14336                return false;
14337            }
14338            ps.setBlockUninstall(blockUninstall, userId);
14339            mSettings.writePackageRestrictionsLPr(userId);
14340        }
14341        return true;
14342    }
14343
14344    @Override
14345    public boolean getBlockUninstallForUser(String packageName, int userId) {
14346        synchronized (mPackages) {
14347            PackageSetting ps = mSettings.mPackages.get(packageName);
14348            if (ps == null) {
14349                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14350                return false;
14351            }
14352            return ps.getBlockUninstall(userId);
14353        }
14354    }
14355
14356    @Override
14357    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14358        int callingUid = Binder.getCallingUid();
14359        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14360            throw new SecurityException(
14361                    "setRequiredForSystemUser can only be run by the system or root");
14362        }
14363        synchronized (mPackages) {
14364            PackageSetting ps = mSettings.mPackages.get(packageName);
14365            if (ps == null) {
14366                Log.w(TAG, "Package doesn't exist: " + packageName);
14367                return false;
14368            }
14369            if (systemUserApp) {
14370                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14371            } else {
14372                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14373            }
14374            mSettings.writeLPr();
14375        }
14376        return true;
14377    }
14378
14379    /*
14380     * This method handles package deletion in general
14381     */
14382    private boolean deletePackageLI(String packageName, UserHandle user,
14383            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
14384            int flags, PackageRemovedInfo outInfo, boolean writeSettings,
14385            PackageParser.Package replacingPackage) {
14386        if (packageName == null) {
14387            Slog.w(TAG, "Attempt to delete null packageName.");
14388            return false;
14389        }
14390
14391        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14392
14393        PackageSetting ps;
14394
14395        synchronized (mPackages) {
14396            ps = mSettings.mPackages.get(packageName);
14397            if (ps == null) {
14398                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14399                return false;
14400            }
14401
14402            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14403                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14404                if (DEBUG_REMOVE) {
14405                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14406                            + ((user == null) ? UserHandle.USER_ALL : user));
14407                }
14408                final int removedUserId = (user != null) ? user.getIdentifier()
14409                        : UserHandle.USER_ALL;
14410                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14411                    return false;
14412                }
14413                markPackageUninstalledForUserLPw(ps, user);
14414                scheduleWritePackageRestrictionsLocked(user);
14415                return true;
14416            }
14417        }
14418
14419        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14420                && user.getIdentifier() != UserHandle.USER_ALL)) {
14421            // The caller is asking that the package only be deleted for a single
14422            // user.  To do this, we just mark its uninstalled state and delete
14423            // its data. If this is a system app, we only allow this to happen if
14424            // they have set the special DELETE_SYSTEM_APP which requests different
14425            // semantics than normal for uninstalling system apps.
14426            markPackageUninstalledForUserLPw(ps, user);
14427
14428            if (!isSystemApp(ps)) {
14429                // Do not uninstall the APK if an app should be cached
14430                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14431                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14432                    // Other user still have this package installed, so all
14433                    // we need to do is clear this user's data and save that
14434                    // it is uninstalled.
14435                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14436                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14437                        return false;
14438                    }
14439                    scheduleWritePackageRestrictionsLocked(user);
14440                    return true;
14441                } else {
14442                    // We need to set it back to 'installed' so the uninstall
14443                    // broadcasts will be sent correctly.
14444                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14445                    ps.setInstalled(true, user.getIdentifier());
14446                }
14447            } else {
14448                // This is a system app, so we assume that the
14449                // other users still have this package installed, so all
14450                // we need to do is clear this user's data and save that
14451                // it is uninstalled.
14452                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14453                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14454                    return false;
14455                }
14456                scheduleWritePackageRestrictionsLocked(user);
14457                return true;
14458            }
14459        }
14460
14461        boolean ret = false;
14462        if (isSystemApp(ps)) {
14463            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14464            // When an updated system application is deleted we delete the existing resources as well and
14465            // fall back to existing code in system partition
14466            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled,
14467                    flags, outInfo, writeSettings, replacingPackage);
14468        } else {
14469            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14470            // Kill application pre-emptively especially for apps on sd.
14471            killApplication(packageName, ps.appId, "uninstall pkg");
14472            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14473                    perUserInstalled, outInfo, writeSettings, replacingPackage);
14474        }
14475
14476        return ret;
14477    }
14478
14479    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14480        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14481                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14482        for (int nextUserId : userIds) {
14483            if (DEBUG_REMOVE) {
14484                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14485            }
14486            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14487                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14488                    false /*hidden*/, false /*suspended*/, null, null, null,
14489                    false /*blockUninstall*/,
14490                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14491        }
14492    }
14493
14494    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14495            PackageRemovedInfo outInfo) {
14496        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14497                : new int[] {userId};
14498        for (int nextUserId : userIds) {
14499            if (DEBUG_REMOVE) {
14500                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14501                        + nextUserId);
14502            }
14503            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14504            try {
14505                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14506            } catch (InstallerException e) {
14507                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14508                return false;
14509            }
14510            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14511            schedulePackageCleaning(ps.name, nextUserId, false);
14512            synchronized (mPackages) {
14513                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14514                    scheduleWritePackageRestrictionsLocked(nextUserId);
14515                }
14516                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14517            }
14518        }
14519
14520        if (outInfo != null) {
14521            outInfo.removedPackage = ps.name;
14522            outInfo.removedAppId = ps.appId;
14523            outInfo.removedUsers = userIds;
14524        }
14525
14526        return true;
14527    }
14528
14529    private final class ClearStorageConnection implements ServiceConnection {
14530        IMediaContainerService mContainerService;
14531
14532        @Override
14533        public void onServiceConnected(ComponentName name, IBinder service) {
14534            synchronized (this) {
14535                mContainerService = IMediaContainerService.Stub.asInterface(service);
14536                notifyAll();
14537            }
14538        }
14539
14540        @Override
14541        public void onServiceDisconnected(ComponentName name) {
14542        }
14543    }
14544
14545    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14546        final boolean mounted;
14547        if (Environment.isExternalStorageEmulated()) {
14548            mounted = true;
14549        } else {
14550            final String status = Environment.getExternalStorageState();
14551
14552            mounted = status.equals(Environment.MEDIA_MOUNTED)
14553                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14554        }
14555
14556        if (!mounted) {
14557            return;
14558        }
14559
14560        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14561        int[] users;
14562        if (userId == UserHandle.USER_ALL) {
14563            users = sUserManager.getUserIds();
14564        } else {
14565            users = new int[] { userId };
14566        }
14567        final ClearStorageConnection conn = new ClearStorageConnection();
14568        if (mContext.bindServiceAsUser(
14569                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14570            try {
14571                for (int curUser : users) {
14572                    long timeout = SystemClock.uptimeMillis() + 5000;
14573                    synchronized (conn) {
14574                        long now = SystemClock.uptimeMillis();
14575                        while (conn.mContainerService == null && now < timeout) {
14576                            try {
14577                                conn.wait(timeout - now);
14578                            } catch (InterruptedException e) {
14579                            }
14580                        }
14581                    }
14582                    if (conn.mContainerService == null) {
14583                        return;
14584                    }
14585
14586                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14587                    clearDirectory(conn.mContainerService,
14588                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14589                    if (allData) {
14590                        clearDirectory(conn.mContainerService,
14591                                userEnv.buildExternalStorageAppDataDirs(packageName));
14592                        clearDirectory(conn.mContainerService,
14593                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14594                    }
14595                }
14596            } finally {
14597                mContext.unbindService(conn);
14598            }
14599        }
14600    }
14601
14602    @Override
14603    public void clearApplicationUserData(final String packageName,
14604            final IPackageDataObserver observer, final int userId) {
14605        mContext.enforceCallingOrSelfPermission(
14606                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14607        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14608        // Queue up an async operation since the package deletion may take a little while.
14609        mHandler.post(new Runnable() {
14610            public void run() {
14611                mHandler.removeCallbacks(this);
14612                final boolean succeeded;
14613                synchronized (mInstallLock) {
14614                    succeeded = clearApplicationUserDataLI(packageName, userId);
14615                }
14616                clearExternalStorageDataSync(packageName, userId, true);
14617                if (succeeded) {
14618                    // invoke DeviceStorageMonitor's update method to clear any notifications
14619                    DeviceStorageMonitorInternal
14620                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14621                    if (dsm != null) {
14622                        dsm.checkMemory();
14623                    }
14624                }
14625                if(observer != null) {
14626                    try {
14627                        observer.onRemoveCompleted(packageName, succeeded);
14628                    } catch (RemoteException e) {
14629                        Log.i(TAG, "Observer no longer exists.");
14630                    }
14631                } //end if observer
14632            } //end run
14633        });
14634    }
14635
14636    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14637        if (packageName == null) {
14638            Slog.w(TAG, "Attempt to delete null packageName.");
14639            return false;
14640        }
14641
14642        // Try finding details about the requested package
14643        PackageParser.Package pkg;
14644        synchronized (mPackages) {
14645            pkg = mPackages.get(packageName);
14646            if (pkg == null) {
14647                final PackageSetting ps = mSettings.mPackages.get(packageName);
14648                if (ps != null) {
14649                    pkg = ps.pkg;
14650                }
14651            }
14652
14653            if (pkg == null) {
14654                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14655                return false;
14656            }
14657
14658            PackageSetting ps = (PackageSetting) pkg.mExtras;
14659            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14660        }
14661
14662        // Always delete data directories for package, even if we found no other
14663        // record of app. This helps users recover from UID mismatches without
14664        // resorting to a full data wipe.
14665        // TODO: triage flags as part of 26466827
14666        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14667        try {
14668            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14669        } catch (InstallerException e) {
14670            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14671            return false;
14672        }
14673
14674        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14675        removeKeystoreDataIfNeeded(userId, appId);
14676
14677        // Create a native library symlink only if we have native libraries
14678        // and if the native libraries are 32 bit libraries. We do not provide
14679        // this symlink for 64 bit libraries.
14680        if (pkg.applicationInfo.primaryCpuAbi != null &&
14681                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14682            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14683            try {
14684                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14685                        nativeLibPath, userId);
14686            } catch (InstallerException e) {
14687                Slog.w(TAG, "Failed linking native library dir", e);
14688                return false;
14689            }
14690        }
14691
14692        return true;
14693    }
14694
14695    /**
14696     * Reverts user permission state changes (permissions and flags) in
14697     * all packages for a given user.
14698     *
14699     * @param userId The device user for which to do a reset.
14700     */
14701    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14702        final int packageCount = mPackages.size();
14703        for (int i = 0; i < packageCount; i++) {
14704            PackageParser.Package pkg = mPackages.valueAt(i);
14705            PackageSetting ps = (PackageSetting) pkg.mExtras;
14706            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14707        }
14708    }
14709
14710    /**
14711     * Reverts user permission state changes (permissions and flags).
14712     *
14713     * @param ps The package for which to reset.
14714     * @param userId The device user for which to do a reset.
14715     */
14716    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14717            final PackageSetting ps, final int userId) {
14718        if (ps.pkg == null) {
14719            return;
14720        }
14721
14722        // These are flags that can change base on user actions.
14723        final int userSettableMask = FLAG_PERMISSION_USER_SET
14724                | FLAG_PERMISSION_USER_FIXED
14725                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14726                | FLAG_PERMISSION_REVIEW_REQUIRED;
14727
14728        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14729                | FLAG_PERMISSION_POLICY_FIXED;
14730
14731        boolean writeInstallPermissions = false;
14732        boolean writeRuntimePermissions = false;
14733
14734        final int permissionCount = ps.pkg.requestedPermissions.size();
14735        for (int i = 0; i < permissionCount; i++) {
14736            String permission = ps.pkg.requestedPermissions.get(i);
14737
14738            BasePermission bp = mSettings.mPermissions.get(permission);
14739            if (bp == null) {
14740                continue;
14741            }
14742
14743            // If shared user we just reset the state to which only this app contributed.
14744            if (ps.sharedUser != null) {
14745                boolean used = false;
14746                final int packageCount = ps.sharedUser.packages.size();
14747                for (int j = 0; j < packageCount; j++) {
14748                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14749                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14750                            && pkg.pkg.requestedPermissions.contains(permission)) {
14751                        used = true;
14752                        break;
14753                    }
14754                }
14755                if (used) {
14756                    continue;
14757                }
14758            }
14759
14760            PermissionsState permissionsState = ps.getPermissionsState();
14761
14762            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14763
14764            // Always clear the user settable flags.
14765            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14766                    bp.name) != null;
14767            // If permission review is enabled and this is a legacy app, mark the
14768            // permission as requiring a review as this is the initial state.
14769            int flags = 0;
14770            if (Build.PERMISSIONS_REVIEW_REQUIRED
14771                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14772                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14773            }
14774            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14775                if (hasInstallState) {
14776                    writeInstallPermissions = true;
14777                } else {
14778                    writeRuntimePermissions = true;
14779                }
14780            }
14781
14782            // Below is only runtime permission handling.
14783            if (!bp.isRuntime()) {
14784                continue;
14785            }
14786
14787            // Never clobber system or policy.
14788            if ((oldFlags & policyOrSystemFlags) != 0) {
14789                continue;
14790            }
14791
14792            // If this permission was granted by default, make sure it is.
14793            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14794                if (permissionsState.grantRuntimePermission(bp, userId)
14795                        != PERMISSION_OPERATION_FAILURE) {
14796                    writeRuntimePermissions = true;
14797                }
14798            // If permission review is enabled the permissions for a legacy apps
14799            // are represented as constantly granted runtime ones, so don't revoke.
14800            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14801                // Otherwise, reset the permission.
14802                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14803                switch (revokeResult) {
14804                    case PERMISSION_OPERATION_SUCCESS: {
14805                        writeRuntimePermissions = true;
14806                    } break;
14807
14808                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14809                        writeRuntimePermissions = true;
14810                        final int appId = ps.appId;
14811                        mHandler.post(new Runnable() {
14812                            @Override
14813                            public void run() {
14814                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14815                            }
14816                        });
14817                    } break;
14818                }
14819            }
14820        }
14821
14822        // Synchronously write as we are taking permissions away.
14823        if (writeRuntimePermissions) {
14824            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14825        }
14826
14827        // Synchronously write as we are taking permissions away.
14828        if (writeInstallPermissions) {
14829            mSettings.writeLPr();
14830        }
14831    }
14832
14833    /**
14834     * Remove entries from the keystore daemon. Will only remove it if the
14835     * {@code appId} is valid.
14836     */
14837    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14838        if (appId < 0) {
14839            return;
14840        }
14841
14842        final KeyStore keyStore = KeyStore.getInstance();
14843        if (keyStore != null) {
14844            if (userId == UserHandle.USER_ALL) {
14845                for (final int individual : sUserManager.getUserIds()) {
14846                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14847                }
14848            } else {
14849                keyStore.clearUid(UserHandle.getUid(userId, appId));
14850            }
14851        } else {
14852            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14853        }
14854    }
14855
14856    @Override
14857    public void deleteApplicationCacheFiles(final String packageName,
14858            final IPackageDataObserver observer) {
14859        mContext.enforceCallingOrSelfPermission(
14860                android.Manifest.permission.DELETE_CACHE_FILES, null);
14861        // Queue up an async operation since the package deletion may take a little while.
14862        final int userId = UserHandle.getCallingUserId();
14863        mHandler.post(new Runnable() {
14864            public void run() {
14865                mHandler.removeCallbacks(this);
14866                final boolean succeded;
14867                synchronized (mInstallLock) {
14868                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14869                }
14870                clearExternalStorageDataSync(packageName, userId, false);
14871                if (observer != null) {
14872                    try {
14873                        observer.onRemoveCompleted(packageName, succeded);
14874                    } catch (RemoteException e) {
14875                        Log.i(TAG, "Observer no longer exists.");
14876                    }
14877                } //end if observer
14878            } //end run
14879        });
14880    }
14881
14882    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14883        if (packageName == null) {
14884            Slog.w(TAG, "Attempt to delete null packageName.");
14885            return false;
14886        }
14887        PackageParser.Package p;
14888        synchronized (mPackages) {
14889            p = mPackages.get(packageName);
14890        }
14891        if (p == null) {
14892            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14893            return false;
14894        }
14895        final ApplicationInfo applicationInfo = p.applicationInfo;
14896        if (applicationInfo == null) {
14897            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14898            return false;
14899        }
14900        // TODO: triage flags as part of 26466827
14901        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14902        try {
14903            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14904                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14905        } catch (InstallerException e) {
14906            Slog.w(TAG, "Couldn't remove cache files for package "
14907                    + packageName + " u" + userId, e);
14908            return false;
14909        }
14910        return true;
14911    }
14912
14913    @Override
14914    public void getPackageSizeInfo(final String packageName, int userHandle,
14915            final IPackageStatsObserver observer) {
14916        mContext.enforceCallingOrSelfPermission(
14917                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14918        if (packageName == null) {
14919            throw new IllegalArgumentException("Attempt to get size of null packageName");
14920        }
14921
14922        PackageStats stats = new PackageStats(packageName, userHandle);
14923
14924        /*
14925         * Queue up an async operation since the package measurement may take a
14926         * little while.
14927         */
14928        Message msg = mHandler.obtainMessage(INIT_COPY);
14929        msg.obj = new MeasureParams(stats, observer);
14930        mHandler.sendMessage(msg);
14931    }
14932
14933    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14934            PackageStats pStats) {
14935        if (packageName == null) {
14936            Slog.w(TAG, "Attempt to get size of null packageName.");
14937            return false;
14938        }
14939        PackageParser.Package p;
14940        boolean dataOnly = false;
14941        String libDirRoot = null;
14942        String asecPath = null;
14943        PackageSetting ps = null;
14944        synchronized (mPackages) {
14945            p = mPackages.get(packageName);
14946            ps = mSettings.mPackages.get(packageName);
14947            if(p == null) {
14948                dataOnly = true;
14949                if((ps == null) || (ps.pkg == null)) {
14950                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14951                    return false;
14952                }
14953                p = ps.pkg;
14954            }
14955            if (ps != null) {
14956                libDirRoot = ps.legacyNativeLibraryPathString;
14957            }
14958            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14959                final long token = Binder.clearCallingIdentity();
14960                try {
14961                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14962                    if (secureContainerId != null) {
14963                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14964                    }
14965                } finally {
14966                    Binder.restoreCallingIdentity(token);
14967                }
14968            }
14969        }
14970        String publicSrcDir = null;
14971        if(!dataOnly) {
14972            final ApplicationInfo applicationInfo = p.applicationInfo;
14973            if (applicationInfo == null) {
14974                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14975                return false;
14976            }
14977            if (p.isForwardLocked()) {
14978                publicSrcDir = applicationInfo.getBaseResourcePath();
14979            }
14980        }
14981        // TODO: extend to measure size of split APKs
14982        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14983        // not just the first level.
14984        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14985        // just the primary.
14986        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14987
14988        String apkPath;
14989        File packageDir = new File(p.codePath);
14990
14991        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14992            apkPath = packageDir.getAbsolutePath();
14993            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14994            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14995                libDirRoot = null;
14996            }
14997        } else {
14998            apkPath = p.baseCodePath;
14999        }
15000
15001        // TODO: triage flags as part of 26466827
15002        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15003        try {
15004            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15005                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15006        } catch (InstallerException e) {
15007            return false;
15008        }
15009
15010        // Fix-up for forward-locked applications in ASEC containers.
15011        if (!isExternal(p)) {
15012            pStats.codeSize += pStats.externalCodeSize;
15013            pStats.externalCodeSize = 0L;
15014        }
15015
15016        return true;
15017    }
15018
15019
15020    @Override
15021    public void addPackageToPreferred(String packageName) {
15022        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15023    }
15024
15025    @Override
15026    public void removePackageFromPreferred(String packageName) {
15027        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15028    }
15029
15030    @Override
15031    public List<PackageInfo> getPreferredPackages(int flags) {
15032        return new ArrayList<PackageInfo>();
15033    }
15034
15035    private int getUidTargetSdkVersionLockedLPr(int uid) {
15036        Object obj = mSettings.getUserIdLPr(uid);
15037        if (obj instanceof SharedUserSetting) {
15038            final SharedUserSetting sus = (SharedUserSetting) obj;
15039            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15040            final Iterator<PackageSetting> it = sus.packages.iterator();
15041            while (it.hasNext()) {
15042                final PackageSetting ps = it.next();
15043                if (ps.pkg != null) {
15044                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15045                    if (v < vers) vers = v;
15046                }
15047            }
15048            return vers;
15049        } else if (obj instanceof PackageSetting) {
15050            final PackageSetting ps = (PackageSetting) obj;
15051            if (ps.pkg != null) {
15052                return ps.pkg.applicationInfo.targetSdkVersion;
15053            }
15054        }
15055        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15056    }
15057
15058    @Override
15059    public void addPreferredActivity(IntentFilter filter, int match,
15060            ComponentName[] set, ComponentName activity, int userId) {
15061        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15062                "Adding preferred");
15063    }
15064
15065    private void addPreferredActivityInternal(IntentFilter filter, int match,
15066            ComponentName[] set, ComponentName activity, boolean always, int userId,
15067            String opname) {
15068        // writer
15069        int callingUid = Binder.getCallingUid();
15070        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15071        if (filter.countActions() == 0) {
15072            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15073            return;
15074        }
15075        synchronized (mPackages) {
15076            if (mContext.checkCallingOrSelfPermission(
15077                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15078                    != PackageManager.PERMISSION_GRANTED) {
15079                if (getUidTargetSdkVersionLockedLPr(callingUid)
15080                        < Build.VERSION_CODES.FROYO) {
15081                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15082                            + callingUid);
15083                    return;
15084                }
15085                mContext.enforceCallingOrSelfPermission(
15086                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15087            }
15088
15089            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15090            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15091                    + userId + ":");
15092            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15093            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15094            scheduleWritePackageRestrictionsLocked(userId);
15095        }
15096    }
15097
15098    @Override
15099    public void replacePreferredActivity(IntentFilter filter, int match,
15100            ComponentName[] set, ComponentName activity, int userId) {
15101        if (filter.countActions() != 1) {
15102            throw new IllegalArgumentException(
15103                    "replacePreferredActivity expects filter to have only 1 action.");
15104        }
15105        if (filter.countDataAuthorities() != 0
15106                || filter.countDataPaths() != 0
15107                || filter.countDataSchemes() > 1
15108                || filter.countDataTypes() != 0) {
15109            throw new IllegalArgumentException(
15110                    "replacePreferredActivity expects filter to have no data authorities, " +
15111                    "paths, or types; and at most one scheme.");
15112        }
15113
15114        final int callingUid = Binder.getCallingUid();
15115        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15116        synchronized (mPackages) {
15117            if (mContext.checkCallingOrSelfPermission(
15118                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15119                    != PackageManager.PERMISSION_GRANTED) {
15120                if (getUidTargetSdkVersionLockedLPr(callingUid)
15121                        < Build.VERSION_CODES.FROYO) {
15122                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15123                            + Binder.getCallingUid());
15124                    return;
15125                }
15126                mContext.enforceCallingOrSelfPermission(
15127                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15128            }
15129
15130            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15131            if (pir != null) {
15132                // Get all of the existing entries that exactly match this filter.
15133                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15134                if (existing != null && existing.size() == 1) {
15135                    PreferredActivity cur = existing.get(0);
15136                    if (DEBUG_PREFERRED) {
15137                        Slog.i(TAG, "Checking replace of preferred:");
15138                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15139                        if (!cur.mPref.mAlways) {
15140                            Slog.i(TAG, "  -- CUR; not mAlways!");
15141                        } else {
15142                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15143                            Slog.i(TAG, "  -- CUR: mSet="
15144                                    + Arrays.toString(cur.mPref.mSetComponents));
15145                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15146                            Slog.i(TAG, "  -- NEW: mMatch="
15147                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15148                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15149                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15150                        }
15151                    }
15152                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15153                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15154                            && cur.mPref.sameSet(set)) {
15155                        // Setting the preferred activity to what it happens to be already
15156                        if (DEBUG_PREFERRED) {
15157                            Slog.i(TAG, "Replacing with same preferred activity "
15158                                    + cur.mPref.mShortComponent + " for user "
15159                                    + userId + ":");
15160                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15161                        }
15162                        return;
15163                    }
15164                }
15165
15166                if (existing != null) {
15167                    if (DEBUG_PREFERRED) {
15168                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15169                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15170                    }
15171                    for (int i = 0; i < existing.size(); i++) {
15172                        PreferredActivity pa = existing.get(i);
15173                        if (DEBUG_PREFERRED) {
15174                            Slog.i(TAG, "Removing existing preferred activity "
15175                                    + pa.mPref.mComponent + ":");
15176                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15177                        }
15178                        pir.removeFilter(pa);
15179                    }
15180                }
15181            }
15182            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15183                    "Replacing preferred");
15184        }
15185    }
15186
15187    @Override
15188    public void clearPackagePreferredActivities(String packageName) {
15189        final int uid = Binder.getCallingUid();
15190        // writer
15191        synchronized (mPackages) {
15192            PackageParser.Package pkg = mPackages.get(packageName);
15193            if (pkg == null || pkg.applicationInfo.uid != uid) {
15194                if (mContext.checkCallingOrSelfPermission(
15195                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15196                        != PackageManager.PERMISSION_GRANTED) {
15197                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15198                            < Build.VERSION_CODES.FROYO) {
15199                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15200                                + Binder.getCallingUid());
15201                        return;
15202                    }
15203                    mContext.enforceCallingOrSelfPermission(
15204                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15205                }
15206            }
15207
15208            int user = UserHandle.getCallingUserId();
15209            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15210                scheduleWritePackageRestrictionsLocked(user);
15211            }
15212        }
15213    }
15214
15215    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15216    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15217        ArrayList<PreferredActivity> removed = null;
15218        boolean changed = false;
15219        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15220            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15221            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15222            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15223                continue;
15224            }
15225            Iterator<PreferredActivity> it = pir.filterIterator();
15226            while (it.hasNext()) {
15227                PreferredActivity pa = it.next();
15228                // Mark entry for removal only if it matches the package name
15229                // and the entry is of type "always".
15230                if (packageName == null ||
15231                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15232                                && pa.mPref.mAlways)) {
15233                    if (removed == null) {
15234                        removed = new ArrayList<PreferredActivity>();
15235                    }
15236                    removed.add(pa);
15237                }
15238            }
15239            if (removed != null) {
15240                for (int j=0; j<removed.size(); j++) {
15241                    PreferredActivity pa = removed.get(j);
15242                    pir.removeFilter(pa);
15243                }
15244                changed = true;
15245            }
15246        }
15247        return changed;
15248    }
15249
15250    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15251    private void clearIntentFilterVerificationsLPw(int userId) {
15252        final int packageCount = mPackages.size();
15253        for (int i = 0; i < packageCount; i++) {
15254            PackageParser.Package pkg = mPackages.valueAt(i);
15255            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15256        }
15257    }
15258
15259    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15260    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15261        if (userId == UserHandle.USER_ALL) {
15262            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15263                    sUserManager.getUserIds())) {
15264                for (int oneUserId : sUserManager.getUserIds()) {
15265                    scheduleWritePackageRestrictionsLocked(oneUserId);
15266                }
15267            }
15268        } else {
15269            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15270                scheduleWritePackageRestrictionsLocked(userId);
15271            }
15272        }
15273    }
15274
15275    void clearDefaultBrowserIfNeeded(String packageName) {
15276        for (int oneUserId : sUserManager.getUserIds()) {
15277            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15278            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15279            if (packageName.equals(defaultBrowserPackageName)) {
15280                setDefaultBrowserPackageName(null, oneUserId);
15281            }
15282        }
15283    }
15284
15285    @Override
15286    public void resetApplicationPreferences(int userId) {
15287        mContext.enforceCallingOrSelfPermission(
15288                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15289        // writer
15290        synchronized (mPackages) {
15291            final long identity = Binder.clearCallingIdentity();
15292            try {
15293                clearPackagePreferredActivitiesLPw(null, userId);
15294                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15295                // TODO: We have to reset the default SMS and Phone. This requires
15296                // significant refactoring to keep all default apps in the package
15297                // manager (cleaner but more work) or have the services provide
15298                // callbacks to the package manager to request a default app reset.
15299                applyFactoryDefaultBrowserLPw(userId);
15300                clearIntentFilterVerificationsLPw(userId);
15301                primeDomainVerificationsLPw(userId);
15302                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15303                scheduleWritePackageRestrictionsLocked(userId);
15304            } finally {
15305                Binder.restoreCallingIdentity(identity);
15306            }
15307        }
15308    }
15309
15310    @Override
15311    public int getPreferredActivities(List<IntentFilter> outFilters,
15312            List<ComponentName> outActivities, String packageName) {
15313
15314        int num = 0;
15315        final int userId = UserHandle.getCallingUserId();
15316        // reader
15317        synchronized (mPackages) {
15318            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15319            if (pir != null) {
15320                final Iterator<PreferredActivity> it = pir.filterIterator();
15321                while (it.hasNext()) {
15322                    final PreferredActivity pa = it.next();
15323                    if (packageName == null
15324                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15325                                    && pa.mPref.mAlways)) {
15326                        if (outFilters != null) {
15327                            outFilters.add(new IntentFilter(pa));
15328                        }
15329                        if (outActivities != null) {
15330                            outActivities.add(pa.mPref.mComponent);
15331                        }
15332                    }
15333                }
15334            }
15335        }
15336
15337        return num;
15338    }
15339
15340    @Override
15341    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15342            int userId) {
15343        int callingUid = Binder.getCallingUid();
15344        if (callingUid != Process.SYSTEM_UID) {
15345            throw new SecurityException(
15346                    "addPersistentPreferredActivity can only be run by the system");
15347        }
15348        if (filter.countActions() == 0) {
15349            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15350            return;
15351        }
15352        synchronized (mPackages) {
15353            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15354                    ":");
15355            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15356            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15357                    new PersistentPreferredActivity(filter, activity));
15358            scheduleWritePackageRestrictionsLocked(userId);
15359        }
15360    }
15361
15362    @Override
15363    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15364        int callingUid = Binder.getCallingUid();
15365        if (callingUid != Process.SYSTEM_UID) {
15366            throw new SecurityException(
15367                    "clearPackagePersistentPreferredActivities can only be run by the system");
15368        }
15369        ArrayList<PersistentPreferredActivity> removed = null;
15370        boolean changed = false;
15371        synchronized (mPackages) {
15372            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15373                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15374                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15375                        .valueAt(i);
15376                if (userId != thisUserId) {
15377                    continue;
15378                }
15379                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15380                while (it.hasNext()) {
15381                    PersistentPreferredActivity ppa = it.next();
15382                    // Mark entry for removal only if it matches the package name.
15383                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15384                        if (removed == null) {
15385                            removed = new ArrayList<PersistentPreferredActivity>();
15386                        }
15387                        removed.add(ppa);
15388                    }
15389                }
15390                if (removed != null) {
15391                    for (int j=0; j<removed.size(); j++) {
15392                        PersistentPreferredActivity ppa = removed.get(j);
15393                        ppir.removeFilter(ppa);
15394                    }
15395                    changed = true;
15396                }
15397            }
15398
15399            if (changed) {
15400                scheduleWritePackageRestrictionsLocked(userId);
15401            }
15402        }
15403    }
15404
15405    /**
15406     * Common machinery for picking apart a restored XML blob and passing
15407     * it to a caller-supplied functor to be applied to the running system.
15408     */
15409    private void restoreFromXml(XmlPullParser parser, int userId,
15410            String expectedStartTag, BlobXmlRestorer functor)
15411            throws IOException, XmlPullParserException {
15412        int type;
15413        while ((type = parser.next()) != XmlPullParser.START_TAG
15414                && type != XmlPullParser.END_DOCUMENT) {
15415        }
15416        if (type != XmlPullParser.START_TAG) {
15417            // oops didn't find a start tag?!
15418            if (DEBUG_BACKUP) {
15419                Slog.e(TAG, "Didn't find start tag during restore");
15420            }
15421            return;
15422        }
15423Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15424        // this is supposed to be TAG_PREFERRED_BACKUP
15425        if (!expectedStartTag.equals(parser.getName())) {
15426            if (DEBUG_BACKUP) {
15427                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15428            }
15429            return;
15430        }
15431
15432        // skip interfering stuff, then we're aligned with the backing implementation
15433        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15434Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15435        functor.apply(parser, userId);
15436    }
15437
15438    private interface BlobXmlRestorer {
15439        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15440    }
15441
15442    /**
15443     * Non-Binder method, support for the backup/restore mechanism: write the
15444     * full set of preferred activities in its canonical XML format.  Returns the
15445     * XML output as a byte array, or null if there is none.
15446     */
15447    @Override
15448    public byte[] getPreferredActivityBackup(int userId) {
15449        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15450            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15451        }
15452
15453        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15454        try {
15455            final XmlSerializer serializer = new FastXmlSerializer();
15456            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15457            serializer.startDocument(null, true);
15458            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15459
15460            synchronized (mPackages) {
15461                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15462            }
15463
15464            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15465            serializer.endDocument();
15466            serializer.flush();
15467        } catch (Exception e) {
15468            if (DEBUG_BACKUP) {
15469                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15470            }
15471            return null;
15472        }
15473
15474        return dataStream.toByteArray();
15475    }
15476
15477    @Override
15478    public void restorePreferredActivities(byte[] backup, int userId) {
15479        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15480            throw new SecurityException("Only the system may call restorePreferredActivities()");
15481        }
15482
15483        try {
15484            final XmlPullParser parser = Xml.newPullParser();
15485            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15486            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15487                    new BlobXmlRestorer() {
15488                        @Override
15489                        public void apply(XmlPullParser parser, int userId)
15490                                throws XmlPullParserException, IOException {
15491                            synchronized (mPackages) {
15492                                mSettings.readPreferredActivitiesLPw(parser, userId);
15493                            }
15494                        }
15495                    } );
15496        } catch (Exception e) {
15497            if (DEBUG_BACKUP) {
15498                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15499            }
15500        }
15501    }
15502
15503    /**
15504     * Non-Binder method, support for the backup/restore mechanism: write the
15505     * default browser (etc) settings in its canonical XML format.  Returns the default
15506     * browser XML representation as a byte array, or null if there is none.
15507     */
15508    @Override
15509    public byte[] getDefaultAppsBackup(int userId) {
15510        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15511            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15512        }
15513
15514        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15515        try {
15516            final XmlSerializer serializer = new FastXmlSerializer();
15517            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15518            serializer.startDocument(null, true);
15519            serializer.startTag(null, TAG_DEFAULT_APPS);
15520
15521            synchronized (mPackages) {
15522                mSettings.writeDefaultAppsLPr(serializer, userId);
15523            }
15524
15525            serializer.endTag(null, TAG_DEFAULT_APPS);
15526            serializer.endDocument();
15527            serializer.flush();
15528        } catch (Exception e) {
15529            if (DEBUG_BACKUP) {
15530                Slog.e(TAG, "Unable to write default apps for backup", e);
15531            }
15532            return null;
15533        }
15534
15535        return dataStream.toByteArray();
15536    }
15537
15538    @Override
15539    public void restoreDefaultApps(byte[] backup, int userId) {
15540        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15541            throw new SecurityException("Only the system may call restoreDefaultApps()");
15542        }
15543
15544        try {
15545            final XmlPullParser parser = Xml.newPullParser();
15546            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15547            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15548                    new BlobXmlRestorer() {
15549                        @Override
15550                        public void apply(XmlPullParser parser, int userId)
15551                                throws XmlPullParserException, IOException {
15552                            synchronized (mPackages) {
15553                                mSettings.readDefaultAppsLPw(parser, userId);
15554                            }
15555                        }
15556                    } );
15557        } catch (Exception e) {
15558            if (DEBUG_BACKUP) {
15559                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15560            }
15561        }
15562    }
15563
15564    @Override
15565    public byte[] getIntentFilterVerificationBackup(int userId) {
15566        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15567            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15568        }
15569
15570        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15571        try {
15572            final XmlSerializer serializer = new FastXmlSerializer();
15573            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15574            serializer.startDocument(null, true);
15575            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15576
15577            synchronized (mPackages) {
15578                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15579            }
15580
15581            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15582            serializer.endDocument();
15583            serializer.flush();
15584        } catch (Exception e) {
15585            if (DEBUG_BACKUP) {
15586                Slog.e(TAG, "Unable to write default apps for backup", e);
15587            }
15588            return null;
15589        }
15590
15591        return dataStream.toByteArray();
15592    }
15593
15594    @Override
15595    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15596        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15597            throw new SecurityException("Only the system may call restorePreferredActivities()");
15598        }
15599
15600        try {
15601            final XmlPullParser parser = Xml.newPullParser();
15602            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15603            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15604                    new BlobXmlRestorer() {
15605                        @Override
15606                        public void apply(XmlPullParser parser, int userId)
15607                                throws XmlPullParserException, IOException {
15608                            synchronized (mPackages) {
15609                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15610                                mSettings.writeLPr();
15611                            }
15612                        }
15613                    } );
15614        } catch (Exception e) {
15615            if (DEBUG_BACKUP) {
15616                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15617            }
15618        }
15619    }
15620
15621    @Override
15622    public byte[] getPermissionGrantBackup(int userId) {
15623        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15624            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15625        }
15626
15627        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15628        try {
15629            final XmlSerializer serializer = new FastXmlSerializer();
15630            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15631            serializer.startDocument(null, true);
15632            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15633
15634            synchronized (mPackages) {
15635                serializeRuntimePermissionGrantsLPr(serializer, userId);
15636            }
15637
15638            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15639            serializer.endDocument();
15640            serializer.flush();
15641        } catch (Exception e) {
15642            if (DEBUG_BACKUP) {
15643                Slog.e(TAG, "Unable to write default apps for backup", e);
15644            }
15645            return null;
15646        }
15647
15648        return dataStream.toByteArray();
15649    }
15650
15651    @Override
15652    public void restorePermissionGrants(byte[] backup, int userId) {
15653        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15654            throw new SecurityException("Only the system may call restorePermissionGrants()");
15655        }
15656
15657        try {
15658            final XmlPullParser parser = Xml.newPullParser();
15659            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15660            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15661                    new BlobXmlRestorer() {
15662                        @Override
15663                        public void apply(XmlPullParser parser, int userId)
15664                                throws XmlPullParserException, IOException {
15665                            synchronized (mPackages) {
15666                                processRestoredPermissionGrantsLPr(parser, userId);
15667                            }
15668                        }
15669                    } );
15670        } catch (Exception e) {
15671            if (DEBUG_BACKUP) {
15672                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15673            }
15674        }
15675    }
15676
15677    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15678            throws IOException {
15679        serializer.startTag(null, TAG_ALL_GRANTS);
15680
15681        final int N = mSettings.mPackages.size();
15682        for (int i = 0; i < N; i++) {
15683            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15684            boolean pkgGrantsKnown = false;
15685
15686            PermissionsState packagePerms = ps.getPermissionsState();
15687
15688            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15689                final int grantFlags = state.getFlags();
15690                // only look at grants that are not system/policy fixed
15691                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15692                    final boolean isGranted = state.isGranted();
15693                    // And only back up the user-twiddled state bits
15694                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15695                        final String packageName = mSettings.mPackages.keyAt(i);
15696                        if (!pkgGrantsKnown) {
15697                            serializer.startTag(null, TAG_GRANT);
15698                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15699                            pkgGrantsKnown = true;
15700                        }
15701
15702                        final boolean userSet =
15703                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15704                        final boolean userFixed =
15705                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15706                        final boolean revoke =
15707                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15708
15709                        serializer.startTag(null, TAG_PERMISSION);
15710                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15711                        if (isGranted) {
15712                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15713                        }
15714                        if (userSet) {
15715                            serializer.attribute(null, ATTR_USER_SET, "true");
15716                        }
15717                        if (userFixed) {
15718                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15719                        }
15720                        if (revoke) {
15721                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15722                        }
15723                        serializer.endTag(null, TAG_PERMISSION);
15724                    }
15725                }
15726            }
15727
15728            if (pkgGrantsKnown) {
15729                serializer.endTag(null, TAG_GRANT);
15730            }
15731        }
15732
15733        serializer.endTag(null, TAG_ALL_GRANTS);
15734    }
15735
15736    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15737            throws XmlPullParserException, IOException {
15738        String pkgName = null;
15739        int outerDepth = parser.getDepth();
15740        int type;
15741        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15742                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15743            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15744                continue;
15745            }
15746
15747            final String tagName = parser.getName();
15748            if (tagName.equals(TAG_GRANT)) {
15749                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15750                if (DEBUG_BACKUP) {
15751                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15752                }
15753            } else if (tagName.equals(TAG_PERMISSION)) {
15754
15755                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15756                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15757
15758                int newFlagSet = 0;
15759                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15760                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15761                }
15762                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15763                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15764                }
15765                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15766                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15767                }
15768                if (DEBUG_BACKUP) {
15769                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15770                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15771                }
15772                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15773                if (ps != null) {
15774                    // Already installed so we apply the grant immediately
15775                    if (DEBUG_BACKUP) {
15776                        Slog.v(TAG, "        + already installed; applying");
15777                    }
15778                    PermissionsState perms = ps.getPermissionsState();
15779                    BasePermission bp = mSettings.mPermissions.get(permName);
15780                    if (bp != null) {
15781                        if (isGranted) {
15782                            perms.grantRuntimePermission(bp, userId);
15783                        }
15784                        if (newFlagSet != 0) {
15785                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15786                        }
15787                    }
15788                } else {
15789                    // Need to wait for post-restore install to apply the grant
15790                    if (DEBUG_BACKUP) {
15791                        Slog.v(TAG, "        - not yet installed; saving for later");
15792                    }
15793                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15794                            isGranted, newFlagSet, userId);
15795                }
15796            } else {
15797                PackageManagerService.reportSettingsProblem(Log.WARN,
15798                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15799                XmlUtils.skipCurrentTag(parser);
15800            }
15801        }
15802
15803        scheduleWriteSettingsLocked();
15804        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15805    }
15806
15807    @Override
15808    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15809            int sourceUserId, int targetUserId, int flags) {
15810        mContext.enforceCallingOrSelfPermission(
15811                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15812        int callingUid = Binder.getCallingUid();
15813        enforceOwnerRights(ownerPackage, callingUid);
15814        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15815        if (intentFilter.countActions() == 0) {
15816            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15817            return;
15818        }
15819        synchronized (mPackages) {
15820            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15821                    ownerPackage, targetUserId, flags);
15822            CrossProfileIntentResolver resolver =
15823                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15824            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15825            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15826            if (existing != null) {
15827                int size = existing.size();
15828                for (int i = 0; i < size; i++) {
15829                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15830                        return;
15831                    }
15832                }
15833            }
15834            resolver.addFilter(newFilter);
15835            scheduleWritePackageRestrictionsLocked(sourceUserId);
15836        }
15837    }
15838
15839    @Override
15840    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15841        mContext.enforceCallingOrSelfPermission(
15842                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15843        int callingUid = Binder.getCallingUid();
15844        enforceOwnerRights(ownerPackage, callingUid);
15845        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15846        synchronized (mPackages) {
15847            CrossProfileIntentResolver resolver =
15848                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15849            ArraySet<CrossProfileIntentFilter> set =
15850                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15851            for (CrossProfileIntentFilter filter : set) {
15852                if (filter.getOwnerPackage().equals(ownerPackage)) {
15853                    resolver.removeFilter(filter);
15854                }
15855            }
15856            scheduleWritePackageRestrictionsLocked(sourceUserId);
15857        }
15858    }
15859
15860    // Enforcing that callingUid is owning pkg on userId
15861    private void enforceOwnerRights(String pkg, int callingUid) {
15862        // The system owns everything.
15863        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15864            return;
15865        }
15866        int callingUserId = UserHandle.getUserId(callingUid);
15867        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15868        if (pi == null) {
15869            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15870                    + callingUserId);
15871        }
15872        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15873            throw new SecurityException("Calling uid " + callingUid
15874                    + " does not own package " + pkg);
15875        }
15876    }
15877
15878    @Override
15879    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15880        Intent intent = new Intent(Intent.ACTION_MAIN);
15881        intent.addCategory(Intent.CATEGORY_HOME);
15882
15883        final int callingUserId = UserHandle.getCallingUserId();
15884        List<ResolveInfo> list = queryIntentActivities(intent, null,
15885                PackageManager.GET_META_DATA, callingUserId);
15886        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15887                true, false, false, callingUserId);
15888
15889        allHomeCandidates.clear();
15890        if (list != null) {
15891            for (ResolveInfo ri : list) {
15892                allHomeCandidates.add(ri);
15893            }
15894        }
15895        return (preferred == null || preferred.activityInfo == null)
15896                ? null
15897                : new ComponentName(preferred.activityInfo.packageName,
15898                        preferred.activityInfo.name);
15899    }
15900
15901    @Override
15902    public void setApplicationEnabledSetting(String appPackageName,
15903            int newState, int flags, int userId, String callingPackage) {
15904        if (!sUserManager.exists(userId)) return;
15905        if (callingPackage == null) {
15906            callingPackage = Integer.toString(Binder.getCallingUid());
15907        }
15908        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15909    }
15910
15911    @Override
15912    public void setComponentEnabledSetting(ComponentName componentName,
15913            int newState, int flags, int userId) {
15914        if (!sUserManager.exists(userId)) return;
15915        setEnabledSetting(componentName.getPackageName(),
15916                componentName.getClassName(), newState, flags, userId, null);
15917    }
15918
15919    private void setEnabledSetting(final String packageName, String className, int newState,
15920            final int flags, int userId, String callingPackage) {
15921        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15922              || newState == COMPONENT_ENABLED_STATE_ENABLED
15923              || newState == COMPONENT_ENABLED_STATE_DISABLED
15924              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15925              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15926            throw new IllegalArgumentException("Invalid new component state: "
15927                    + newState);
15928        }
15929        PackageSetting pkgSetting;
15930        final int uid = Binder.getCallingUid();
15931        final int permission = mContext.checkCallingOrSelfPermission(
15932                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15933        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15934        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15935        boolean sendNow = false;
15936        boolean isApp = (className == null);
15937        String componentName = isApp ? packageName : className;
15938        int packageUid = -1;
15939        ArrayList<String> components;
15940
15941        // writer
15942        synchronized (mPackages) {
15943            pkgSetting = mSettings.mPackages.get(packageName);
15944            if (pkgSetting == null) {
15945                if (className == null) {
15946                    throw new IllegalArgumentException("Unknown package: " + packageName);
15947                }
15948                throw new IllegalArgumentException(
15949                        "Unknown component: " + packageName + "/" + className);
15950            }
15951            // Allow root and verify that userId is not being specified by a different user
15952            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15953                throw new SecurityException(
15954                        "Permission Denial: attempt to change component state from pid="
15955                        + Binder.getCallingPid()
15956                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15957            }
15958            if (className == null) {
15959                // We're dealing with an application/package level state change
15960                if (pkgSetting.getEnabled(userId) == newState) {
15961                    // Nothing to do
15962                    return;
15963                }
15964                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15965                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15966                    // Don't care about who enables an app.
15967                    callingPackage = null;
15968                }
15969                pkgSetting.setEnabled(newState, userId, callingPackage);
15970                // pkgSetting.pkg.mSetEnabled = newState;
15971            } else {
15972                // We're dealing with a component level state change
15973                // First, verify that this is a valid class name.
15974                PackageParser.Package pkg = pkgSetting.pkg;
15975                if (pkg == null || !pkg.hasComponentClassName(className)) {
15976                    if (pkg != null &&
15977                            pkg.applicationInfo.targetSdkVersion >=
15978                                    Build.VERSION_CODES.JELLY_BEAN) {
15979                        throw new IllegalArgumentException("Component class " + className
15980                                + " does not exist in " + packageName);
15981                    } else {
15982                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15983                                + className + " does not exist in " + packageName);
15984                    }
15985                }
15986                switch (newState) {
15987                case COMPONENT_ENABLED_STATE_ENABLED:
15988                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15989                        return;
15990                    }
15991                    break;
15992                case COMPONENT_ENABLED_STATE_DISABLED:
15993                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15994                        return;
15995                    }
15996                    break;
15997                case COMPONENT_ENABLED_STATE_DEFAULT:
15998                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15999                        return;
16000                    }
16001                    break;
16002                default:
16003                    Slog.e(TAG, "Invalid new component state: " + newState);
16004                    return;
16005                }
16006            }
16007            scheduleWritePackageRestrictionsLocked(userId);
16008            components = mPendingBroadcasts.get(userId, packageName);
16009            final boolean newPackage = components == null;
16010            if (newPackage) {
16011                components = new ArrayList<String>();
16012            }
16013            if (!components.contains(componentName)) {
16014                components.add(componentName);
16015            }
16016            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16017                sendNow = true;
16018                // Purge entry from pending broadcast list if another one exists already
16019                // since we are sending one right away.
16020                mPendingBroadcasts.remove(userId, packageName);
16021            } else {
16022                if (newPackage) {
16023                    mPendingBroadcasts.put(userId, packageName, components);
16024                }
16025                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16026                    // Schedule a message
16027                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16028                }
16029            }
16030        }
16031
16032        long callingId = Binder.clearCallingIdentity();
16033        try {
16034            if (sendNow) {
16035                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16036                sendPackageChangedBroadcast(packageName,
16037                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16038            }
16039        } finally {
16040            Binder.restoreCallingIdentity(callingId);
16041        }
16042    }
16043
16044    private void sendPackageChangedBroadcast(String packageName,
16045            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16046        if (DEBUG_INSTALL)
16047            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16048                    + componentNames);
16049        Bundle extras = new Bundle(4);
16050        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16051        String nameList[] = new String[componentNames.size()];
16052        componentNames.toArray(nameList);
16053        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16054        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16055        extras.putInt(Intent.EXTRA_UID, packageUid);
16056        // If this is not reporting a change of the overall package, then only send it
16057        // to registered receivers.  We don't want to launch a swath of apps for every
16058        // little component state change.
16059        final int flags = !componentNames.contains(packageName)
16060                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16061        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16062                new int[] {UserHandle.getUserId(packageUid)});
16063    }
16064
16065    @Override
16066    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16067        if (!sUserManager.exists(userId)) return;
16068        final int uid = Binder.getCallingUid();
16069        final int permission = mContext.checkCallingOrSelfPermission(
16070                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16071        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16072        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16073        // writer
16074        synchronized (mPackages) {
16075            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16076                    allowedByPermission, uid, userId)) {
16077                scheduleWritePackageRestrictionsLocked(userId);
16078            }
16079        }
16080    }
16081
16082    @Override
16083    public String getInstallerPackageName(String packageName) {
16084        // reader
16085        synchronized (mPackages) {
16086            return mSettings.getInstallerPackageNameLPr(packageName);
16087        }
16088    }
16089
16090    @Override
16091    public int getApplicationEnabledSetting(String packageName, int userId) {
16092        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16093        int uid = Binder.getCallingUid();
16094        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16095        // reader
16096        synchronized (mPackages) {
16097            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16098        }
16099    }
16100
16101    @Override
16102    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16103        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16104        int uid = Binder.getCallingUid();
16105        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16106        // reader
16107        synchronized (mPackages) {
16108            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16109        }
16110    }
16111
16112    @Override
16113    public void enterSafeMode() {
16114        enforceSystemOrRoot("Only the system can request entering safe mode");
16115
16116        if (!mSystemReady) {
16117            mSafeMode = true;
16118        }
16119    }
16120
16121    @Override
16122    public void systemReady() {
16123        mSystemReady = true;
16124
16125        // Read the compatibilty setting when the system is ready.
16126        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16127                mContext.getContentResolver(),
16128                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16129        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16130        if (DEBUG_SETTINGS) {
16131            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16132        }
16133
16134        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16135
16136        synchronized (mPackages) {
16137            // Verify that all of the preferred activity components actually
16138            // exist.  It is possible for applications to be updated and at
16139            // that point remove a previously declared activity component that
16140            // had been set as a preferred activity.  We try to clean this up
16141            // the next time we encounter that preferred activity, but it is
16142            // possible for the user flow to never be able to return to that
16143            // situation so here we do a sanity check to make sure we haven't
16144            // left any junk around.
16145            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16146            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16147                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16148                removed.clear();
16149                for (PreferredActivity pa : pir.filterSet()) {
16150                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16151                        removed.add(pa);
16152                    }
16153                }
16154                if (removed.size() > 0) {
16155                    for (int r=0; r<removed.size(); r++) {
16156                        PreferredActivity pa = removed.get(r);
16157                        Slog.w(TAG, "Removing dangling preferred activity: "
16158                                + pa.mPref.mComponent);
16159                        pir.removeFilter(pa);
16160                    }
16161                    mSettings.writePackageRestrictionsLPr(
16162                            mSettings.mPreferredActivities.keyAt(i));
16163                }
16164            }
16165
16166            for (int userId : UserManagerService.getInstance().getUserIds()) {
16167                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16168                    grantPermissionsUserIds = ArrayUtils.appendInt(
16169                            grantPermissionsUserIds, userId);
16170                }
16171            }
16172        }
16173        sUserManager.systemReady();
16174
16175        // If we upgraded grant all default permissions before kicking off.
16176        for (int userId : grantPermissionsUserIds) {
16177            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16178        }
16179
16180        // Kick off any messages waiting for system ready
16181        if (mPostSystemReadyMessages != null) {
16182            for (Message msg : mPostSystemReadyMessages) {
16183                msg.sendToTarget();
16184            }
16185            mPostSystemReadyMessages = null;
16186        }
16187
16188        // Watch for external volumes that come and go over time
16189        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16190        storage.registerListener(mStorageListener);
16191
16192        mInstallerService.systemReady();
16193        mPackageDexOptimizer.systemReady();
16194
16195        MountServiceInternal mountServiceInternal = LocalServices.getService(
16196                MountServiceInternal.class);
16197        mountServiceInternal.addExternalStoragePolicy(
16198                new MountServiceInternal.ExternalStorageMountPolicy() {
16199            @Override
16200            public int getMountMode(int uid, String packageName) {
16201                if (Process.isIsolated(uid)) {
16202                    return Zygote.MOUNT_EXTERNAL_NONE;
16203                }
16204                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16205                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16206                }
16207                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16208                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16209                }
16210                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16211                    return Zygote.MOUNT_EXTERNAL_READ;
16212                }
16213                return Zygote.MOUNT_EXTERNAL_WRITE;
16214            }
16215
16216            @Override
16217            public boolean hasExternalStorage(int uid, String packageName) {
16218                return true;
16219            }
16220        });
16221    }
16222
16223    @Override
16224    public boolean isSafeMode() {
16225        return mSafeMode;
16226    }
16227
16228    @Override
16229    public boolean hasSystemUidErrors() {
16230        return mHasSystemUidErrors;
16231    }
16232
16233    static String arrayToString(int[] array) {
16234        StringBuffer buf = new StringBuffer(128);
16235        buf.append('[');
16236        if (array != null) {
16237            for (int i=0; i<array.length; i++) {
16238                if (i > 0) buf.append(", ");
16239                buf.append(array[i]);
16240            }
16241        }
16242        buf.append(']');
16243        return buf.toString();
16244    }
16245
16246    static class DumpState {
16247        public static final int DUMP_LIBS = 1 << 0;
16248        public static final int DUMP_FEATURES = 1 << 1;
16249        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16250        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16251        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16252        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16253        public static final int DUMP_PERMISSIONS = 1 << 6;
16254        public static final int DUMP_PACKAGES = 1 << 7;
16255        public static final int DUMP_SHARED_USERS = 1 << 8;
16256        public static final int DUMP_MESSAGES = 1 << 9;
16257        public static final int DUMP_PROVIDERS = 1 << 10;
16258        public static final int DUMP_VERIFIERS = 1 << 11;
16259        public static final int DUMP_PREFERRED = 1 << 12;
16260        public static final int DUMP_PREFERRED_XML = 1 << 13;
16261        public static final int DUMP_KEYSETS = 1 << 14;
16262        public static final int DUMP_VERSION = 1 << 15;
16263        public static final int DUMP_INSTALLS = 1 << 16;
16264        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16265        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16266
16267        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16268
16269        private int mTypes;
16270
16271        private int mOptions;
16272
16273        private boolean mTitlePrinted;
16274
16275        private SharedUserSetting mSharedUser;
16276
16277        public boolean isDumping(int type) {
16278            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16279                return true;
16280            }
16281
16282            return (mTypes & type) != 0;
16283        }
16284
16285        public void setDump(int type) {
16286            mTypes |= type;
16287        }
16288
16289        public boolean isOptionEnabled(int option) {
16290            return (mOptions & option) != 0;
16291        }
16292
16293        public void setOptionEnabled(int option) {
16294            mOptions |= option;
16295        }
16296
16297        public boolean onTitlePrinted() {
16298            final boolean printed = mTitlePrinted;
16299            mTitlePrinted = true;
16300            return printed;
16301        }
16302
16303        public boolean getTitlePrinted() {
16304            return mTitlePrinted;
16305        }
16306
16307        public void setTitlePrinted(boolean enabled) {
16308            mTitlePrinted = enabled;
16309        }
16310
16311        public SharedUserSetting getSharedUser() {
16312            return mSharedUser;
16313        }
16314
16315        public void setSharedUser(SharedUserSetting user) {
16316            mSharedUser = user;
16317        }
16318    }
16319
16320    @Override
16321    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16322            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16323        (new PackageManagerShellCommand(this)).exec(
16324                this, in, out, err, args, resultReceiver);
16325    }
16326
16327    @Override
16328    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16329        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16330                != PackageManager.PERMISSION_GRANTED) {
16331            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16332                    + Binder.getCallingPid()
16333                    + ", uid=" + Binder.getCallingUid()
16334                    + " without permission "
16335                    + android.Manifest.permission.DUMP);
16336            return;
16337        }
16338
16339        DumpState dumpState = new DumpState();
16340        boolean fullPreferred = false;
16341        boolean checkin = false;
16342
16343        String packageName = null;
16344        ArraySet<String> permissionNames = null;
16345
16346        int opti = 0;
16347        while (opti < args.length) {
16348            String opt = args[opti];
16349            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16350                break;
16351            }
16352            opti++;
16353
16354            if ("-a".equals(opt)) {
16355                // Right now we only know how to print all.
16356            } else if ("-h".equals(opt)) {
16357                pw.println("Package manager dump options:");
16358                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16359                pw.println("    --checkin: dump for a checkin");
16360                pw.println("    -f: print details of intent filters");
16361                pw.println("    -h: print this help");
16362                pw.println("  cmd may be one of:");
16363                pw.println("    l[ibraries]: list known shared libraries");
16364                pw.println("    f[eatures]: list device features");
16365                pw.println("    k[eysets]: print known keysets");
16366                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16367                pw.println("    perm[issions]: dump permissions");
16368                pw.println("    permission [name ...]: dump declaration and use of given permission");
16369                pw.println("    pref[erred]: print preferred package settings");
16370                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16371                pw.println("    prov[iders]: dump content providers");
16372                pw.println("    p[ackages]: dump installed packages");
16373                pw.println("    s[hared-users]: dump shared user IDs");
16374                pw.println("    m[essages]: print collected runtime messages");
16375                pw.println("    v[erifiers]: print package verifier info");
16376                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16377                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16378                pw.println("    version: print database version info");
16379                pw.println("    write: write current settings now");
16380                pw.println("    installs: details about install sessions");
16381                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16382                pw.println("    <package.name>: info about given package");
16383                return;
16384            } else if ("--checkin".equals(opt)) {
16385                checkin = true;
16386            } else if ("-f".equals(opt)) {
16387                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16388            } else {
16389                pw.println("Unknown argument: " + opt + "; use -h for help");
16390            }
16391        }
16392
16393        // Is the caller requesting to dump a particular piece of data?
16394        if (opti < args.length) {
16395            String cmd = args[opti];
16396            opti++;
16397            // Is this a package name?
16398            if ("android".equals(cmd) || cmd.contains(".")) {
16399                packageName = cmd;
16400                // When dumping a single package, we always dump all of its
16401                // filter information since the amount of data will be reasonable.
16402                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16403            } else if ("check-permission".equals(cmd)) {
16404                if (opti >= args.length) {
16405                    pw.println("Error: check-permission missing permission argument");
16406                    return;
16407                }
16408                String perm = args[opti];
16409                opti++;
16410                if (opti >= args.length) {
16411                    pw.println("Error: check-permission missing package argument");
16412                    return;
16413                }
16414                String pkg = args[opti];
16415                opti++;
16416                int user = UserHandle.getUserId(Binder.getCallingUid());
16417                if (opti < args.length) {
16418                    try {
16419                        user = Integer.parseInt(args[opti]);
16420                    } catch (NumberFormatException e) {
16421                        pw.println("Error: check-permission user argument is not a number: "
16422                                + args[opti]);
16423                        return;
16424                    }
16425                }
16426                pw.println(checkPermission(perm, pkg, user));
16427                return;
16428            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16429                dumpState.setDump(DumpState.DUMP_LIBS);
16430            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16431                dumpState.setDump(DumpState.DUMP_FEATURES);
16432            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16433                if (opti >= args.length) {
16434                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16435                            | DumpState.DUMP_SERVICE_RESOLVERS
16436                            | DumpState.DUMP_RECEIVER_RESOLVERS
16437                            | DumpState.DUMP_CONTENT_RESOLVERS);
16438                } else {
16439                    while (opti < args.length) {
16440                        String name = args[opti];
16441                        if ("a".equals(name) || "activity".equals(name)) {
16442                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16443                        } else if ("s".equals(name) || "service".equals(name)) {
16444                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16445                        } else if ("r".equals(name) || "receiver".equals(name)) {
16446                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16447                        } else if ("c".equals(name) || "content".equals(name)) {
16448                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16449                        } else {
16450                            pw.println("Error: unknown resolver table type: " + name);
16451                            return;
16452                        }
16453                        opti++;
16454                    }
16455                }
16456            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16457                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16458            } else if ("permission".equals(cmd)) {
16459                if (opti >= args.length) {
16460                    pw.println("Error: permission requires permission name");
16461                    return;
16462                }
16463                permissionNames = new ArraySet<>();
16464                while (opti < args.length) {
16465                    permissionNames.add(args[opti]);
16466                    opti++;
16467                }
16468                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16469                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16470            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16471                dumpState.setDump(DumpState.DUMP_PREFERRED);
16472            } else if ("preferred-xml".equals(cmd)) {
16473                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16474                if (opti < args.length && "--full".equals(args[opti])) {
16475                    fullPreferred = true;
16476                    opti++;
16477                }
16478            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16479                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16480            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16481                dumpState.setDump(DumpState.DUMP_PACKAGES);
16482            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16483                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16484            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16485                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16486            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16487                dumpState.setDump(DumpState.DUMP_MESSAGES);
16488            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16489                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16490            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16491                    || "intent-filter-verifiers".equals(cmd)) {
16492                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16493            } else if ("version".equals(cmd)) {
16494                dumpState.setDump(DumpState.DUMP_VERSION);
16495            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16496                dumpState.setDump(DumpState.DUMP_KEYSETS);
16497            } else if ("installs".equals(cmd)) {
16498                dumpState.setDump(DumpState.DUMP_INSTALLS);
16499            } else if ("write".equals(cmd)) {
16500                synchronized (mPackages) {
16501                    mSettings.writeLPr();
16502                    pw.println("Settings written.");
16503                    return;
16504                }
16505            }
16506        }
16507
16508        if (checkin) {
16509            pw.println("vers,1");
16510        }
16511
16512        // reader
16513        synchronized (mPackages) {
16514            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16515                if (!checkin) {
16516                    if (dumpState.onTitlePrinted())
16517                        pw.println();
16518                    pw.println("Database versions:");
16519                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16520                }
16521            }
16522
16523            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16524                if (!checkin) {
16525                    if (dumpState.onTitlePrinted())
16526                        pw.println();
16527                    pw.println("Verifiers:");
16528                    pw.print("  Required: ");
16529                    pw.print(mRequiredVerifierPackage);
16530                    pw.print(" (uid=");
16531                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16532                            UserHandle.USER_SYSTEM));
16533                    pw.println(")");
16534                } else if (mRequiredVerifierPackage != null) {
16535                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16536                    pw.print(",");
16537                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16538                            UserHandle.USER_SYSTEM));
16539                }
16540            }
16541
16542            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16543                    packageName == null) {
16544                if (mIntentFilterVerifierComponent != null) {
16545                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16546                    if (!checkin) {
16547                        if (dumpState.onTitlePrinted())
16548                            pw.println();
16549                        pw.println("Intent Filter Verifier:");
16550                        pw.print("  Using: ");
16551                        pw.print(verifierPackageName);
16552                        pw.print(" (uid=");
16553                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16554                                UserHandle.USER_SYSTEM));
16555                        pw.println(")");
16556                    } else if (verifierPackageName != null) {
16557                        pw.print("ifv,"); pw.print(verifierPackageName);
16558                        pw.print(",");
16559                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16560                                UserHandle.USER_SYSTEM));
16561                    }
16562                } else {
16563                    pw.println();
16564                    pw.println("No Intent Filter Verifier available!");
16565                }
16566            }
16567
16568            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16569                boolean printedHeader = false;
16570                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16571                while (it.hasNext()) {
16572                    String name = it.next();
16573                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16574                    if (!checkin) {
16575                        if (!printedHeader) {
16576                            if (dumpState.onTitlePrinted())
16577                                pw.println();
16578                            pw.println("Libraries:");
16579                            printedHeader = true;
16580                        }
16581                        pw.print("  ");
16582                    } else {
16583                        pw.print("lib,");
16584                    }
16585                    pw.print(name);
16586                    if (!checkin) {
16587                        pw.print(" -> ");
16588                    }
16589                    if (ent.path != null) {
16590                        if (!checkin) {
16591                            pw.print("(jar) ");
16592                            pw.print(ent.path);
16593                        } else {
16594                            pw.print(",jar,");
16595                            pw.print(ent.path);
16596                        }
16597                    } else {
16598                        if (!checkin) {
16599                            pw.print("(apk) ");
16600                            pw.print(ent.apk);
16601                        } else {
16602                            pw.print(",apk,");
16603                            pw.print(ent.apk);
16604                        }
16605                    }
16606                    pw.println();
16607                }
16608            }
16609
16610            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16611                if (dumpState.onTitlePrinted())
16612                    pw.println();
16613                if (!checkin) {
16614                    pw.println("Features:");
16615                }
16616                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16617                while (it.hasNext()) {
16618                    String name = it.next();
16619                    if (!checkin) {
16620                        pw.print("  ");
16621                    } else {
16622                        pw.print("feat,");
16623                    }
16624                    pw.println(name);
16625                }
16626            }
16627
16628            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16629                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16630                        : "Activity Resolver Table:", "  ", packageName,
16631                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16632                    dumpState.setTitlePrinted(true);
16633                }
16634            }
16635            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16636                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16637                        : "Receiver Resolver Table:", "  ", packageName,
16638                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16639                    dumpState.setTitlePrinted(true);
16640                }
16641            }
16642            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16643                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16644                        : "Service Resolver Table:", "  ", packageName,
16645                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16646                    dumpState.setTitlePrinted(true);
16647                }
16648            }
16649            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16650                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16651                        : "Provider Resolver Table:", "  ", packageName,
16652                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16653                    dumpState.setTitlePrinted(true);
16654                }
16655            }
16656
16657            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16658                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16659                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16660                    int user = mSettings.mPreferredActivities.keyAt(i);
16661                    if (pir.dump(pw,
16662                            dumpState.getTitlePrinted()
16663                                ? "\nPreferred Activities User " + user + ":"
16664                                : "Preferred Activities User " + user + ":", "  ",
16665                            packageName, true, false)) {
16666                        dumpState.setTitlePrinted(true);
16667                    }
16668                }
16669            }
16670
16671            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16672                pw.flush();
16673                FileOutputStream fout = new FileOutputStream(fd);
16674                BufferedOutputStream str = new BufferedOutputStream(fout);
16675                XmlSerializer serializer = new FastXmlSerializer();
16676                try {
16677                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16678                    serializer.startDocument(null, true);
16679                    serializer.setFeature(
16680                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16681                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16682                    serializer.endDocument();
16683                    serializer.flush();
16684                } catch (IllegalArgumentException e) {
16685                    pw.println("Failed writing: " + e);
16686                } catch (IllegalStateException e) {
16687                    pw.println("Failed writing: " + e);
16688                } catch (IOException e) {
16689                    pw.println("Failed writing: " + e);
16690                }
16691            }
16692
16693            if (!checkin
16694                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16695                    && packageName == null) {
16696                pw.println();
16697                int count = mSettings.mPackages.size();
16698                if (count == 0) {
16699                    pw.println("No applications!");
16700                    pw.println();
16701                } else {
16702                    final String prefix = "  ";
16703                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16704                    if (allPackageSettings.size() == 0) {
16705                        pw.println("No domain preferred apps!");
16706                        pw.println();
16707                    } else {
16708                        pw.println("App verification status:");
16709                        pw.println();
16710                        count = 0;
16711                        for (PackageSetting ps : allPackageSettings) {
16712                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16713                            if (ivi == null || ivi.getPackageName() == null) continue;
16714                            pw.println(prefix + "Package: " + ivi.getPackageName());
16715                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16716                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16717                            pw.println();
16718                            count++;
16719                        }
16720                        if (count == 0) {
16721                            pw.println(prefix + "No app verification established.");
16722                            pw.println();
16723                        }
16724                        for (int userId : sUserManager.getUserIds()) {
16725                            pw.println("App linkages for user " + userId + ":");
16726                            pw.println();
16727                            count = 0;
16728                            for (PackageSetting ps : allPackageSettings) {
16729                                final long status = ps.getDomainVerificationStatusForUser(userId);
16730                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16731                                    continue;
16732                                }
16733                                pw.println(prefix + "Package: " + ps.name);
16734                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16735                                String statusStr = IntentFilterVerificationInfo.
16736                                        getStatusStringFromValue(status);
16737                                pw.println(prefix + "Status:  " + statusStr);
16738                                pw.println();
16739                                count++;
16740                            }
16741                            if (count == 0) {
16742                                pw.println(prefix + "No configured app linkages.");
16743                                pw.println();
16744                            }
16745                        }
16746                    }
16747                }
16748            }
16749
16750            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16751                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16752                if (packageName == null && permissionNames == null) {
16753                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16754                        if (iperm == 0) {
16755                            if (dumpState.onTitlePrinted())
16756                                pw.println();
16757                            pw.println("AppOp Permissions:");
16758                        }
16759                        pw.print("  AppOp Permission ");
16760                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16761                        pw.println(":");
16762                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16763                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16764                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16765                        }
16766                    }
16767                }
16768            }
16769
16770            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16771                boolean printedSomething = false;
16772                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16773                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16774                        continue;
16775                    }
16776                    if (!printedSomething) {
16777                        if (dumpState.onTitlePrinted())
16778                            pw.println();
16779                        pw.println("Registered ContentProviders:");
16780                        printedSomething = true;
16781                    }
16782                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16783                    pw.print("    "); pw.println(p.toString());
16784                }
16785                printedSomething = false;
16786                for (Map.Entry<String, PackageParser.Provider> entry :
16787                        mProvidersByAuthority.entrySet()) {
16788                    PackageParser.Provider p = entry.getValue();
16789                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16790                        continue;
16791                    }
16792                    if (!printedSomething) {
16793                        if (dumpState.onTitlePrinted())
16794                            pw.println();
16795                        pw.println("ContentProvider Authorities:");
16796                        printedSomething = true;
16797                    }
16798                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16799                    pw.print("    "); pw.println(p.toString());
16800                    if (p.info != null && p.info.applicationInfo != null) {
16801                        final String appInfo = p.info.applicationInfo.toString();
16802                        pw.print("      applicationInfo="); pw.println(appInfo);
16803                    }
16804                }
16805            }
16806
16807            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16808                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16809            }
16810
16811            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16812                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16813            }
16814
16815            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16816                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16817            }
16818
16819            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16820                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16821            }
16822
16823            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16824                // XXX should handle packageName != null by dumping only install data that
16825                // the given package is involved with.
16826                if (dumpState.onTitlePrinted()) pw.println();
16827                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16828            }
16829
16830            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16831                if (dumpState.onTitlePrinted()) pw.println();
16832                mSettings.dumpReadMessagesLPr(pw, dumpState);
16833
16834                pw.println();
16835                pw.println("Package warning messages:");
16836                BufferedReader in = null;
16837                String line = null;
16838                try {
16839                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16840                    while ((line = in.readLine()) != null) {
16841                        if (line.contains("ignored: updated version")) continue;
16842                        pw.println(line);
16843                    }
16844                } catch (IOException ignored) {
16845                } finally {
16846                    IoUtils.closeQuietly(in);
16847                }
16848            }
16849
16850            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16851                BufferedReader in = null;
16852                String line = null;
16853                try {
16854                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16855                    while ((line = in.readLine()) != null) {
16856                        if (line.contains("ignored: updated version")) continue;
16857                        pw.print("msg,");
16858                        pw.println(line);
16859                    }
16860                } catch (IOException ignored) {
16861                } finally {
16862                    IoUtils.closeQuietly(in);
16863                }
16864            }
16865        }
16866    }
16867
16868    private String dumpDomainString(String packageName) {
16869        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16870        List<IntentFilter> filters = getAllIntentFilters(packageName);
16871
16872        ArraySet<String> result = new ArraySet<>();
16873        if (iviList.size() > 0) {
16874            for (IntentFilterVerificationInfo ivi : iviList) {
16875                for (String host : ivi.getDomains()) {
16876                    result.add(host);
16877                }
16878            }
16879        }
16880        if (filters != null && filters.size() > 0) {
16881            for (IntentFilter filter : filters) {
16882                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16883                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16884                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16885                    result.addAll(filter.getHostsList());
16886                }
16887            }
16888        }
16889
16890        StringBuilder sb = new StringBuilder(result.size() * 16);
16891        for (String domain : result) {
16892            if (sb.length() > 0) sb.append(" ");
16893            sb.append(domain);
16894        }
16895        return sb.toString();
16896    }
16897
16898    // ------- apps on sdcard specific code -------
16899    static final boolean DEBUG_SD_INSTALL = false;
16900
16901    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16902
16903    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16904
16905    private boolean mMediaMounted = false;
16906
16907    static String getEncryptKey() {
16908        try {
16909            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16910                    SD_ENCRYPTION_KEYSTORE_NAME);
16911            if (sdEncKey == null) {
16912                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16913                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16914                if (sdEncKey == null) {
16915                    Slog.e(TAG, "Failed to create encryption keys");
16916                    return null;
16917                }
16918            }
16919            return sdEncKey;
16920        } catch (NoSuchAlgorithmException nsae) {
16921            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16922            return null;
16923        } catch (IOException ioe) {
16924            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16925            return null;
16926        }
16927    }
16928
16929    /*
16930     * Update media status on PackageManager.
16931     */
16932    @Override
16933    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16934        int callingUid = Binder.getCallingUid();
16935        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16936            throw new SecurityException("Media status can only be updated by the system");
16937        }
16938        // reader; this apparently protects mMediaMounted, but should probably
16939        // be a different lock in that case.
16940        synchronized (mPackages) {
16941            Log.i(TAG, "Updating external media status from "
16942                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16943                    + (mediaStatus ? "mounted" : "unmounted"));
16944            if (DEBUG_SD_INSTALL)
16945                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16946                        + ", mMediaMounted=" + mMediaMounted);
16947            if (mediaStatus == mMediaMounted) {
16948                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16949                        : 0, -1);
16950                mHandler.sendMessage(msg);
16951                return;
16952            }
16953            mMediaMounted = mediaStatus;
16954        }
16955        // Queue up an async operation since the package installation may take a
16956        // little while.
16957        mHandler.post(new Runnable() {
16958            public void run() {
16959                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16960            }
16961        });
16962    }
16963
16964    /**
16965     * Called by MountService when the initial ASECs to scan are available.
16966     * Should block until all the ASEC containers are finished being scanned.
16967     */
16968    public void scanAvailableAsecs() {
16969        updateExternalMediaStatusInner(true, false, false);
16970    }
16971
16972    /*
16973     * Collect information of applications on external media, map them against
16974     * existing containers and update information based on current mount status.
16975     * Please note that we always have to report status if reportStatus has been
16976     * set to true especially when unloading packages.
16977     */
16978    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16979            boolean externalStorage) {
16980        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16981        int[] uidArr = EmptyArray.INT;
16982
16983        final String[] list = PackageHelper.getSecureContainerList();
16984        if (ArrayUtils.isEmpty(list)) {
16985            Log.i(TAG, "No secure containers found");
16986        } else {
16987            // Process list of secure containers and categorize them
16988            // as active or stale based on their package internal state.
16989
16990            // reader
16991            synchronized (mPackages) {
16992                for (String cid : list) {
16993                    // Leave stages untouched for now; installer service owns them
16994                    if (PackageInstallerService.isStageName(cid)) continue;
16995
16996                    if (DEBUG_SD_INSTALL)
16997                        Log.i(TAG, "Processing container " + cid);
16998                    String pkgName = getAsecPackageName(cid);
16999                    if (pkgName == null) {
17000                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17001                        continue;
17002                    }
17003                    if (DEBUG_SD_INSTALL)
17004                        Log.i(TAG, "Looking for pkg : " + pkgName);
17005
17006                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17007                    if (ps == null) {
17008                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17009                        continue;
17010                    }
17011
17012                    /*
17013                     * Skip packages that are not external if we're unmounting
17014                     * external storage.
17015                     */
17016                    if (externalStorage && !isMounted && !isExternal(ps)) {
17017                        continue;
17018                    }
17019
17020                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17021                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17022                    // The package status is changed only if the code path
17023                    // matches between settings and the container id.
17024                    if (ps.codePathString != null
17025                            && ps.codePathString.startsWith(args.getCodePath())) {
17026                        if (DEBUG_SD_INSTALL) {
17027                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17028                                    + " at code path: " + ps.codePathString);
17029                        }
17030
17031                        // We do have a valid package installed on sdcard
17032                        processCids.put(args, ps.codePathString);
17033                        final int uid = ps.appId;
17034                        if (uid != -1) {
17035                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17036                        }
17037                    } else {
17038                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17039                                + ps.codePathString);
17040                    }
17041                }
17042            }
17043
17044            Arrays.sort(uidArr);
17045        }
17046
17047        // Process packages with valid entries.
17048        if (isMounted) {
17049            if (DEBUG_SD_INSTALL)
17050                Log.i(TAG, "Loading packages");
17051            loadMediaPackages(processCids, uidArr, externalStorage);
17052            startCleaningPackages();
17053            mInstallerService.onSecureContainersAvailable();
17054        } else {
17055            if (DEBUG_SD_INSTALL)
17056                Log.i(TAG, "Unloading packages");
17057            unloadMediaPackages(processCids, uidArr, reportStatus);
17058        }
17059    }
17060
17061    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17062            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17063        final int size = infos.size();
17064        final String[] packageNames = new String[size];
17065        final int[] packageUids = new int[size];
17066        for (int i = 0; i < size; i++) {
17067            final ApplicationInfo info = infos.get(i);
17068            packageNames[i] = info.packageName;
17069            packageUids[i] = info.uid;
17070        }
17071        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17072                finishedReceiver);
17073    }
17074
17075    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17076            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17077        sendResourcesChangedBroadcast(mediaStatus, replacing,
17078                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17079    }
17080
17081    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17082            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17083        int size = pkgList.length;
17084        if (size > 0) {
17085            // Send broadcasts here
17086            Bundle extras = new Bundle();
17087            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17088            if (uidArr != null) {
17089                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17090            }
17091            if (replacing) {
17092                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17093            }
17094            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17095                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17096            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17097        }
17098    }
17099
17100   /*
17101     * Look at potentially valid container ids from processCids If package
17102     * information doesn't match the one on record or package scanning fails,
17103     * the cid is added to list of removeCids. We currently don't delete stale
17104     * containers.
17105     */
17106    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17107            boolean externalStorage) {
17108        ArrayList<String> pkgList = new ArrayList<String>();
17109        Set<AsecInstallArgs> keys = processCids.keySet();
17110
17111        for (AsecInstallArgs args : keys) {
17112            String codePath = processCids.get(args);
17113            if (DEBUG_SD_INSTALL)
17114                Log.i(TAG, "Loading container : " + args.cid);
17115            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17116            try {
17117                // Make sure there are no container errors first.
17118                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17119                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17120                            + " when installing from sdcard");
17121                    continue;
17122                }
17123                // Check code path here.
17124                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17125                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17126                            + " does not match one in settings " + codePath);
17127                    continue;
17128                }
17129                // Parse package
17130                int parseFlags = mDefParseFlags;
17131                if (args.isExternalAsec()) {
17132                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17133                }
17134                if (args.isFwdLocked()) {
17135                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17136                }
17137
17138                synchronized (mInstallLock) {
17139                    PackageParser.Package pkg = null;
17140                    try {
17141                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17142                    } catch (PackageManagerException e) {
17143                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17144                    }
17145                    // Scan the package
17146                    if (pkg != null) {
17147                        /*
17148                         * TODO why is the lock being held? doPostInstall is
17149                         * called in other places without the lock. This needs
17150                         * to be straightened out.
17151                         */
17152                        // writer
17153                        synchronized (mPackages) {
17154                            retCode = PackageManager.INSTALL_SUCCEEDED;
17155                            pkgList.add(pkg.packageName);
17156                            // Post process args
17157                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17158                                    pkg.applicationInfo.uid);
17159                        }
17160                    } else {
17161                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17162                    }
17163                }
17164
17165            } finally {
17166                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17167                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17168                }
17169            }
17170        }
17171        // writer
17172        synchronized (mPackages) {
17173            // If the platform SDK has changed since the last time we booted,
17174            // we need to re-grant app permission to catch any new ones that
17175            // appear. This is really a hack, and means that apps can in some
17176            // cases get permissions that the user didn't initially explicitly
17177            // allow... it would be nice to have some better way to handle
17178            // this situation.
17179            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17180                    : mSettings.getInternalVersion();
17181            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17182                    : StorageManager.UUID_PRIVATE_INTERNAL;
17183
17184            int updateFlags = UPDATE_PERMISSIONS_ALL;
17185            if (ver.sdkVersion != mSdkVersion) {
17186                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17187                        + mSdkVersion + "; regranting permissions for external");
17188                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17189            }
17190            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17191
17192            // Yay, everything is now upgraded
17193            ver.forceCurrent();
17194
17195            // can downgrade to reader
17196            // Persist settings
17197            mSettings.writeLPr();
17198        }
17199        // Send a broadcast to let everyone know we are done processing
17200        if (pkgList.size() > 0) {
17201            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17202        }
17203    }
17204
17205   /*
17206     * Utility method to unload a list of specified containers
17207     */
17208    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17209        // Just unmount all valid containers.
17210        for (AsecInstallArgs arg : cidArgs) {
17211            synchronized (mInstallLock) {
17212                arg.doPostDeleteLI(false);
17213           }
17214       }
17215   }
17216
17217    /*
17218     * Unload packages mounted on external media. This involves deleting package
17219     * data from internal structures, sending broadcasts about disabled packages,
17220     * gc'ing to free up references, unmounting all secure containers
17221     * corresponding to packages on external media, and posting a
17222     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17223     * that we always have to post this message if status has been requested no
17224     * matter what.
17225     */
17226    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17227            final boolean reportStatus) {
17228        if (DEBUG_SD_INSTALL)
17229            Log.i(TAG, "unloading media packages");
17230        ArrayList<String> pkgList = new ArrayList<String>();
17231        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17232        final Set<AsecInstallArgs> keys = processCids.keySet();
17233        for (AsecInstallArgs args : keys) {
17234            String pkgName = args.getPackageName();
17235            if (DEBUG_SD_INSTALL)
17236                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17237            // Delete package internally
17238            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17239            synchronized (mInstallLock) {
17240                boolean res = deletePackageLI(pkgName, null, false, null, null,
17241                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17242                if (res) {
17243                    pkgList.add(pkgName);
17244                } else {
17245                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17246                    failedList.add(args);
17247                }
17248            }
17249        }
17250
17251        // reader
17252        synchronized (mPackages) {
17253            // We didn't update the settings after removing each package;
17254            // write them now for all packages.
17255            mSettings.writeLPr();
17256        }
17257
17258        // We have to absolutely send UPDATED_MEDIA_STATUS only
17259        // after confirming that all the receivers processed the ordered
17260        // broadcast when packages get disabled, force a gc to clean things up.
17261        // and unload all the containers.
17262        if (pkgList.size() > 0) {
17263            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17264                    new IIntentReceiver.Stub() {
17265                public void performReceive(Intent intent, int resultCode, String data,
17266                        Bundle extras, boolean ordered, boolean sticky,
17267                        int sendingUser) throws RemoteException {
17268                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17269                            reportStatus ? 1 : 0, 1, keys);
17270                    mHandler.sendMessage(msg);
17271                }
17272            });
17273        } else {
17274            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17275                    keys);
17276            mHandler.sendMessage(msg);
17277        }
17278    }
17279
17280    private void loadPrivatePackages(final VolumeInfo vol) {
17281        mHandler.post(new Runnable() {
17282            @Override
17283            public void run() {
17284                loadPrivatePackagesInner(vol);
17285            }
17286        });
17287    }
17288
17289    private void loadPrivatePackagesInner(VolumeInfo vol) {
17290        final String volumeUuid = vol.fsUuid;
17291        if (TextUtils.isEmpty(volumeUuid)) {
17292            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17293            return;
17294        }
17295
17296        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17297        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17298
17299        final VersionInfo ver;
17300        final List<PackageSetting> packages;
17301        synchronized (mPackages) {
17302            ver = mSettings.findOrCreateVersion(volumeUuid);
17303            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17304        }
17305
17306        // TODO: introduce a new concept similar to "frozen" to prevent these
17307        // apps from being launched until after data has been fully reconciled
17308        for (PackageSetting ps : packages) {
17309            synchronized (mInstallLock) {
17310                final PackageParser.Package pkg;
17311                try {
17312                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17313                    loaded.add(pkg.applicationInfo);
17314
17315                } catch (PackageManagerException e) {
17316                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17317                }
17318
17319                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17320                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17321                }
17322            }
17323        }
17324
17325        // Reconcile app data for all started/unlocked users
17326        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17327        final UserManager um = mContext.getSystemService(UserManager.class);
17328        for (UserInfo user : um.getUsers()) {
17329            final int flags;
17330            if (um.isUserUnlocked(user.id)) {
17331                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17332            } else if (um.isUserRunning(user.id)) {
17333                flags = StorageManager.FLAG_STORAGE_DE;
17334            } else {
17335                continue;
17336            }
17337
17338            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17339            reconcileAppsData(volumeUuid, user.id, flags);
17340        }
17341
17342        synchronized (mPackages) {
17343            int updateFlags = UPDATE_PERMISSIONS_ALL;
17344            if (ver.sdkVersion != mSdkVersion) {
17345                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17346                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17347                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17348            }
17349            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17350
17351            // Yay, everything is now upgraded
17352            ver.forceCurrent();
17353
17354            mSettings.writeLPr();
17355        }
17356
17357        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17358        sendResourcesChangedBroadcast(true, false, loaded, null);
17359    }
17360
17361    private void unloadPrivatePackages(final VolumeInfo vol) {
17362        mHandler.post(new Runnable() {
17363            @Override
17364            public void run() {
17365                unloadPrivatePackagesInner(vol);
17366            }
17367        });
17368    }
17369
17370    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17371        final String volumeUuid = vol.fsUuid;
17372        if (TextUtils.isEmpty(volumeUuid)) {
17373            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17374            return;
17375        }
17376
17377        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17378        synchronized (mInstallLock) {
17379        synchronized (mPackages) {
17380            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17381            for (PackageSetting ps : packages) {
17382                if (ps.pkg == null) continue;
17383
17384                final ApplicationInfo info = ps.pkg.applicationInfo;
17385                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17386                if (deletePackageLI(ps.name, null, false, null, null,
17387                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17388                    unloaded.add(info);
17389                } else {
17390                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17391                }
17392            }
17393
17394            mSettings.writeLPr();
17395        }
17396        }
17397
17398        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17399        sendResourcesChangedBroadcast(false, false, unloaded, null);
17400    }
17401
17402    /**
17403     * Examine all users present on given mounted volume, and destroy data
17404     * belonging to users that are no longer valid, or whose user ID has been
17405     * recycled.
17406     */
17407    private void reconcileUsers(String volumeUuid) {
17408        // TODO: also reconcile DE directories
17409        final File[] files = FileUtils
17410                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17411        for (File file : files) {
17412            if (!file.isDirectory()) continue;
17413
17414            final int userId;
17415            final UserInfo info;
17416            try {
17417                userId = Integer.parseInt(file.getName());
17418                info = sUserManager.getUserInfo(userId);
17419            } catch (NumberFormatException e) {
17420                Slog.w(TAG, "Invalid user directory " + file);
17421                continue;
17422            }
17423
17424            boolean destroyUser = false;
17425            if (info == null) {
17426                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17427                        + " because no matching user was found");
17428                destroyUser = true;
17429            } else {
17430                try {
17431                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17432                } catch (IOException e) {
17433                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17434                            + " because we failed to enforce serial number: " + e);
17435                    destroyUser = true;
17436                }
17437            }
17438
17439            if (destroyUser) {
17440                synchronized (mInstallLock) {
17441                    try {
17442                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17443                    } catch (InstallerException e) {
17444                        Slog.w(TAG, "Failed to clean up user dirs", e);
17445                    }
17446                }
17447            }
17448        }
17449    }
17450
17451    private void assertPackageKnown(String volumeUuid, String packageName)
17452            throws PackageManagerException {
17453        synchronized (mPackages) {
17454            final PackageSetting ps = mSettings.mPackages.get(packageName);
17455            if (ps == null) {
17456                throw new PackageManagerException("Package " + packageName + " is unknown");
17457            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17458                throw new PackageManagerException(
17459                        "Package " + packageName + " found on unknown volume " + volumeUuid
17460                                + "; expected volume " + ps.volumeUuid);
17461            }
17462        }
17463    }
17464
17465    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17466            throws PackageManagerException {
17467        synchronized (mPackages) {
17468            final PackageSetting ps = mSettings.mPackages.get(packageName);
17469            if (ps == null) {
17470                throw new PackageManagerException("Package " + packageName + " is unknown");
17471            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17472                throw new PackageManagerException(
17473                        "Package " + packageName + " found on unknown volume " + volumeUuid
17474                                + "; expected volume " + ps.volumeUuid);
17475            } else if (!ps.getInstalled(userId)) {
17476                throw new PackageManagerException(
17477                        "Package " + packageName + " not installed for user " + userId);
17478            }
17479        }
17480    }
17481
17482    /**
17483     * Examine all apps present on given mounted volume, and destroy apps that
17484     * aren't expected, either due to uninstallation or reinstallation on
17485     * another volume.
17486     */
17487    private void reconcileApps(String volumeUuid) {
17488        final File[] files = FileUtils
17489                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17490        for (File file : files) {
17491            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17492                    && !PackageInstallerService.isStageName(file.getName());
17493            if (!isPackage) {
17494                // Ignore entries which are not packages
17495                continue;
17496            }
17497
17498            try {
17499                final PackageLite pkg = PackageParser.parsePackageLite(file,
17500                        PackageParser.PARSE_MUST_BE_APK);
17501                assertPackageKnown(volumeUuid, pkg.packageName);
17502
17503            } catch (PackageParserException | PackageManagerException e) {
17504                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17505                synchronized (mInstallLock) {
17506                    removeCodePathLI(file);
17507                }
17508            }
17509        }
17510    }
17511
17512    /**
17513     * Reconcile all app data for the given user.
17514     * <p>
17515     * Verifies that directories exist and that ownership and labeling is
17516     * correct for all installed apps on all mounted volumes.
17517     */
17518    void reconcileAppsData(int userId, int flags) {
17519        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17520        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17521            final String volumeUuid = vol.getFsUuid();
17522            reconcileAppsData(volumeUuid, userId, flags);
17523        }
17524    }
17525
17526    /**
17527     * Reconcile all app data on given mounted volume.
17528     * <p>
17529     * Destroys app data that isn't expected, either due to uninstallation or
17530     * reinstallation on another volume.
17531     * <p>
17532     * Verifies that directories exist and that ownership and labeling is
17533     * correct for all installed apps.
17534     */
17535    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17536        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17537                + Integer.toHexString(flags));
17538
17539        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17540        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17541
17542        boolean restoreconNeeded = false;
17543
17544        // First look for stale data that doesn't belong, and check if things
17545        // have changed since we did our last restorecon
17546        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17547            if (!isUserKeyUnlocked(userId)) {
17548                throw new RuntimeException(
17549                        "Yikes, someone asked us to reconcile CE storage while " + userId
17550                                + " was still locked; this would have caused massive data loss!");
17551            }
17552
17553            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17554
17555            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17556            for (File file : files) {
17557                final String packageName = file.getName();
17558                try {
17559                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17560                } catch (PackageManagerException e) {
17561                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17562                    synchronized (mInstallLock) {
17563                        destroyAppDataLI(volumeUuid, packageName, userId,
17564                                StorageManager.FLAG_STORAGE_CE);
17565                    }
17566                }
17567            }
17568        }
17569        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17570            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17571
17572            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17573            for (File file : files) {
17574                final String packageName = file.getName();
17575                try {
17576                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17577                } catch (PackageManagerException e) {
17578                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17579                    synchronized (mInstallLock) {
17580                        destroyAppDataLI(volumeUuid, packageName, userId,
17581                                StorageManager.FLAG_STORAGE_DE);
17582                    }
17583                }
17584            }
17585        }
17586
17587        // Ensure that data directories are ready to roll for all packages
17588        // installed for this volume and user
17589        final List<PackageSetting> packages;
17590        synchronized (mPackages) {
17591            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17592        }
17593        int preparedCount = 0;
17594        for (PackageSetting ps : packages) {
17595            final String packageName = ps.name;
17596            if (ps.pkg == null) {
17597                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17598                // TODO: might be due to legacy ASEC apps; we should circle back
17599                // and reconcile again once they're scanned
17600                continue;
17601            }
17602
17603            if (ps.getInstalled(userId)) {
17604                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17605                preparedCount++;
17606            }
17607        }
17608
17609        if (restoreconNeeded) {
17610            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17611                SELinuxMMAC.setRestoreconDone(ceDir);
17612            }
17613            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17614                SELinuxMMAC.setRestoreconDone(deDir);
17615            }
17616        }
17617
17618        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17619                + " packages; restoreconNeeded was " + restoreconNeeded);
17620    }
17621
17622    /**
17623     * Prepare app data for the given app just after it was installed or
17624     * upgraded. This method carefully only touches users that it's installed
17625     * for, and it forces a restorecon to handle any seinfo changes.
17626     * <p>
17627     * Verifies that directories exist and that ownership and labeling is
17628     * correct for all installed apps. If there is an ownership mismatch, it
17629     * will try recovering system apps by wiping data; third-party app data is
17630     * left intact.
17631     */
17632    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17633        prepareAppDataAfterInstallInternal(pkg);
17634        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17635        for (int i = 0; i < childCount; i++) {
17636            PackageParser.Package childPackage = pkg.childPackages.get(i);
17637            prepareAppDataAfterInstallInternal(childPackage);
17638        }
17639    }
17640
17641    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17642        final PackageSetting ps;
17643        synchronized (mPackages) {
17644            ps = mSettings.mPackages.get(pkg.packageName);
17645        }
17646
17647        final UserManager um = mContext.getSystemService(UserManager.class);
17648        for (UserInfo user : um.getUsers()) {
17649            final int flags;
17650            if (um.isUserUnlocked(user.id)) {
17651                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17652            } else if (um.isUserRunning(user.id)) {
17653                flags = StorageManager.FLAG_STORAGE_DE;
17654            } else {
17655                continue;
17656            }
17657
17658            if (ps.getInstalled(user.id)) {
17659                // Whenever an app changes, force a restorecon of its data
17660                // TODO: when user data is locked, mark that we're still dirty
17661                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17662            }
17663        }
17664    }
17665
17666    /**
17667     * Prepare app data for the given app.
17668     * <p>
17669     * Verifies that directories exist and that ownership and labeling is
17670     * correct for all installed apps. If there is an ownership mismatch, this
17671     * will try recovering system apps by wiping data; third-party app data is
17672     * left intact.
17673     */
17674    private void prepareAppData(String volumeUuid, int userId, int flags,
17675            PackageParser.Package pkg, boolean restoreconNeeded) {
17676        if (DEBUG_APP_DATA) {
17677            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17678                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17679        }
17680
17681        final String packageName = pkg.packageName;
17682        final ApplicationInfo app = pkg.applicationInfo;
17683        final int appId = UserHandle.getAppId(app.uid);
17684
17685        Preconditions.checkNotNull(app.seinfo);
17686
17687        synchronized (mInstallLock) {
17688            try {
17689                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17690                        appId, app.seinfo, app.targetSdkVersion);
17691            } catch (InstallerException e) {
17692                if (app.isSystemApp()) {
17693                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17694                            + ", but trying to recover: " + e);
17695                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17696                    try {
17697                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17698                                appId, app.seinfo, app.targetSdkVersion);
17699                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17700                    } catch (InstallerException e2) {
17701                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17702                    }
17703                } else {
17704                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17705                }
17706            }
17707
17708            if (restoreconNeeded) {
17709                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17710            }
17711
17712            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17713                // Create a native library symlink only if we have native libraries
17714                // and if the native libraries are 32 bit libraries. We do not provide
17715                // this symlink for 64 bit libraries.
17716                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17717                    final String nativeLibPath = app.nativeLibraryDir;
17718                    try {
17719                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17720                                nativeLibPath, userId);
17721                    } catch (InstallerException e) {
17722                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17723                    }
17724                }
17725            }
17726        }
17727    }
17728
17729    private void unfreezePackage(String packageName) {
17730        synchronized (mPackages) {
17731            final PackageSetting ps = mSettings.mPackages.get(packageName);
17732            if (ps != null) {
17733                ps.frozen = false;
17734            }
17735        }
17736    }
17737
17738    @Override
17739    public int movePackage(final String packageName, final String volumeUuid) {
17740        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17741
17742        final int moveId = mNextMoveId.getAndIncrement();
17743        mHandler.post(new Runnable() {
17744            @Override
17745            public void run() {
17746                try {
17747                    movePackageInternal(packageName, volumeUuid, moveId);
17748                } catch (PackageManagerException e) {
17749                    Slog.w(TAG, "Failed to move " + packageName, e);
17750                    mMoveCallbacks.notifyStatusChanged(moveId,
17751                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17752                }
17753            }
17754        });
17755        return moveId;
17756    }
17757
17758    private void movePackageInternal(final String packageName, final String volumeUuid,
17759            final int moveId) throws PackageManagerException {
17760        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17761        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17762        final PackageManager pm = mContext.getPackageManager();
17763
17764        final boolean currentAsec;
17765        final String currentVolumeUuid;
17766        final File codeFile;
17767        final String installerPackageName;
17768        final String packageAbiOverride;
17769        final int appId;
17770        final String seinfo;
17771        final String label;
17772        final int targetSdkVersion;
17773
17774        // reader
17775        synchronized (mPackages) {
17776            final PackageParser.Package pkg = mPackages.get(packageName);
17777            final PackageSetting ps = mSettings.mPackages.get(packageName);
17778            if (pkg == null || ps == null) {
17779                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17780            }
17781
17782            if (pkg.applicationInfo.isSystemApp()) {
17783                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17784                        "Cannot move system application");
17785            }
17786
17787            if (pkg.applicationInfo.isExternalAsec()) {
17788                currentAsec = true;
17789                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17790            } else if (pkg.applicationInfo.isForwardLocked()) {
17791                currentAsec = true;
17792                currentVolumeUuid = "forward_locked";
17793            } else {
17794                currentAsec = false;
17795                currentVolumeUuid = ps.volumeUuid;
17796
17797                final File probe = new File(pkg.codePath);
17798                final File probeOat = new File(probe, "oat");
17799                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17800                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17801                            "Move only supported for modern cluster style installs");
17802                }
17803            }
17804
17805            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17806                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17807                        "Package already moved to " + volumeUuid);
17808            }
17809
17810            if (ps.frozen) {
17811                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17812                        "Failed to move already frozen package");
17813            }
17814            ps.frozen = true;
17815
17816            codeFile = new File(pkg.codePath);
17817            installerPackageName = ps.installerPackageName;
17818            packageAbiOverride = ps.cpuAbiOverrideString;
17819            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17820            seinfo = pkg.applicationInfo.seinfo;
17821            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17822            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17823        }
17824
17825        // Now that we're guarded by frozen state, kill app during move
17826        final long token = Binder.clearCallingIdentity();
17827        try {
17828            killApplication(packageName, appId, "move pkg");
17829        } finally {
17830            Binder.restoreCallingIdentity(token);
17831        }
17832
17833        final Bundle extras = new Bundle();
17834        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17835        extras.putString(Intent.EXTRA_TITLE, label);
17836        mMoveCallbacks.notifyCreated(moveId, extras);
17837
17838        int installFlags;
17839        final boolean moveCompleteApp;
17840        final File measurePath;
17841
17842        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17843            installFlags = INSTALL_INTERNAL;
17844            moveCompleteApp = !currentAsec;
17845            measurePath = Environment.getDataAppDirectory(volumeUuid);
17846        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17847            installFlags = INSTALL_EXTERNAL;
17848            moveCompleteApp = false;
17849            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17850        } else {
17851            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17852            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17853                    || !volume.isMountedWritable()) {
17854                unfreezePackage(packageName);
17855                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17856                        "Move location not mounted private volume");
17857            }
17858
17859            Preconditions.checkState(!currentAsec);
17860
17861            installFlags = INSTALL_INTERNAL;
17862            moveCompleteApp = true;
17863            measurePath = Environment.getDataAppDirectory(volumeUuid);
17864        }
17865
17866        final PackageStats stats = new PackageStats(null, -1);
17867        synchronized (mInstaller) {
17868            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17869                unfreezePackage(packageName);
17870                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17871                        "Failed to measure package size");
17872            }
17873        }
17874
17875        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17876                + stats.dataSize);
17877
17878        final long startFreeBytes = measurePath.getFreeSpace();
17879        final long sizeBytes;
17880        if (moveCompleteApp) {
17881            sizeBytes = stats.codeSize + stats.dataSize;
17882        } else {
17883            sizeBytes = stats.codeSize;
17884        }
17885
17886        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17887            unfreezePackage(packageName);
17888            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17889                    "Not enough free space to move");
17890        }
17891
17892        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17893
17894        final CountDownLatch installedLatch = new CountDownLatch(1);
17895        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17896            @Override
17897            public void onUserActionRequired(Intent intent) throws RemoteException {
17898                throw new IllegalStateException();
17899            }
17900
17901            @Override
17902            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17903                    Bundle extras) throws RemoteException {
17904                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17905                        + PackageManager.installStatusToString(returnCode, msg));
17906
17907                installedLatch.countDown();
17908
17909                // Regardless of success or failure of the move operation,
17910                // always unfreeze the package
17911                unfreezePackage(packageName);
17912
17913                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17914                switch (status) {
17915                    case PackageInstaller.STATUS_SUCCESS:
17916                        mMoveCallbacks.notifyStatusChanged(moveId,
17917                                PackageManager.MOVE_SUCCEEDED);
17918                        break;
17919                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17920                        mMoveCallbacks.notifyStatusChanged(moveId,
17921                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17922                        break;
17923                    default:
17924                        mMoveCallbacks.notifyStatusChanged(moveId,
17925                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17926                        break;
17927                }
17928            }
17929        };
17930
17931        final MoveInfo move;
17932        if (moveCompleteApp) {
17933            // Kick off a thread to report progress estimates
17934            new Thread() {
17935                @Override
17936                public void run() {
17937                    while (true) {
17938                        try {
17939                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17940                                break;
17941                            }
17942                        } catch (InterruptedException ignored) {
17943                        }
17944
17945                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17946                        final int progress = 10 + (int) MathUtils.constrain(
17947                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17948                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17949                    }
17950                }
17951            }.start();
17952
17953            final String dataAppName = codeFile.getName();
17954            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17955                    dataAppName, appId, seinfo, targetSdkVersion);
17956        } else {
17957            move = null;
17958        }
17959
17960        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17961
17962        final Message msg = mHandler.obtainMessage(INIT_COPY);
17963        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17964        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17965                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17966        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17967        msg.obj = params;
17968
17969        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17970                System.identityHashCode(msg.obj));
17971        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17972                System.identityHashCode(msg.obj));
17973
17974        mHandler.sendMessage(msg);
17975    }
17976
17977    @Override
17978    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17980
17981        final int realMoveId = mNextMoveId.getAndIncrement();
17982        final Bundle extras = new Bundle();
17983        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17984        mMoveCallbacks.notifyCreated(realMoveId, extras);
17985
17986        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17987            @Override
17988            public void onCreated(int moveId, Bundle extras) {
17989                // Ignored
17990            }
17991
17992            @Override
17993            public void onStatusChanged(int moveId, int status, long estMillis) {
17994                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17995            }
17996        };
17997
17998        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17999        storage.setPrimaryStorageUuid(volumeUuid, callback);
18000        return realMoveId;
18001    }
18002
18003    @Override
18004    public int getMoveStatus(int moveId) {
18005        mContext.enforceCallingOrSelfPermission(
18006                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18007        return mMoveCallbacks.mLastStatus.get(moveId);
18008    }
18009
18010    @Override
18011    public void registerMoveCallback(IPackageMoveObserver callback) {
18012        mContext.enforceCallingOrSelfPermission(
18013                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18014        mMoveCallbacks.register(callback);
18015    }
18016
18017    @Override
18018    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18019        mContext.enforceCallingOrSelfPermission(
18020                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18021        mMoveCallbacks.unregister(callback);
18022    }
18023
18024    @Override
18025    public boolean setInstallLocation(int loc) {
18026        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18027                null);
18028        if (getInstallLocation() == loc) {
18029            return true;
18030        }
18031        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18032                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18033            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18034                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18035            return true;
18036        }
18037        return false;
18038   }
18039
18040    @Override
18041    public int getInstallLocation() {
18042        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18043                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18044                PackageHelper.APP_INSTALL_AUTO);
18045    }
18046
18047    /** Called by UserManagerService */
18048    void cleanUpUser(UserManagerService userManager, int userHandle) {
18049        synchronized (mPackages) {
18050            mDirtyUsers.remove(userHandle);
18051            mUserNeedsBadging.delete(userHandle);
18052            mSettings.removeUserLPw(userHandle);
18053            mPendingBroadcasts.remove(userHandle);
18054            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18055        }
18056        synchronized (mInstallLock) {
18057            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18058            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18059                final String volumeUuid = vol.getFsUuid();
18060                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18061                try {
18062                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18063                } catch (InstallerException e) {
18064                    Slog.w(TAG, "Failed to remove user data", e);
18065                }
18066            }
18067            synchronized (mPackages) {
18068                removeUnusedPackagesLILPw(userManager, userHandle);
18069            }
18070        }
18071    }
18072
18073    /**
18074     * We're removing userHandle and would like to remove any downloaded packages
18075     * that are no longer in use by any other user.
18076     * @param userHandle the user being removed
18077     */
18078    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18079        final boolean DEBUG_CLEAN_APKS = false;
18080        int [] users = userManager.getUserIds();
18081        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18082        while (psit.hasNext()) {
18083            PackageSetting ps = psit.next();
18084            if (ps.pkg == null) {
18085                continue;
18086            }
18087            final String packageName = ps.pkg.packageName;
18088            // Skip over if system app
18089            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18090                continue;
18091            }
18092            if (DEBUG_CLEAN_APKS) {
18093                Slog.i(TAG, "Checking package " + packageName);
18094            }
18095            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18096            if (keep) {
18097                if (DEBUG_CLEAN_APKS) {
18098                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18099                }
18100            } else {
18101                for (int i = 0; i < users.length; i++) {
18102                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18103                        keep = true;
18104                        if (DEBUG_CLEAN_APKS) {
18105                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18106                                    + users[i]);
18107                        }
18108                        break;
18109                    }
18110                }
18111            }
18112            if (!keep) {
18113                if (DEBUG_CLEAN_APKS) {
18114                    Slog.i(TAG, "  Removing package " + packageName);
18115                }
18116                mHandler.post(new Runnable() {
18117                    public void run() {
18118                        deletePackageX(packageName, userHandle, 0);
18119                    } //end run
18120                });
18121            }
18122        }
18123    }
18124
18125    /** Called by UserManagerService */
18126    void createNewUser(int userHandle) {
18127        synchronized (mInstallLock) {
18128            try {
18129                mInstaller.createUserConfig(userHandle);
18130            } catch (InstallerException e) {
18131                Slog.w(TAG, "Failed to create user config", e);
18132            }
18133            mSettings.createNewUserLI(this, mInstaller, userHandle);
18134        }
18135        synchronized (mPackages) {
18136            applyFactoryDefaultBrowserLPw(userHandle);
18137            primeDomainVerificationsLPw(userHandle);
18138        }
18139    }
18140
18141    void newUserCreated(final int userHandle) {
18142        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18143        // If permission review for legacy apps is required, we represent
18144        // dagerous permissions for such apps as always granted runtime
18145        // permissions to keep per user flag state whether review is needed.
18146        // Hence, if a new user is added we have to propagate dangerous
18147        // permission grants for these legacy apps.
18148        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18149            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18150                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18151        }
18152    }
18153
18154    @Override
18155    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18156        mContext.enforceCallingOrSelfPermission(
18157                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18158                "Only package verification agents can read the verifier device identity");
18159
18160        synchronized (mPackages) {
18161            return mSettings.getVerifierDeviceIdentityLPw();
18162        }
18163    }
18164
18165    @Override
18166    public void setPermissionEnforced(String permission, boolean enforced) {
18167        // TODO: Now that we no longer change GID for storage, this should to away.
18168        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18169                "setPermissionEnforced");
18170        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18171            synchronized (mPackages) {
18172                if (mSettings.mReadExternalStorageEnforced == null
18173                        || mSettings.mReadExternalStorageEnforced != enforced) {
18174                    mSettings.mReadExternalStorageEnforced = enforced;
18175                    mSettings.writeLPr();
18176                }
18177            }
18178            // kill any non-foreground processes so we restart them and
18179            // grant/revoke the GID.
18180            final IActivityManager am = ActivityManagerNative.getDefault();
18181            if (am != null) {
18182                final long token = Binder.clearCallingIdentity();
18183                try {
18184                    am.killProcessesBelowForeground("setPermissionEnforcement");
18185                } catch (RemoteException e) {
18186                } finally {
18187                    Binder.restoreCallingIdentity(token);
18188                }
18189            }
18190        } else {
18191            throw new IllegalArgumentException("No selective enforcement for " + permission);
18192        }
18193    }
18194
18195    @Override
18196    @Deprecated
18197    public boolean isPermissionEnforced(String permission) {
18198        return true;
18199    }
18200
18201    @Override
18202    public boolean isStorageLow() {
18203        final long token = Binder.clearCallingIdentity();
18204        try {
18205            final DeviceStorageMonitorInternal
18206                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18207            if (dsm != null) {
18208                return dsm.isMemoryLow();
18209            } else {
18210                return false;
18211            }
18212        } finally {
18213            Binder.restoreCallingIdentity(token);
18214        }
18215    }
18216
18217    @Override
18218    public IPackageInstaller getPackageInstaller() {
18219        return mInstallerService;
18220    }
18221
18222    private boolean userNeedsBadging(int userId) {
18223        int index = mUserNeedsBadging.indexOfKey(userId);
18224        if (index < 0) {
18225            final UserInfo userInfo;
18226            final long token = Binder.clearCallingIdentity();
18227            try {
18228                userInfo = sUserManager.getUserInfo(userId);
18229            } finally {
18230                Binder.restoreCallingIdentity(token);
18231            }
18232            final boolean b;
18233            if (userInfo != null && userInfo.isManagedProfile()) {
18234                b = true;
18235            } else {
18236                b = false;
18237            }
18238            mUserNeedsBadging.put(userId, b);
18239            return b;
18240        }
18241        return mUserNeedsBadging.valueAt(index);
18242    }
18243
18244    @Override
18245    public KeySet getKeySetByAlias(String packageName, String alias) {
18246        if (packageName == null || alias == null) {
18247            return null;
18248        }
18249        synchronized(mPackages) {
18250            final PackageParser.Package pkg = mPackages.get(packageName);
18251            if (pkg == null) {
18252                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18253                throw new IllegalArgumentException("Unknown package: " + packageName);
18254            }
18255            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18256            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18257        }
18258    }
18259
18260    @Override
18261    public KeySet getSigningKeySet(String packageName) {
18262        if (packageName == null) {
18263            return null;
18264        }
18265        synchronized(mPackages) {
18266            final PackageParser.Package pkg = mPackages.get(packageName);
18267            if (pkg == null) {
18268                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18269                throw new IllegalArgumentException("Unknown package: " + packageName);
18270            }
18271            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18272                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18273                throw new SecurityException("May not access signing KeySet of other apps.");
18274            }
18275            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18276            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18277        }
18278    }
18279
18280    @Override
18281    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18282        if (packageName == null || ks == null) {
18283            return false;
18284        }
18285        synchronized(mPackages) {
18286            final PackageParser.Package pkg = mPackages.get(packageName);
18287            if (pkg == null) {
18288                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18289                throw new IllegalArgumentException("Unknown package: " + packageName);
18290            }
18291            IBinder ksh = ks.getToken();
18292            if (ksh instanceof KeySetHandle) {
18293                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18294                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18295            }
18296            return false;
18297        }
18298    }
18299
18300    @Override
18301    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18302        if (packageName == null || ks == null) {
18303            return false;
18304        }
18305        synchronized(mPackages) {
18306            final PackageParser.Package pkg = mPackages.get(packageName);
18307            if (pkg == null) {
18308                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18309                throw new IllegalArgumentException("Unknown package: " + packageName);
18310            }
18311            IBinder ksh = ks.getToken();
18312            if (ksh instanceof KeySetHandle) {
18313                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18314                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18315            }
18316            return false;
18317        }
18318    }
18319
18320    private void deletePackageIfUnusedLPr(final String packageName) {
18321        PackageSetting ps = mSettings.mPackages.get(packageName);
18322        if (ps == null) {
18323            return;
18324        }
18325        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18326            // TODO Implement atomic delete if package is unused
18327            // It is currently possible that the package will be deleted even if it is installed
18328            // after this method returns.
18329            mHandler.post(new Runnable() {
18330                public void run() {
18331                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18332                }
18333            });
18334        }
18335    }
18336
18337    /**
18338     * Check and throw if the given before/after packages would be considered a
18339     * downgrade.
18340     */
18341    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18342            throws PackageManagerException {
18343        if (after.versionCode < before.mVersionCode) {
18344            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18345                    "Update version code " + after.versionCode + " is older than current "
18346                    + before.mVersionCode);
18347        } else if (after.versionCode == before.mVersionCode) {
18348            if (after.baseRevisionCode < before.baseRevisionCode) {
18349                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18350                        "Update base revision code " + after.baseRevisionCode
18351                        + " is older than current " + before.baseRevisionCode);
18352            }
18353
18354            if (!ArrayUtils.isEmpty(after.splitNames)) {
18355                for (int i = 0; i < after.splitNames.length; i++) {
18356                    final String splitName = after.splitNames[i];
18357                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18358                    if (j != -1) {
18359                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18360                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18361                                    "Update split " + splitName + " revision code "
18362                                    + after.splitRevisionCodes[i] + " is older than current "
18363                                    + before.splitRevisionCodes[j]);
18364                        }
18365                    }
18366                }
18367            }
18368        }
18369    }
18370
18371    private static class MoveCallbacks extends Handler {
18372        private static final int MSG_CREATED = 1;
18373        private static final int MSG_STATUS_CHANGED = 2;
18374
18375        private final RemoteCallbackList<IPackageMoveObserver>
18376                mCallbacks = new RemoteCallbackList<>();
18377
18378        private final SparseIntArray mLastStatus = new SparseIntArray();
18379
18380        public MoveCallbacks(Looper looper) {
18381            super(looper);
18382        }
18383
18384        public void register(IPackageMoveObserver callback) {
18385            mCallbacks.register(callback);
18386        }
18387
18388        public void unregister(IPackageMoveObserver callback) {
18389            mCallbacks.unregister(callback);
18390        }
18391
18392        @Override
18393        public void handleMessage(Message msg) {
18394            final SomeArgs args = (SomeArgs) msg.obj;
18395            final int n = mCallbacks.beginBroadcast();
18396            for (int i = 0; i < n; i++) {
18397                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18398                try {
18399                    invokeCallback(callback, msg.what, args);
18400                } catch (RemoteException ignored) {
18401                }
18402            }
18403            mCallbacks.finishBroadcast();
18404            args.recycle();
18405        }
18406
18407        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18408                throws RemoteException {
18409            switch (what) {
18410                case MSG_CREATED: {
18411                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18412                    break;
18413                }
18414                case MSG_STATUS_CHANGED: {
18415                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18416                    break;
18417                }
18418            }
18419        }
18420
18421        private void notifyCreated(int moveId, Bundle extras) {
18422            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18423
18424            final SomeArgs args = SomeArgs.obtain();
18425            args.argi1 = moveId;
18426            args.arg2 = extras;
18427            obtainMessage(MSG_CREATED, args).sendToTarget();
18428        }
18429
18430        private void notifyStatusChanged(int moveId, int status) {
18431            notifyStatusChanged(moveId, status, -1);
18432        }
18433
18434        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18435            Slog.v(TAG, "Move " + moveId + " status " + status);
18436
18437            final SomeArgs args = SomeArgs.obtain();
18438            args.argi1 = moveId;
18439            args.argi2 = status;
18440            args.arg3 = estMillis;
18441            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18442
18443            synchronized (mLastStatus) {
18444                mLastStatus.put(moveId, status);
18445            }
18446        }
18447    }
18448
18449    private final static class OnPermissionChangeListeners extends Handler {
18450        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18451
18452        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18453                new RemoteCallbackList<>();
18454
18455        public OnPermissionChangeListeners(Looper looper) {
18456            super(looper);
18457        }
18458
18459        @Override
18460        public void handleMessage(Message msg) {
18461            switch (msg.what) {
18462                case MSG_ON_PERMISSIONS_CHANGED: {
18463                    final int uid = msg.arg1;
18464                    handleOnPermissionsChanged(uid);
18465                } break;
18466            }
18467        }
18468
18469        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18470            mPermissionListeners.register(listener);
18471
18472        }
18473
18474        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18475            mPermissionListeners.unregister(listener);
18476        }
18477
18478        public void onPermissionsChanged(int uid) {
18479            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18480                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18481            }
18482        }
18483
18484        private void handleOnPermissionsChanged(int uid) {
18485            final int count = mPermissionListeners.beginBroadcast();
18486            try {
18487                for (int i = 0; i < count; i++) {
18488                    IOnPermissionsChangeListener callback = mPermissionListeners
18489                            .getBroadcastItem(i);
18490                    try {
18491                        callback.onPermissionsChanged(uid);
18492                    } catch (RemoteException e) {
18493                        Log.e(TAG, "Permission listener is dead", e);
18494                    }
18495                }
18496            } finally {
18497                mPermissionListeners.finishBroadcast();
18498            }
18499        }
18500    }
18501
18502    private class PackageManagerInternalImpl extends PackageManagerInternal {
18503        @Override
18504        public void setLocationPackagesProvider(PackagesProvider provider) {
18505            synchronized (mPackages) {
18506                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18507            }
18508        }
18509
18510        @Override
18511        public void setImePackagesProvider(PackagesProvider provider) {
18512            synchronized (mPackages) {
18513                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18514            }
18515        }
18516
18517        @Override
18518        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18519            synchronized (mPackages) {
18520                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18521            }
18522        }
18523
18524        @Override
18525        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18526            synchronized (mPackages) {
18527                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18528            }
18529        }
18530
18531        @Override
18532        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18533            synchronized (mPackages) {
18534                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18535            }
18536        }
18537
18538        @Override
18539        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18540            synchronized (mPackages) {
18541                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18542            }
18543        }
18544
18545        @Override
18546        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18547            synchronized (mPackages) {
18548                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18549            }
18550        }
18551
18552        @Override
18553        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18554            synchronized (mPackages) {
18555                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18556                        packageName, userId);
18557            }
18558        }
18559
18560        @Override
18561        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18562            synchronized (mPackages) {
18563                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18564                        packageName, userId);
18565            }
18566        }
18567
18568        @Override
18569        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18570            synchronized (mPackages) {
18571                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18572                        packageName, userId);
18573            }
18574        }
18575
18576        @Override
18577        public void setKeepUninstalledPackages(final List<String> packageList) {
18578            Preconditions.checkNotNull(packageList);
18579            List<String> removedFromList = null;
18580            synchronized (mPackages) {
18581                if (mKeepUninstalledPackages != null) {
18582                    final int packagesCount = mKeepUninstalledPackages.size();
18583                    for (int i = 0; i < packagesCount; i++) {
18584                        String oldPackage = mKeepUninstalledPackages.get(i);
18585                        if (packageList != null && packageList.contains(oldPackage)) {
18586                            continue;
18587                        }
18588                        if (removedFromList == null) {
18589                            removedFromList = new ArrayList<>();
18590                        }
18591                        removedFromList.add(oldPackage);
18592                    }
18593                }
18594                mKeepUninstalledPackages = new ArrayList<>(packageList);
18595                if (removedFromList != null) {
18596                    final int removedCount = removedFromList.size();
18597                    for (int i = 0; i < removedCount; i++) {
18598                        deletePackageIfUnusedLPr(removedFromList.get(i));
18599                    }
18600                }
18601            }
18602        }
18603
18604        @Override
18605        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18606            synchronized (mPackages) {
18607                // If we do not support permission review, done.
18608                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18609                    return false;
18610                }
18611
18612                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18613                if (packageSetting == null) {
18614                    return false;
18615                }
18616
18617                // Permission review applies only to apps not supporting the new permission model.
18618                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18619                    return false;
18620                }
18621
18622                // Legacy apps have the permission and get user consent on launch.
18623                PermissionsState permissionsState = packageSetting.getPermissionsState();
18624                return permissionsState.isPermissionReviewRequired(userId);
18625            }
18626        }
18627    }
18628
18629    @Override
18630    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18631        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18632        synchronized (mPackages) {
18633            final long identity = Binder.clearCallingIdentity();
18634            try {
18635                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18636                        packageNames, userId);
18637            } finally {
18638                Binder.restoreCallingIdentity(identity);
18639            }
18640        }
18641    }
18642
18643    private static void enforceSystemOrPhoneCaller(String tag) {
18644        int callingUid = Binder.getCallingUid();
18645        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18646            throw new SecurityException(
18647                    "Cannot call " + tag + " from UID " + callingUid);
18648        }
18649    }
18650
18651    boolean isHistoricalPackageUsageAvailable() {
18652        return mPackageUsage.isHistoricalPackageUsageAvailable();
18653    }
18654}
18655