PackageManagerService.java revision e4697136ed8d3e2486738b5798b22f2226b7de75
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
71import static android.content.pm.PackageManager.PERMISSION_DENIED;
72import static android.content.pm.PackageManager.PERMISSION_GRANTED;
73import static android.content.pm.PackageParser.isApkFile;
74import static android.os.Process.PACKAGE_INFO_GID;
75import static android.os.Process.SYSTEM_UID;
76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
77import static android.system.OsConstants.O_CREAT;
78import static android.system.OsConstants.O_RDWR;
79
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
84import static com.android.internal.util.ArrayUtils.appendInt;
85import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
94
95import android.Manifest;
96import android.annotation.NonNull;
97import android.annotation.Nullable;
98import android.app.ActivityManager;
99import android.app.ActivityManagerNative;
100import android.app.AppGlobals;
101import android.app.IActivityManager;
102import android.app.admin.IDevicePolicyManager;
103import android.app.backup.IBackupManager;
104import android.content.BroadcastReceiver;
105import android.content.ComponentName;
106import android.content.Context;
107import android.content.IIntentReceiver;
108import android.content.Intent;
109import android.content.IntentFilter;
110import android.content.IntentSender;
111import android.content.IntentSender.SendIntentException;
112import android.content.ServiceConnection;
113import android.content.pm.ActivityInfo;
114import android.content.pm.ApplicationInfo;
115import android.content.pm.AppsQueryHelper;
116import android.content.pm.ComponentInfo;
117import android.content.pm.EphemeralApplicationInfo;
118import android.content.pm.EphemeralResolveInfo;
119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
120import android.content.pm.FeatureInfo;
121import android.content.pm.IOnPermissionsChangeListener;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageDeleteObserver;
124import android.content.pm.IPackageDeleteObserver2;
125import android.content.pm.IPackageInstallObserver2;
126import android.content.pm.IPackageInstaller;
127import android.content.pm.IPackageManager;
128import android.content.pm.IPackageMoveObserver;
129import android.content.pm.IPackageStatsObserver;
130import android.content.pm.InstrumentationInfo;
131import android.content.pm.IntentFilterVerificationInfo;
132import android.content.pm.KeySet;
133import android.content.pm.PackageCleanItem;
134import android.content.pm.PackageInfo;
135import android.content.pm.PackageInfoLite;
136import android.content.pm.PackageInstaller;
137import android.content.pm.PackageManager;
138import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
139import android.content.pm.PackageManagerInternal;
140import android.content.pm.PackageParser;
141import android.content.pm.PackageParser.ActivityIntentInfo;
142import android.content.pm.PackageParser.Package;
143import android.content.pm.PackageParser.PackageLite;
144import android.content.pm.PackageParser.PackageParserException;
145import android.content.pm.PackageStats;
146import android.content.pm.PackageUserState;
147import android.content.pm.ParceledListSlice;
148import android.content.pm.PermissionGroupInfo;
149import android.content.pm.PermissionInfo;
150import android.content.pm.ProviderInfo;
151import android.content.pm.ResolveInfo;
152import android.content.pm.ServiceInfo;
153import android.content.pm.Signature;
154import android.content.pm.UserInfo;
155import android.content.pm.VerificationParams;
156import android.content.pm.VerifierDeviceIdentity;
157import android.content.pm.VerifierInfo;
158import android.content.res.Resources;
159import android.graphics.Bitmap;
160import android.hardware.display.DisplayManager;
161import android.net.Uri;
162import android.os.Binder;
163import android.os.Build;
164import android.os.Bundle;
165import android.os.Debug;
166import android.os.Environment;
167import android.os.Environment.UserEnvironment;
168import android.os.FileUtils;
169import android.os.Handler;
170import android.os.IBinder;
171import android.os.Looper;
172import android.os.Message;
173import android.os.Parcel;
174import android.os.ParcelFileDescriptor;
175import android.os.Process;
176import android.os.RemoteCallbackList;
177import android.os.RemoteException;
178import android.os.ResultReceiver;
179import android.os.SELinux;
180import android.os.ServiceManager;
181import android.os.SystemClock;
182import android.os.SystemProperties;
183import android.os.Trace;
184import android.os.UserHandle;
185import android.os.UserManager;
186import android.os.storage.IMountService;
187import android.os.storage.MountServiceInternal;
188import android.os.storage.StorageEventListener;
189import android.os.storage.StorageManager;
190import android.os.storage.VolumeInfo;
191import android.os.storage.VolumeRecord;
192import android.security.KeyStore;
193import android.security.SystemKeyStore;
194import android.system.ErrnoException;
195import android.system.Os;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.InstallerConnection.InstallerException;
223import com.android.internal.os.SomeArgs;
224import com.android.internal.os.Zygote;
225import com.android.internal.util.ArrayUtils;
226import com.android.internal.util.FastPrintWriter;
227import com.android.internal.util.FastXmlSerializer;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.Preconditions;
230import com.android.internal.util.XmlUtils;
231import com.android.server.EventLogTags;
232import com.android.server.FgThread;
233import com.android.server.IntentResolver;
234import com.android.server.LocalServices;
235import com.android.server.ServiceThread;
236import com.android.server.SystemConfig;
237import com.android.server.Watchdog;
238import com.android.server.pm.PermissionsState.PermissionState;
239import com.android.server.pm.Settings.DatabaseVersion;
240import com.android.server.pm.Settings.VersionInfo;
241import com.android.server.storage.DeviceStorageMonitorInternal;
242
243import dalvik.system.DexFile;
244import dalvik.system.VMRuntime;
245
246import libcore.io.IoUtils;
247import libcore.util.EmptyArray;
248
249import org.xmlpull.v1.XmlPullParser;
250import org.xmlpull.v1.XmlPullParserException;
251import org.xmlpull.v1.XmlSerializer;
252
253import java.io.BufferedInputStream;
254import java.io.BufferedOutputStream;
255import java.io.BufferedReader;
256import java.io.ByteArrayInputStream;
257import java.io.ByteArrayOutputStream;
258import java.io.File;
259import java.io.FileDescriptor;
260import java.io.FileNotFoundException;
261import java.io.FileOutputStream;
262import java.io.FileReader;
263import java.io.FilenameFilter;
264import java.io.IOException;
265import java.io.InputStream;
266import java.io.PrintStream;
267import java.io.PrintWriter;
268import java.nio.charset.StandardCharsets;
269import java.security.MessageDigest;
270import java.security.NoSuchAlgorithmException;
271import java.security.PublicKey;
272import java.security.cert.CertificateEncodingException;
273import java.security.cert.CertificateException;
274import java.text.SimpleDateFormat;
275import java.util.ArrayList;
276import java.util.Arrays;
277import java.util.Collection;
278import java.util.Collections;
279import java.util.Comparator;
280import java.util.Date;
281import java.util.HashSet;
282import java.util.Iterator;
283import java.util.List;
284import java.util.Map;
285import java.util.Objects;
286import java.util.Set;
287import java.util.concurrent.CountDownLatch;
288import java.util.concurrent.TimeUnit;
289import java.util.concurrent.atomic.AtomicBoolean;
290import java.util.concurrent.atomic.AtomicInteger;
291import java.util.concurrent.atomic.AtomicLong;
292
293/**
294 * Keep track of all those .apks everywhere.
295 *
296 * This is very central to the platform's security; please run the unit
297 * tests whenever making modifications here:
298 *
299runtest -c android.content.pm.PackageManagerTests frameworks-core
300 *
301 * {@hide}
302 */
303public class PackageManagerService extends IPackageManager.Stub {
304    static final String TAG = "PackageManager";
305    static final boolean DEBUG_SETTINGS = false;
306    static final boolean DEBUG_PREFERRED = false;
307    static final boolean DEBUG_UPGRADE = false;
308    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
309    private static final boolean DEBUG_BACKUP = false;
310    private static final boolean DEBUG_INSTALL = false;
311    private static final boolean DEBUG_REMOVE = false;
312    private static final boolean DEBUG_BROADCASTS = false;
313    private static final boolean DEBUG_SHOW_INFO = false;
314    private static final boolean DEBUG_PACKAGE_INFO = false;
315    private static final boolean DEBUG_INTENT_MATCHING = false;
316    private static final boolean DEBUG_PACKAGE_SCANNING = false;
317    private static final boolean DEBUG_VERIFY = false;
318
319    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
320    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
321    // user, but by default initialize to this.
322    static final boolean DEBUG_DEXOPT = false;
323
324    private static final boolean DEBUG_ABI_SELECTION = false;
325    private static final boolean DEBUG_EPHEMERAL = false;
326    private static final boolean DEBUG_TRIAGED_MISSING = false;
327    private static final boolean DEBUG_APP_DATA = false;
328
329    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
330
331    private static final boolean DISABLE_EPHEMERAL_APPS = true;
332
333    private static final int RADIO_UID = Process.PHONE_UID;
334    private static final int LOG_UID = Process.LOG_UID;
335    private static final int NFC_UID = Process.NFC_UID;
336    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
337    private static final int SHELL_UID = Process.SHELL_UID;
338
339    // Cap the size of permission trees that 3rd party apps can define
340    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
341
342    // Suffix used during package installation when copying/moving
343    // package apks to install directory.
344    private static final String INSTALL_PACKAGE_SUFFIX = "-";
345
346    static final int SCAN_NO_DEX = 1<<1;
347    static final int SCAN_FORCE_DEX = 1<<2;
348    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
349    static final int SCAN_NEW_INSTALL = 1<<4;
350    static final int SCAN_NO_PATHS = 1<<5;
351    static final int SCAN_UPDATE_TIME = 1<<6;
352    static final int SCAN_DEFER_DEX = 1<<7;
353    static final int SCAN_BOOTING = 1<<8;
354    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
355    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
356    static final int SCAN_REPLACING = 1<<11;
357    static final int SCAN_REQUIRE_KNOWN = 1<<12;
358    static final int SCAN_MOVE = 1<<13;
359    static final int SCAN_INITIAL = 1<<14;
360
361    static final int REMOVE_CHATTY = 1<<16;
362
363    private static final int[] EMPTY_INT_ARRAY = new int[0];
364
365    /**
366     * Timeout (in milliseconds) after which the watchdog should declare that
367     * our handler thread is wedged.  The usual default for such things is one
368     * minute but we sometimes do very lengthy I/O operations on this thread,
369     * such as installing multi-gigabyte applications, so ours needs to be longer.
370     */
371    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
372
373    /**
374     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
375     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
376     * settings entry if available, otherwise we use the hardcoded default.  If it's been
377     * more than this long since the last fstrim, we force one during the boot sequence.
378     *
379     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
380     * one gets run at the next available charging+idle time.  This final mandatory
381     * no-fstrim check kicks in only of the other scheduling criteria is never met.
382     */
383    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
384
385    /**
386     * Whether verification is enabled by default.
387     */
388    private static final boolean DEFAULT_VERIFY_ENABLE = true;
389
390    /**
391     * The default maximum time to wait for the verification agent to return in
392     * milliseconds.
393     */
394    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
395
396    /**
397     * The default response for package verification timeout.
398     *
399     * This can be either PackageManager.VERIFICATION_ALLOW or
400     * PackageManager.VERIFICATION_REJECT.
401     */
402    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
403
404    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
405
406    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
407            DEFAULT_CONTAINER_PACKAGE,
408            "com.android.defcontainer.DefaultContainerService");
409
410    private static final String KILL_APP_REASON_GIDS_CHANGED =
411            "permission grant or revoke changed gids";
412
413    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
414            "permissions revoked";
415
416    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
417
418    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
419
420    /** Permission grant: not grant the permission. */
421    private static final int GRANT_DENIED = 1;
422
423    /** Permission grant: grant the permission as an install permission. */
424    private static final int GRANT_INSTALL = 2;
425
426    /** Permission grant: grant the permission as a runtime one. */
427    private static final int GRANT_RUNTIME = 3;
428
429    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
430    private static final int GRANT_UPGRADE = 4;
431
432    /** Canonical intent used to identify what counts as a "web browser" app */
433    private static final Intent sBrowserIntent;
434    static {
435        sBrowserIntent = new Intent();
436        sBrowserIntent.setAction(Intent.ACTION_VIEW);
437        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
438        sBrowserIntent.setData(Uri.parse("http:"));
439    }
440
441    final ServiceThread mHandlerThread;
442
443    final PackageHandler mHandler;
444
445    /**
446     * Messages for {@link #mHandler} that need to wait for system ready before
447     * being dispatched.
448     */
449    private ArrayList<Message> mPostSystemReadyMessages;
450
451    final int mSdkVersion = Build.VERSION.SDK_INT;
452
453    final Context mContext;
454    final boolean mFactoryTest;
455    final boolean mOnlyCore;
456    final DisplayMetrics mMetrics;
457    final int mDefParseFlags;
458    final String[] mSeparateProcesses;
459    final boolean mIsUpgrade;
460
461    /** The location for ASEC container files on internal storage. */
462    final String mAsecInternalPath;
463
464    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
465    // LOCK HELD.  Can be called with mInstallLock held.
466    @GuardedBy("mInstallLock")
467    final Installer mInstaller;
468
469    /** Directory where installed third-party apps stored */
470    final File mAppInstallDir;
471    final File mEphemeralInstallDir;
472
473    /**
474     * Directory to which applications installed internally have their
475     * 32 bit native libraries copied.
476     */
477    private File mAppLib32InstallDir;
478
479    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
480    // apps.
481    final File mDrmAppPrivateInstallDir;
482
483    // ----------------------------------------------------------------
484
485    // Lock for state used when installing and doing other long running
486    // operations.  Methods that must be called with this lock held have
487    // the suffix "LI".
488    final Object mInstallLock = new Object();
489
490    // ----------------------------------------------------------------
491
492    // Keys are String (package name), values are Package.  This also serves
493    // as the lock for the global state.  Methods that must be called with
494    // this lock held have the prefix "LP".
495    @GuardedBy("mPackages")
496    final ArrayMap<String, PackageParser.Package> mPackages =
497            new ArrayMap<String, PackageParser.Package>();
498
499    // Tracks available target package names -> overlay package paths.
500    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
501        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
502
503    /**
504     * Tracks new system packages [received in an OTA] that we expect to
505     * find updated user-installed versions. Keys are package name, values
506     * are package location.
507     */
508    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
509
510    /**
511     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
512     */
513    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
514    /**
515     * Whether or not system app permissions should be promoted from install to runtime.
516     */
517    boolean mPromoteSystemApps;
518
519    final Settings mSettings;
520    boolean mRestoredSettings;
521
522    // System configuration read by SystemConfig.
523    final int[] mGlobalGids;
524    final SparseArray<ArraySet<String>> mSystemPermissions;
525    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
526
527    // If mac_permissions.xml was found for seinfo labeling.
528    boolean mFoundPolicyFile;
529
530    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
531
532    public static final class SharedLibraryEntry {
533        public final String path;
534        public final String apk;
535
536        SharedLibraryEntry(String _path, String _apk) {
537            path = _path;
538            apk = _apk;
539        }
540    }
541
542    // Currently known shared libraries.
543    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
544            new ArrayMap<String, SharedLibraryEntry>();
545
546    // All available activities, for your resolving pleasure.
547    final ActivityIntentResolver mActivities =
548            new ActivityIntentResolver();
549
550    // All available receivers, for your resolving pleasure.
551    final ActivityIntentResolver mReceivers =
552            new ActivityIntentResolver();
553
554    // All available services, for your resolving pleasure.
555    final ServiceIntentResolver mServices = new ServiceIntentResolver();
556
557    // All available providers, for your resolving pleasure.
558    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
559
560    // Mapping from provider base names (first directory in content URI codePath)
561    // to the provider information.
562    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
563            new ArrayMap<String, PackageParser.Provider>();
564
565    // Mapping from instrumentation class names to info about them.
566    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
567            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
568
569    // Mapping from permission names to info about them.
570    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
571            new ArrayMap<String, PackageParser.PermissionGroup>();
572
573    // Packages whose data we have transfered into another package, thus
574    // should no longer exist.
575    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
576
577    // Broadcast actions that are only available to the system.
578    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
579
580    /** List of packages waiting for verification. */
581    final SparseArray<PackageVerificationState> mPendingVerification
582            = new SparseArray<PackageVerificationState>();
583
584    /** Set of packages associated with each app op permission. */
585    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
586
587    final PackageInstallerService mInstallerService;
588
589    private final PackageDexOptimizer mPackageDexOptimizer;
590
591    private AtomicInteger mNextMoveId = new AtomicInteger();
592    private final MoveCallbacks mMoveCallbacks;
593
594    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
595
596    // Cache of users who need badging.
597    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
598
599    /** Token for keys in mPendingVerification. */
600    private int mPendingVerificationToken = 0;
601
602    volatile boolean mSystemReady;
603    volatile boolean mSafeMode;
604    volatile boolean mHasSystemUidErrors;
605
606    ApplicationInfo mAndroidApplication;
607    final ActivityInfo mResolveActivity = new ActivityInfo();
608    final ResolveInfo mResolveInfo = new ResolveInfo();
609    ComponentName mResolveComponentName;
610    PackageParser.Package mPlatformPackage;
611    ComponentName mCustomResolverComponentName;
612
613    boolean mResolverReplaced = false;
614
615    private final @Nullable ComponentName mIntentFilterVerifierComponent;
616    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
617
618    private int mIntentFilterVerificationToken = 0;
619
620    /** Component that knows whether or not an ephemeral application exists */
621    final ComponentName mEphemeralResolverComponent;
622    /** The service connection to the ephemeral resolver */
623    final EphemeralResolverConnection mEphemeralResolverConnection;
624
625    /** Component used to install ephemeral applications */
626    final ComponentName mEphemeralInstallerComponent;
627    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
628    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
629
630    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
631            = new SparseArray<IntentFilterVerificationState>();
632
633    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
634            new DefaultPermissionGrantPolicy(this);
635
636    // List of packages names to keep cached, even if they are uninstalled for all users
637    private List<String> mKeepUninstalledPackages;
638
639    private boolean mUseJitProfiles =
640            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
641
642    private static class IFVerificationParams {
643        PackageParser.Package pkg;
644        boolean replacing;
645        int userId;
646        int verifierUid;
647
648        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
649                int _userId, int _verifierUid) {
650            pkg = _pkg;
651            replacing = _replacing;
652            userId = _userId;
653            replacing = _replacing;
654            verifierUid = _verifierUid;
655        }
656    }
657
658    private interface IntentFilterVerifier<T extends IntentFilter> {
659        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
660                                               T filter, String packageName);
661        void startVerifications(int userId);
662        void receiveVerificationResponse(int verificationId);
663    }
664
665    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
666        private Context mContext;
667        private ComponentName mIntentFilterVerifierComponent;
668        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
669
670        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
671            mContext = context;
672            mIntentFilterVerifierComponent = verifierComponent;
673        }
674
675        private String getDefaultScheme() {
676            return IntentFilter.SCHEME_HTTPS;
677        }
678
679        @Override
680        public void startVerifications(int userId) {
681            // Launch verifications requests
682            int count = mCurrentIntentFilterVerifications.size();
683            for (int n=0; n<count; n++) {
684                int verificationId = mCurrentIntentFilterVerifications.get(n);
685                final IntentFilterVerificationState ivs =
686                        mIntentFilterVerificationStates.get(verificationId);
687
688                String packageName = ivs.getPackageName();
689
690                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
691                final int filterCount = filters.size();
692                ArraySet<String> domainsSet = new ArraySet<>();
693                for (int m=0; m<filterCount; m++) {
694                    PackageParser.ActivityIntentInfo filter = filters.get(m);
695                    domainsSet.addAll(filter.getHostsList());
696                }
697                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
698                synchronized (mPackages) {
699                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
700                            packageName, domainsList) != null) {
701                        scheduleWriteSettingsLocked();
702                    }
703                }
704                sendVerificationRequest(userId, verificationId, ivs);
705            }
706            mCurrentIntentFilterVerifications.clear();
707        }
708
709        private void sendVerificationRequest(int userId, int verificationId,
710                IntentFilterVerificationState ivs) {
711
712            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
713            verificationIntent.putExtra(
714                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
715                    verificationId);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
718                    getDefaultScheme());
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
721                    ivs.getHostsString());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
724                    ivs.getPackageName());
725            verificationIntent.setComponent(mIntentFilterVerifierComponent);
726            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
727
728            UserHandle user = new UserHandle(userId);
729            mContext.sendBroadcastAsUser(verificationIntent, user);
730            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
731                    "Sending IntentFilter verification broadcast");
732        }
733
734        public void receiveVerificationResponse(int verificationId) {
735            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
736
737            final boolean verified = ivs.isVerified();
738
739            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
740            final int count = filters.size();
741            if (DEBUG_DOMAIN_VERIFICATION) {
742                Slog.i(TAG, "Received verification response " + verificationId
743                        + " for " + count + " filters, verified=" + verified);
744            }
745            for (int n=0; n<count; n++) {
746                PackageParser.ActivityIntentInfo filter = filters.get(n);
747                filter.setVerified(verified);
748
749                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
750                        + " verified with result:" + verified + " and hosts:"
751                        + ivs.getHostsString());
752            }
753
754            mIntentFilterVerificationStates.remove(verificationId);
755
756            final String packageName = ivs.getPackageName();
757            IntentFilterVerificationInfo ivi = null;
758
759            synchronized (mPackages) {
760                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
761            }
762            if (ivi == null) {
763                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
764                        + verificationId + " packageName:" + packageName);
765                return;
766            }
767            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
768                    "Updating IntentFilterVerificationInfo for package " + packageName
769                            +" verificationId:" + verificationId);
770
771            synchronized (mPackages) {
772                if (verified) {
773                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
774                } else {
775                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
776                }
777                scheduleWriteSettingsLocked();
778
779                final int userId = ivs.getUserId();
780                if (userId != UserHandle.USER_ALL) {
781                    final int userStatus =
782                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
783
784                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
785                    boolean needUpdate = false;
786
787                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
788                    // already been set by the User thru the Disambiguation dialog
789                    switch (userStatus) {
790                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
791                            if (verified) {
792                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
793                            } else {
794                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
795                            }
796                            needUpdate = true;
797                            break;
798
799                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
800                            if (verified) {
801                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
802                                needUpdate = true;
803                            }
804                            break;
805
806                        default:
807                            // Nothing to do
808                    }
809
810                    if (needUpdate) {
811                        mSettings.updateIntentFilterVerificationStatusLPw(
812                                packageName, updatedStatus, userId);
813                        scheduleWritePackageRestrictionsLocked(userId);
814                    }
815                }
816            }
817        }
818
819        @Override
820        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
821                    ActivityIntentInfo filter, String packageName) {
822            if (!hasValidDomains(filter)) {
823                return false;
824            }
825            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
826            if (ivs == null) {
827                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
828                        packageName);
829            }
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
832            }
833            ivs.addFilter(filter);
834            return true;
835        }
836
837        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
838                int userId, int verificationId, String packageName) {
839            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
840                    verifierUid, userId, packageName);
841            ivs.setPendingState();
842            synchronized (mPackages) {
843                mIntentFilterVerificationStates.append(verificationId, ivs);
844                mCurrentIntentFilterVerifications.add(verificationId);
845            }
846            return ivs;
847        }
848    }
849
850    private static boolean hasValidDomains(ActivityIntentInfo filter) {
851        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
852                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
853                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
854    }
855
856    // Set of pending broadcasts for aggregating enable/disable of components.
857    static class PendingPackageBroadcasts {
858        // for each user id, a map of <package name -> components within that package>
859        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
860
861        public PendingPackageBroadcasts() {
862            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
863        }
864
865        public ArrayList<String> get(int userId, String packageName) {
866            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
867            return packages.get(packageName);
868        }
869
870        public void put(int userId, String packageName, ArrayList<String> components) {
871            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
872            packages.put(packageName, components);
873        }
874
875        public void remove(int userId, String packageName) {
876            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
877            if (packages != null) {
878                packages.remove(packageName);
879            }
880        }
881
882        public void remove(int userId) {
883            mUidMap.remove(userId);
884        }
885
886        public int userIdCount() {
887            return mUidMap.size();
888        }
889
890        public int userIdAt(int n) {
891            return mUidMap.keyAt(n);
892        }
893
894        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
895            return mUidMap.get(userId);
896        }
897
898        public int size() {
899            // total number of pending broadcast entries across all userIds
900            int num = 0;
901            for (int i = 0; i< mUidMap.size(); i++) {
902                num += mUidMap.valueAt(i).size();
903            }
904            return num;
905        }
906
907        public void clear() {
908            mUidMap.clear();
909        }
910
911        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
912            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
913            if (map == null) {
914                map = new ArrayMap<String, ArrayList<String>>();
915                mUidMap.put(userId, map);
916            }
917            return map;
918        }
919    }
920    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
921
922    // Service Connection to remote media container service to copy
923    // package uri's from external media onto secure containers
924    // or internal storage.
925    private IMediaContainerService mContainerService = null;
926
927    static final int SEND_PENDING_BROADCAST = 1;
928    static final int MCS_BOUND = 3;
929    static final int END_COPY = 4;
930    static final int INIT_COPY = 5;
931    static final int MCS_UNBIND = 6;
932    static final int START_CLEANING_PACKAGE = 7;
933    static final int FIND_INSTALL_LOC = 8;
934    static final int POST_INSTALL = 9;
935    static final int MCS_RECONNECT = 10;
936    static final int MCS_GIVE_UP = 11;
937    static final int UPDATED_MEDIA_STATUS = 12;
938    static final int WRITE_SETTINGS = 13;
939    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
940    static final int PACKAGE_VERIFIED = 15;
941    static final int CHECK_PENDING_VERIFICATION = 16;
942    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
943    static final int INTENT_FILTER_VERIFIED = 18;
944
945    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
946
947    // Delay time in millisecs
948    static final int BROADCAST_DELAY = 10 * 1000;
949
950    static UserManagerService sUserManager;
951
952    // Stores a list of users whose package restrictions file needs to be updated
953    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
954
955    final private DefaultContainerConnection mDefContainerConn =
956            new DefaultContainerConnection();
957    class DefaultContainerConnection implements ServiceConnection {
958        public void onServiceConnected(ComponentName name, IBinder service) {
959            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
960            IMediaContainerService imcs =
961                IMediaContainerService.Stub.asInterface(service);
962            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
963        }
964
965        public void onServiceDisconnected(ComponentName name) {
966            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
967        }
968    }
969
970    // Recordkeeping of restore-after-install operations that are currently in flight
971    // between the Package Manager and the Backup Manager
972    static class PostInstallData {
973        public InstallArgs args;
974        public PackageInstalledInfo res;
975
976        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
977            args = _a;
978            res = _r;
979        }
980    }
981
982    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
983    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
984
985    // XML tags for backup/restore of various bits of state
986    private static final String TAG_PREFERRED_BACKUP = "pa";
987    private static final String TAG_DEFAULT_APPS = "da";
988    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
989
990    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
991    private static final String TAG_ALL_GRANTS = "rt-grants";
992    private static final String TAG_GRANT = "grant";
993    private static final String ATTR_PACKAGE_NAME = "pkg";
994
995    private static final String TAG_PERMISSION = "perm";
996    private static final String ATTR_PERMISSION_NAME = "name";
997    private static final String ATTR_IS_GRANTED = "g";
998    private static final String ATTR_USER_SET = "set";
999    private static final String ATTR_USER_FIXED = "fixed";
1000    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1001
1002    // System/policy permission grants are not backed up
1003    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1004            FLAG_PERMISSION_POLICY_FIXED
1005            | FLAG_PERMISSION_SYSTEM_FIXED
1006            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1007
1008    // And we back up these user-adjusted states
1009    private static final int USER_RUNTIME_GRANT_MASK =
1010            FLAG_PERMISSION_USER_SET
1011            | FLAG_PERMISSION_USER_FIXED
1012            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1013
1014    final @Nullable String mRequiredVerifierPackage;
1015    final @Nullable String mRequiredInstallerPackage;
1016
1017    private final PackageUsage mPackageUsage = new PackageUsage();
1018
1019    private class PackageUsage {
1020        private static final int WRITE_INTERVAL
1021            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1022
1023        private final Object mFileLock = new Object();
1024        private final AtomicLong mLastWritten = new AtomicLong(0);
1025        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1026
1027        private boolean mIsHistoricalPackageUsageAvailable = true;
1028
1029        boolean isHistoricalPackageUsageAvailable() {
1030            return mIsHistoricalPackageUsageAvailable;
1031        }
1032
1033        void write(boolean force) {
1034            if (force) {
1035                writeInternal();
1036                return;
1037            }
1038            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1039                && !DEBUG_DEXOPT) {
1040                return;
1041            }
1042            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1043                new Thread("PackageUsage_DiskWriter") {
1044                    @Override
1045                    public void run() {
1046                        try {
1047                            writeInternal();
1048                        } finally {
1049                            mBackgroundWriteRunning.set(false);
1050                        }
1051                    }
1052                }.start();
1053            }
1054        }
1055
1056        private void writeInternal() {
1057            synchronized (mPackages) {
1058                synchronized (mFileLock) {
1059                    AtomicFile file = getFile();
1060                    FileOutputStream f = null;
1061                    try {
1062                        f = file.startWrite();
1063                        BufferedOutputStream out = new BufferedOutputStream(f);
1064                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1065                        StringBuilder sb = new StringBuilder();
1066                        for (PackageParser.Package pkg : mPackages.values()) {
1067                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1068                                continue;
1069                            }
1070                            sb.setLength(0);
1071                            sb.append(pkg.packageName);
1072                            sb.append(' ');
1073                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1074                            sb.append('\n');
1075                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1076                        }
1077                        out.flush();
1078                        file.finishWrite(f);
1079                    } catch (IOException e) {
1080                        if (f != null) {
1081                            file.failWrite(f);
1082                        }
1083                        Log.e(TAG, "Failed to write package usage times", e);
1084                    }
1085                }
1086            }
1087            mLastWritten.set(SystemClock.elapsedRealtime());
1088        }
1089
1090        void readLP() {
1091            synchronized (mFileLock) {
1092                AtomicFile file = getFile();
1093                BufferedInputStream in = null;
1094                try {
1095                    in = new BufferedInputStream(file.openRead());
1096                    StringBuffer sb = new StringBuffer();
1097                    while (true) {
1098                        String packageName = readToken(in, sb, ' ');
1099                        if (packageName == null) {
1100                            break;
1101                        }
1102                        String timeInMillisString = readToken(in, sb, '\n');
1103                        if (timeInMillisString == null) {
1104                            throw new IOException("Failed to find last usage time for package "
1105                                                  + packageName);
1106                        }
1107                        PackageParser.Package pkg = mPackages.get(packageName);
1108                        if (pkg == null) {
1109                            continue;
1110                        }
1111                        long timeInMillis;
1112                        try {
1113                            timeInMillis = Long.parseLong(timeInMillisString);
1114                        } catch (NumberFormatException e) {
1115                            throw new IOException("Failed to parse " + timeInMillisString
1116                                                  + " as a long.", e);
1117                        }
1118                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1119                    }
1120                } catch (FileNotFoundException expected) {
1121                    mIsHistoricalPackageUsageAvailable = false;
1122                } catch (IOException e) {
1123                    Log.w(TAG, "Failed to read package usage times", e);
1124                } finally {
1125                    IoUtils.closeQuietly(in);
1126                }
1127            }
1128            mLastWritten.set(SystemClock.elapsedRealtime());
1129        }
1130
1131        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1132                throws IOException {
1133            sb.setLength(0);
1134            while (true) {
1135                int ch = in.read();
1136                if (ch == -1) {
1137                    if (sb.length() == 0) {
1138                        return null;
1139                    }
1140                    throw new IOException("Unexpected EOF");
1141                }
1142                if (ch == endOfToken) {
1143                    return sb.toString();
1144                }
1145                sb.append((char)ch);
1146            }
1147        }
1148
1149        private AtomicFile getFile() {
1150            File dataDir = Environment.getDataDirectory();
1151            File systemDir = new File(dataDir, "system");
1152            File fname = new File(systemDir, "package-usage.list");
1153            return new AtomicFile(fname);
1154        }
1155    }
1156
1157    class PackageHandler extends Handler {
1158        private boolean mBound = false;
1159        final ArrayList<HandlerParams> mPendingInstalls =
1160            new ArrayList<HandlerParams>();
1161
1162        private boolean connectToService() {
1163            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1164                    " DefaultContainerService");
1165            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1166            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1167            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1168                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1169                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170                mBound = true;
1171                return true;
1172            }
1173            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174            return false;
1175        }
1176
1177        private void disconnectService() {
1178            mContainerService = null;
1179            mBound = false;
1180            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1181            mContext.unbindService(mDefContainerConn);
1182            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1183        }
1184
1185        PackageHandler(Looper looper) {
1186            super(looper);
1187        }
1188
1189        public void handleMessage(Message msg) {
1190            try {
1191                doHandleMessage(msg);
1192            } finally {
1193                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1194            }
1195        }
1196
1197        void doHandleMessage(Message msg) {
1198            switch (msg.what) {
1199                case INIT_COPY: {
1200                    HandlerParams params = (HandlerParams) msg.obj;
1201                    int idx = mPendingInstalls.size();
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1203                    // If a bind was already initiated we dont really
1204                    // need to do anything. The pending install
1205                    // will be processed later on.
1206                    if (!mBound) {
1207                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                System.identityHashCode(mHandler));
1209                        // If this is the only one pending we might
1210                        // have to bind to the service again.
1211                        if (!connectToService()) {
1212                            Slog.e(TAG, "Failed to bind to media container service");
1213                            params.serviceError();
1214                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                    System.identityHashCode(mHandler));
1216                            if (params.traceMethod != null) {
1217                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1218                                        params.traceCookie);
1219                            }
1220                            return;
1221                        } else {
1222                            // Once we bind to the service, the first
1223                            // pending request will be processed.
1224                            mPendingInstalls.add(idx, params);
1225                        }
1226                    } else {
1227                        mPendingInstalls.add(idx, params);
1228                        // Already bound to the service. Just make
1229                        // sure we trigger off processing the first request.
1230                        if (idx == 0) {
1231                            mHandler.sendEmptyMessage(MCS_BOUND);
1232                        }
1233                    }
1234                    break;
1235                }
1236                case MCS_BOUND: {
1237                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1238                    if (msg.obj != null) {
1239                        mContainerService = (IMediaContainerService) msg.obj;
1240                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1241                                System.identityHashCode(mHandler));
1242                    }
1243                    if (mContainerService == null) {
1244                        if (!mBound) {
1245                            // Something seriously wrong since we are not bound and we are not
1246                            // waiting for connection. Bail out.
1247                            Slog.e(TAG, "Cannot bind to media container service");
1248                            for (HandlerParams params : mPendingInstalls) {
1249                                // Indicate service bind error
1250                                params.serviceError();
1251                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1252                                        System.identityHashCode(params));
1253                                if (params.traceMethod != null) {
1254                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1255                                            params.traceMethod, params.traceCookie);
1256                                }
1257                                return;
1258                            }
1259                            mPendingInstalls.clear();
1260                        } else {
1261                            Slog.w(TAG, "Waiting to connect to media container service");
1262                        }
1263                    } else if (mPendingInstalls.size() > 0) {
1264                        HandlerParams params = mPendingInstalls.get(0);
1265                        if (params != null) {
1266                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1267                                    System.identityHashCode(params));
1268                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1269                            if (params.startCopy()) {
1270                                // We are done...  look for more work or to
1271                                // go idle.
1272                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                        "Checking for more work or unbind...");
1274                                // Delete pending install
1275                                if (mPendingInstalls.size() > 0) {
1276                                    mPendingInstalls.remove(0);
1277                                }
1278                                if (mPendingInstalls.size() == 0) {
1279                                    if (mBound) {
1280                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1281                                                "Posting delayed MCS_UNBIND");
1282                                        removeMessages(MCS_UNBIND);
1283                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1284                                        // Unbind after a little delay, to avoid
1285                                        // continual thrashing.
1286                                        sendMessageDelayed(ubmsg, 10000);
1287                                    }
1288                                } else {
1289                                    // There are more pending requests in queue.
1290                                    // Just post MCS_BOUND message to trigger processing
1291                                    // of next pending install.
1292                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1293                                            "Posting MCS_BOUND for next work");
1294                                    mHandler.sendEmptyMessage(MCS_BOUND);
1295                                }
1296                            }
1297                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1298                        }
1299                    } else {
1300                        // Should never happen ideally.
1301                        Slog.w(TAG, "Empty queue");
1302                    }
1303                    break;
1304                }
1305                case MCS_RECONNECT: {
1306                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1307                    if (mPendingInstalls.size() > 0) {
1308                        if (mBound) {
1309                            disconnectService();
1310                        }
1311                        if (!connectToService()) {
1312                            Slog.e(TAG, "Failed to bind to media container service");
1313                            for (HandlerParams params : mPendingInstalls) {
1314                                // Indicate service bind error
1315                                params.serviceError();
1316                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                                        System.identityHashCode(params));
1318                            }
1319                            mPendingInstalls.clear();
1320                        }
1321                    }
1322                    break;
1323                }
1324                case MCS_UNBIND: {
1325                    // If there is no actual work left, then time to unbind.
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1327
1328                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1329                        if (mBound) {
1330                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1331
1332                            disconnectService();
1333                        }
1334                    } else if (mPendingInstalls.size() > 0) {
1335                        // There are more pending requests in queue.
1336                        // Just post MCS_BOUND message to trigger processing
1337                        // of next pending install.
1338                        mHandler.sendEmptyMessage(MCS_BOUND);
1339                    }
1340
1341                    break;
1342                }
1343                case MCS_GIVE_UP: {
1344                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1345                    HandlerParams params = mPendingInstalls.remove(0);
1346                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                            System.identityHashCode(params));
1348                    break;
1349                }
1350                case SEND_PENDING_BROADCAST: {
1351                    String packages[];
1352                    ArrayList<String> components[];
1353                    int size = 0;
1354                    int uids[];
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356                    synchronized (mPackages) {
1357                        if (mPendingBroadcasts == null) {
1358                            return;
1359                        }
1360                        size = mPendingBroadcasts.size();
1361                        if (size <= 0) {
1362                            // Nothing to be done. Just return
1363                            return;
1364                        }
1365                        packages = new String[size];
1366                        components = new ArrayList[size];
1367                        uids = new int[size];
1368                        int i = 0;  // filling out the above arrays
1369
1370                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1371                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1372                            Iterator<Map.Entry<String, ArrayList<String>>> it
1373                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1374                                            .entrySet().iterator();
1375                            while (it.hasNext() && i < size) {
1376                                Map.Entry<String, ArrayList<String>> ent = it.next();
1377                                packages[i] = ent.getKey();
1378                                components[i] = ent.getValue();
1379                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1380                                uids[i] = (ps != null)
1381                                        ? UserHandle.getUid(packageUserId, ps.appId)
1382                                        : -1;
1383                                i++;
1384                            }
1385                        }
1386                        size = i;
1387                        mPendingBroadcasts.clear();
1388                    }
1389                    // Send broadcasts
1390                    for (int i = 0; i < size; i++) {
1391                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1392                    }
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1394                    break;
1395                }
1396                case START_CLEANING_PACKAGE: {
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398                    final String packageName = (String)msg.obj;
1399                    final int userId = msg.arg1;
1400                    final boolean andCode = msg.arg2 != 0;
1401                    synchronized (mPackages) {
1402                        if (userId == UserHandle.USER_ALL) {
1403                            int[] users = sUserManager.getUserIds();
1404                            for (int user : users) {
1405                                mSettings.addPackageToCleanLPw(
1406                                        new PackageCleanItem(user, packageName, andCode));
1407                            }
1408                        } else {
1409                            mSettings.addPackageToCleanLPw(
1410                                    new PackageCleanItem(userId, packageName, andCode));
1411                        }
1412                    }
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                    startCleaningPackages();
1415                } break;
1416                case POST_INSTALL: {
1417                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1418
1419                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1420                    mRunningInstalls.delete(msg.arg1);
1421                    boolean deleteOld = false;
1422
1423                    if (data != null) {
1424                        InstallArgs args = data.args;
1425                        PackageInstalledInfo res = data.res;
1426
1427                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1428                            final String packageName = res.pkg.applicationInfo.packageName;
1429                            res.removedInfo.sendBroadcast(false, true, false);
1430                            Bundle extras = new Bundle(1);
1431                            extras.putInt(Intent.EXTRA_UID, res.uid);
1432
1433                            // Now that we successfully installed the package, grant runtime
1434                            // permissions if requested before broadcasting the install.
1435                            if ((args.installFlags
1436                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1437                                    && res.pkg.applicationInfo.targetSdkVersion
1438                                            >= Build.VERSION_CODES.M) {
1439                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1440                                        args.installGrantPermissions);
1441                            }
1442
1443                            synchronized (mPackages) {
1444                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1445                            }
1446
1447                            // Determine the set of users who are adding this
1448                            // package for the first time vs. those who are seeing
1449                            // an update.
1450                            int[] firstUsers;
1451                            int[] updateUsers = new int[0];
1452                            if (res.origUsers == null || res.origUsers.length == 0) {
1453                                firstUsers = res.newUsers;
1454                            } else {
1455                                firstUsers = new int[0];
1456                                for (int i=0; i<res.newUsers.length; i++) {
1457                                    int user = res.newUsers[i];
1458                                    boolean isNew = true;
1459                                    for (int j=0; j<res.origUsers.length; j++) {
1460                                        if (res.origUsers[j] == user) {
1461                                            isNew = false;
1462                                            break;
1463                                        }
1464                                    }
1465                                    if (isNew) {
1466                                        int[] newFirst = new int[firstUsers.length+1];
1467                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1468                                                firstUsers.length);
1469                                        newFirst[firstUsers.length] = user;
1470                                        firstUsers = newFirst;
1471                                    } else {
1472                                        int[] newUpdate = new int[updateUsers.length+1];
1473                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1474                                                updateUsers.length);
1475                                        newUpdate[updateUsers.length] = user;
1476                                        updateUsers = newUpdate;
1477                                    }
1478                                }
1479                            }
1480                            // don't broadcast for ephemeral installs/updates
1481                            final boolean isEphemeral = isEphemeral(res.pkg);
1482                            if (!isEphemeral) {
1483                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1484                                        extras, 0 /*flags*/, null /*targetPackage*/,
1485                                        null /*finishedReceiver*/, firstUsers);
1486                            }
1487                            final boolean update = res.removedInfo.removedPackage != null;
1488                            if (update) {
1489                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1490                            }
1491                            if (!isEphemeral) {
1492                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1493                                        extras, 0 /*flags*/, null /*targetPackage*/,
1494                                        null /*finishedReceiver*/, updateUsers);
1495                            }
1496                            if (update) {
1497                                if (!isEphemeral) {
1498                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1499                                            packageName, extras, 0 /*flags*/,
1500                                            null /*targetPackage*/, null /*finishedReceiver*/,
1501                                            updateUsers);
1502                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1503                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1504                                            packageName /*targetPackage*/,
1505                                            null /*finishedReceiver*/, updateUsers);
1506                                }
1507
1508                                // treat asec-hosted packages like removable media on upgrade
1509                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1510                                    if (DEBUG_INSTALL) {
1511                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1512                                                + " is ASEC-hosted -> AVAILABLE");
1513                                    }
1514                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1515                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1516                                    pkgList.add(packageName);
1517                                    sendResourcesChangedBroadcast(true, true,
1518                                            pkgList,uidArray, null);
1519                                }
1520                            }
1521                            if (res.removedInfo.args != null) {
1522                                // Remove the replaced package's older resources safely now
1523                                deleteOld = true;
1524                            }
1525
1526
1527                            // Work that needs to happen on first install within each user
1528                            if (firstUsers.length > 0) {
1529                                for (int userId : firstUsers) {
1530                                    synchronized (mPackages) {
1531                                        // If this app is a browser and it's newly-installed for
1532                                        // some users, clear any default-browser state in those
1533                                        // users.  The app's nature doesn't depend on the user,
1534                                        // so we can just check its browser nature in any user
1535                                        // and generalize.
1536                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1537                                            mSettings.setDefaultBrowserPackageNameLPw(
1538                                                    null, userId);
1539                                        }
1540
1541                                        // We may also need to apply pending (restored) runtime
1542                                        // permission grants within these users.
1543                                        mSettings.applyPendingPermissionGrantsLPw(
1544                                                packageName, userId);
1545                                    }
1546                                }
1547                            }
1548                            // Log current value of "unknown sources" setting
1549                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1550                                getUnknownSourcesSettings());
1551                        }
1552                        // Force a gc to clear up things
1553                        Runtime.getRuntime().gc();
1554                        // We delete after a gc for applications  on sdcard.
1555                        if (deleteOld) {
1556                            synchronized (mInstallLock) {
1557                                res.removedInfo.args.doPostDeleteLI(true);
1558                            }
1559                        }
1560                        if (args.observer != null) {
1561                            try {
1562                                Bundle extras = extrasForInstallResult(res);
1563                                args.observer.onPackageInstalled(res.name, res.returnCode,
1564                                        res.returnMsg, extras);
1565                            } catch (RemoteException e) {
1566                                Slog.i(TAG, "Observer no longer exists.");
1567                            }
1568                        }
1569                        if (args.traceMethod != null) {
1570                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1571                                    args.traceCookie);
1572                        }
1573                        return;
1574                    } else {
1575                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1576                    }
1577
1578                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1579                } break;
1580                case UPDATED_MEDIA_STATUS: {
1581                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1582                    boolean reportStatus = msg.arg1 == 1;
1583                    boolean doGc = msg.arg2 == 1;
1584                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1585                    if (doGc) {
1586                        // Force a gc to clear up stale containers.
1587                        Runtime.getRuntime().gc();
1588                    }
1589                    if (msg.obj != null) {
1590                        @SuppressWarnings("unchecked")
1591                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1592                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1593                        // Unload containers
1594                        unloadAllContainers(args);
1595                    }
1596                    if (reportStatus) {
1597                        try {
1598                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1599                            PackageHelper.getMountService().finishMediaUpdate();
1600                        } catch (RemoteException e) {
1601                            Log.e(TAG, "MountService not running?");
1602                        }
1603                    }
1604                } break;
1605                case WRITE_SETTINGS: {
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        removeMessages(WRITE_SETTINGS);
1609                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1610                        mSettings.writeLPr();
1611                        mDirtyUsers.clear();
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                } break;
1615                case WRITE_PACKAGE_RESTRICTIONS: {
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1617                    synchronized (mPackages) {
1618                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1619                        for (int userId : mDirtyUsers) {
1620                            mSettings.writePackageRestrictionsLPr(userId);
1621                        }
1622                        mDirtyUsers.clear();
1623                    }
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1625                } break;
1626                case CHECK_PENDING_VERIFICATION: {
1627                    final int verificationId = msg.arg1;
1628                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1629
1630                    if ((state != null) && !state.timeoutExtended()) {
1631                        final InstallArgs args = state.getInstallArgs();
1632                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1633
1634                        Slog.i(TAG, "Verification timed out for " + originUri);
1635                        mPendingVerification.remove(verificationId);
1636
1637                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1638
1639                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1640                            Slog.i(TAG, "Continuing with installation of " + originUri);
1641                            state.setVerifierResponse(Binder.getCallingUid(),
1642                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1643                            broadcastPackageVerified(verificationId, originUri,
1644                                    PackageManager.VERIFICATION_ALLOW,
1645                                    state.getInstallArgs().getUser());
1646                            try {
1647                                ret = args.copyApk(mContainerService, true);
1648                            } catch (RemoteException e) {
1649                                Slog.e(TAG, "Could not contact the ContainerService");
1650                            }
1651                        } else {
1652                            broadcastPackageVerified(verificationId, originUri,
1653                                    PackageManager.VERIFICATION_REJECT,
1654                                    state.getInstallArgs().getUser());
1655                        }
1656
1657                        Trace.asyncTraceEnd(
1658                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1659
1660                        processPendingInstall(args, ret);
1661                        mHandler.sendEmptyMessage(MCS_UNBIND);
1662                    }
1663                    break;
1664                }
1665                case PACKAGE_VERIFIED: {
1666                    final int verificationId = msg.arg1;
1667
1668                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1669                    if (state == null) {
1670                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1671                        break;
1672                    }
1673
1674                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1675
1676                    state.setVerifierResponse(response.callerUid, response.code);
1677
1678                    if (state.isVerificationComplete()) {
1679                        mPendingVerification.remove(verificationId);
1680
1681                        final InstallArgs args = state.getInstallArgs();
1682                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1683
1684                        int ret;
1685                        if (state.isInstallAllowed()) {
1686                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1687                            broadcastPackageVerified(verificationId, originUri,
1688                                    response.code, state.getInstallArgs().getUser());
1689                            try {
1690                                ret = args.copyApk(mContainerService, true);
1691                            } catch (RemoteException e) {
1692                                Slog.e(TAG, "Could not contact the ContainerService");
1693                            }
1694                        } else {
1695                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1696                        }
1697
1698                        Trace.asyncTraceEnd(
1699                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1700
1701                        processPendingInstall(args, ret);
1702                        mHandler.sendEmptyMessage(MCS_UNBIND);
1703                    }
1704
1705                    break;
1706                }
1707                case START_INTENT_FILTER_VERIFICATIONS: {
1708                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1709                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1710                            params.replacing, params.pkg);
1711                    break;
1712                }
1713                case INTENT_FILTER_VERIFIED: {
1714                    final int verificationId = msg.arg1;
1715
1716                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1717                            verificationId);
1718                    if (state == null) {
1719                        Slog.w(TAG, "Invalid IntentFilter verification token "
1720                                + verificationId + " received");
1721                        break;
1722                    }
1723
1724                    final int userId = state.getUserId();
1725
1726                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1727                            "Processing IntentFilter verification with token:"
1728                            + verificationId + " and userId:" + userId);
1729
1730                    final IntentFilterVerificationResponse response =
1731                            (IntentFilterVerificationResponse) msg.obj;
1732
1733                    state.setVerifierResponse(response.callerUid, response.code);
1734
1735                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1736                            "IntentFilter verification with token:" + verificationId
1737                            + " and userId:" + userId
1738                            + " is settings verifier response with response code:"
1739                            + response.code);
1740
1741                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1742                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1743                                + response.getFailedDomainsString());
1744                    }
1745
1746                    if (state.isVerificationComplete()) {
1747                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1748                    } else {
1749                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1750                                "IntentFilter verification with token:" + verificationId
1751                                + " was not said to be complete");
1752                    }
1753
1754                    break;
1755                }
1756            }
1757        }
1758    }
1759
1760    private StorageEventListener mStorageListener = new StorageEventListener() {
1761        @Override
1762        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1763            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1764                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1765                    final String volumeUuid = vol.getFsUuid();
1766
1767                    // Clean up any users or apps that were removed or recreated
1768                    // while this volume was missing
1769                    reconcileUsers(volumeUuid);
1770                    reconcileApps(volumeUuid);
1771
1772                    // Clean up any install sessions that expired or were
1773                    // cancelled while this volume was missing
1774                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1775
1776                    loadPrivatePackages(vol);
1777
1778                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1779                    unloadPrivatePackages(vol);
1780                }
1781            }
1782
1783            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1784                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1785                    updateExternalMediaStatus(true, false);
1786                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1787                    updateExternalMediaStatus(false, false);
1788                }
1789            }
1790        }
1791
1792        @Override
1793        public void onVolumeForgotten(String fsUuid) {
1794            if (TextUtils.isEmpty(fsUuid)) {
1795                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1796                return;
1797            }
1798
1799            // Remove any apps installed on the forgotten volume
1800            synchronized (mPackages) {
1801                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1802                for (PackageSetting ps : packages) {
1803                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1804                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1805                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1806                }
1807
1808                mSettings.onVolumeForgotten(fsUuid);
1809                mSettings.writeLPr();
1810            }
1811        }
1812    };
1813
1814    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1815            String[] grantedPermissions) {
1816        if (userId >= UserHandle.USER_SYSTEM) {
1817            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1818        } else if (userId == UserHandle.USER_ALL) {
1819            final int[] userIds;
1820            synchronized (mPackages) {
1821                userIds = UserManagerService.getInstance().getUserIds();
1822            }
1823            for (int someUserId : userIds) {
1824                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1825            }
1826        }
1827
1828        // We could have touched GID membership, so flush out packages.list
1829        synchronized (mPackages) {
1830            mSettings.writePackageListLPr();
1831        }
1832    }
1833
1834    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1835            String[] grantedPermissions) {
1836        SettingBase sb = (SettingBase) pkg.mExtras;
1837        if (sb == null) {
1838            return;
1839        }
1840
1841        PermissionsState permissionsState = sb.getPermissionsState();
1842
1843        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1844                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1845
1846        synchronized (mPackages) {
1847            for (String permission : pkg.requestedPermissions) {
1848                BasePermission bp = mSettings.mPermissions.get(permission);
1849                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1850                        && (grantedPermissions == null
1851                               || ArrayUtils.contains(grantedPermissions, permission))) {
1852                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1853                    // Installer cannot change immutable permissions.
1854                    if ((flags & immutableFlags) == 0) {
1855                        grantRuntimePermission(pkg.packageName, permission, userId);
1856                    }
1857                }
1858            }
1859        }
1860    }
1861
1862    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1863        Bundle extras = null;
1864        switch (res.returnCode) {
1865            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1866                extras = new Bundle();
1867                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1868                        res.origPermission);
1869                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1870                        res.origPackage);
1871                break;
1872            }
1873            case PackageManager.INSTALL_SUCCEEDED: {
1874                extras = new Bundle();
1875                extras.putBoolean(Intent.EXTRA_REPLACING,
1876                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1877                break;
1878            }
1879        }
1880        return extras;
1881    }
1882
1883    void scheduleWriteSettingsLocked() {
1884        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1885            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1886        }
1887    }
1888
1889    void scheduleWritePackageRestrictionsLocked(int userId) {
1890        if (!sUserManager.exists(userId)) return;
1891        mDirtyUsers.add(userId);
1892        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1893            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1894        }
1895    }
1896
1897    public static PackageManagerService main(Context context, Installer installer,
1898            boolean factoryTest, boolean onlyCore) {
1899        PackageManagerService m = new PackageManagerService(context, installer,
1900                factoryTest, onlyCore);
1901        m.enableSystemUserPackages();
1902        ServiceManager.addService("package", m);
1903        return m;
1904    }
1905
1906    private void enableSystemUserPackages() {
1907        if (!UserManager.isSplitSystemUser()) {
1908            return;
1909        }
1910        // For system user, enable apps based on the following conditions:
1911        // - app is whitelisted or belong to one of these groups:
1912        //   -- system app which has no launcher icons
1913        //   -- system app which has INTERACT_ACROSS_USERS permission
1914        //   -- system IME app
1915        // - app is not in the blacklist
1916        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1917        Set<String> enableApps = new ArraySet<>();
1918        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1919                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1920                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1921        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1922        enableApps.addAll(wlApps);
1923        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1924                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1925        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1926        enableApps.removeAll(blApps);
1927        Log.i(TAG, "Applications installed for system user: " + enableApps);
1928        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1929                UserHandle.SYSTEM);
1930        final int allAppsSize = allAps.size();
1931        synchronized (mPackages) {
1932            for (int i = 0; i < allAppsSize; i++) {
1933                String pName = allAps.get(i);
1934                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1935                // Should not happen, but we shouldn't be failing if it does
1936                if (pkgSetting == null) {
1937                    continue;
1938                }
1939                boolean install = enableApps.contains(pName);
1940                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1941                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1942                            + " for system user");
1943                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1944                }
1945            }
1946        }
1947    }
1948
1949    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1950        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1951                Context.DISPLAY_SERVICE);
1952        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1953    }
1954
1955    public PackageManagerService(Context context, Installer installer,
1956            boolean factoryTest, boolean onlyCore) {
1957        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1958                SystemClock.uptimeMillis());
1959
1960        if (mSdkVersion <= 0) {
1961            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1962        }
1963
1964        mContext = context;
1965        mFactoryTest = factoryTest;
1966        mOnlyCore = onlyCore;
1967        mMetrics = new DisplayMetrics();
1968        mSettings = new Settings(mPackages);
1969        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1970                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1971        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1972                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1973        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1974                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1975        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1976                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1977        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1978                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1979        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1980                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1981
1982        String separateProcesses = SystemProperties.get("debug.separate_processes");
1983        if (separateProcesses != null && separateProcesses.length() > 0) {
1984            if ("*".equals(separateProcesses)) {
1985                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1986                mSeparateProcesses = null;
1987                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1988            } else {
1989                mDefParseFlags = 0;
1990                mSeparateProcesses = separateProcesses.split(",");
1991                Slog.w(TAG, "Running with debug.separate_processes: "
1992                        + separateProcesses);
1993            }
1994        } else {
1995            mDefParseFlags = 0;
1996            mSeparateProcesses = null;
1997        }
1998
1999        mInstaller = installer;
2000        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2001                "*dexopt*");
2002        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2003
2004        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2005                FgThread.get().getLooper());
2006
2007        getDefaultDisplayMetrics(context, mMetrics);
2008
2009        SystemConfig systemConfig = SystemConfig.getInstance();
2010        mGlobalGids = systemConfig.getGlobalGids();
2011        mSystemPermissions = systemConfig.getSystemPermissions();
2012        mAvailableFeatures = systemConfig.getAvailableFeatures();
2013
2014        synchronized (mInstallLock) {
2015        // writer
2016        synchronized (mPackages) {
2017            mHandlerThread = new ServiceThread(TAG,
2018                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2019            mHandlerThread.start();
2020            mHandler = new PackageHandler(mHandlerThread.getLooper());
2021            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2022
2023            File dataDir = Environment.getDataDirectory();
2024            mAppInstallDir = new File(dataDir, "app");
2025            mAppLib32InstallDir = new File(dataDir, "app-lib");
2026            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2027            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2028            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2029
2030            sUserManager = new UserManagerService(context, this, mPackages);
2031
2032            // Propagate permission configuration in to package manager.
2033            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2034                    = systemConfig.getPermissions();
2035            for (int i=0; i<permConfig.size(); i++) {
2036                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2037                BasePermission bp = mSettings.mPermissions.get(perm.name);
2038                if (bp == null) {
2039                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2040                    mSettings.mPermissions.put(perm.name, bp);
2041                }
2042                if (perm.gids != null) {
2043                    bp.setGids(perm.gids, perm.perUser);
2044                }
2045            }
2046
2047            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2048            for (int i=0; i<libConfig.size(); i++) {
2049                mSharedLibraries.put(libConfig.keyAt(i),
2050                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2051            }
2052
2053            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2054
2055            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2056
2057            String customResolverActivity = Resources.getSystem().getString(
2058                    R.string.config_customResolverActivity);
2059            if (TextUtils.isEmpty(customResolverActivity)) {
2060                customResolverActivity = null;
2061            } else {
2062                mCustomResolverComponentName = ComponentName.unflattenFromString(
2063                        customResolverActivity);
2064            }
2065
2066            long startTime = SystemClock.uptimeMillis();
2067
2068            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2069                    startTime);
2070
2071            // Set flag to monitor and not change apk file paths when
2072            // scanning install directories.
2073            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2074
2075            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2076            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2077
2078            if (bootClassPath == null) {
2079                Slog.w(TAG, "No BOOTCLASSPATH found!");
2080            }
2081
2082            if (systemServerClassPath == null) {
2083                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2084            }
2085
2086            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2087            final String[] dexCodeInstructionSets =
2088                    getDexCodeInstructionSets(
2089                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2090
2091            /**
2092             * Ensure all external libraries have had dexopt run on them.
2093             */
2094            if (mSharedLibraries.size() > 0) {
2095                // NOTE: For now, we're compiling these system "shared libraries"
2096                // (and framework jars) into all available architectures. It's possible
2097                // to compile them only when we come across an app that uses them (there's
2098                // already logic for that in scanPackageLI) but that adds some complexity.
2099                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2100                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2101                        final String lib = libEntry.path;
2102                        if (lib == null) {
2103                            continue;
2104                        }
2105
2106                        try {
2107                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2108                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2109                                // Shared libraries do not have profiles so we perform a full
2110                                // AOT compilation.
2111                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2112                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2113                                        StorageManager.UUID_PRIVATE_INTERNAL,
2114                                        false /*useProfiles*/);
2115                            }
2116                        } catch (FileNotFoundException e) {
2117                            Slog.w(TAG, "Library not found: " + lib);
2118                        } catch (IOException | InstallerException e) {
2119                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2120                                    + e.getMessage());
2121                        }
2122                    }
2123                }
2124            }
2125
2126            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2127
2128            final VersionInfo ver = mSettings.getInternalVersion();
2129            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2130            // when upgrading from pre-M, promote system app permissions from install to runtime
2131            mPromoteSystemApps =
2132                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2133
2134            // save off the names of pre-existing system packages prior to scanning; we don't
2135            // want to automatically grant runtime permissions for new system apps
2136            if (mPromoteSystemApps) {
2137                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2138                while (pkgSettingIter.hasNext()) {
2139                    PackageSetting ps = pkgSettingIter.next();
2140                    if (isSystemApp(ps)) {
2141                        mExistingSystemPackages.add(ps.name);
2142                    }
2143                }
2144            }
2145
2146            // Collect vendor overlay packages.
2147            // (Do this before scanning any apps.)
2148            // For security and version matching reason, only consider
2149            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2150            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2151            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2152                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2153
2154            // Find base frameworks (resource packages without code).
2155            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2156                    | PackageParser.PARSE_IS_SYSTEM_DIR
2157                    | PackageParser.PARSE_IS_PRIVILEGED,
2158                    scanFlags | SCAN_NO_DEX, 0);
2159
2160            // Collected privileged system packages.
2161            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2162            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2163                    | PackageParser.PARSE_IS_SYSTEM_DIR
2164                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2165
2166            // Collect ordinary system packages.
2167            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2168            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2169                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2170
2171            // Collect all vendor packages.
2172            File vendorAppDir = new File("/vendor/app");
2173            try {
2174                vendorAppDir = vendorAppDir.getCanonicalFile();
2175            } catch (IOException e) {
2176                // failed to look up canonical path, continue with original one
2177            }
2178            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2179                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2180
2181            // Collect all OEM packages.
2182            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2183            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2184                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2185
2186            // Prune any system packages that no longer exist.
2187            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2188            if (!mOnlyCore) {
2189                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2190                while (psit.hasNext()) {
2191                    PackageSetting ps = psit.next();
2192
2193                    /*
2194                     * If this is not a system app, it can't be a
2195                     * disable system app.
2196                     */
2197                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2198                        continue;
2199                    }
2200
2201                    /*
2202                     * If the package is scanned, it's not erased.
2203                     */
2204                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2205                    if (scannedPkg != null) {
2206                        /*
2207                         * If the system app is both scanned and in the
2208                         * disabled packages list, then it must have been
2209                         * added via OTA. Remove it from the currently
2210                         * scanned package so the previously user-installed
2211                         * application can be scanned.
2212                         */
2213                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2214                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2215                                    + ps.name + "; removing system app.  Last known codePath="
2216                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2217                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2218                                    + scannedPkg.mVersionCode);
2219                            removePackageLI(ps, true);
2220                            mExpectingBetter.put(ps.name, ps.codePath);
2221                        }
2222
2223                        continue;
2224                    }
2225
2226                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2227                        psit.remove();
2228                        logCriticalInfo(Log.WARN, "System package " + ps.name
2229                                + " no longer exists; wiping its data");
2230                        removeDataDirsLI(null, ps.name);
2231                    } else {
2232                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2233                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2234                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2235                        }
2236                    }
2237                }
2238            }
2239
2240            //look for any incomplete package installations
2241            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2242            //clean up list
2243            for(int i = 0; i < deletePkgsList.size(); i++) {
2244                //clean up here
2245                cleanupInstallFailedPackage(deletePkgsList.get(i));
2246            }
2247            //delete tmp files
2248            deleteTempPackageFiles();
2249
2250            // Remove any shared userIDs that have no associated packages
2251            mSettings.pruneSharedUsersLPw();
2252
2253            if (!mOnlyCore) {
2254                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2255                        SystemClock.uptimeMillis());
2256                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2257
2258                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2259                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2260
2261                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2262                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2263
2264                /**
2265                 * Remove disable package settings for any updated system
2266                 * apps that were removed via an OTA. If they're not a
2267                 * previously-updated app, remove them completely.
2268                 * Otherwise, just revoke their system-level permissions.
2269                 */
2270                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2271                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2272                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2273
2274                    String msg;
2275                    if (deletedPkg == null) {
2276                        msg = "Updated system package " + deletedAppName
2277                                + " no longer exists; wiping its data";
2278                        removeDataDirsLI(null, deletedAppName);
2279                    } else {
2280                        msg = "Updated system app + " + deletedAppName
2281                                + " no longer present; removing system privileges for "
2282                                + deletedAppName;
2283
2284                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2285
2286                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2287                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2288                    }
2289                    logCriticalInfo(Log.WARN, msg);
2290                }
2291
2292                /**
2293                 * Make sure all system apps that we expected to appear on
2294                 * the userdata partition actually showed up. If they never
2295                 * appeared, crawl back and revive the system version.
2296                 */
2297                for (int i = 0; i < mExpectingBetter.size(); i++) {
2298                    final String packageName = mExpectingBetter.keyAt(i);
2299                    if (!mPackages.containsKey(packageName)) {
2300                        final File scanFile = mExpectingBetter.valueAt(i);
2301
2302                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2303                                + " but never showed up; reverting to system");
2304
2305                        final int reparseFlags;
2306                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2307                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2308                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2309                                    | PackageParser.PARSE_IS_PRIVILEGED;
2310                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2311                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2312                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2313                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2314                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2315                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2316                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2317                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2318                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2319                        } else {
2320                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2321                            continue;
2322                        }
2323
2324                        mSettings.enableSystemPackageLPw(packageName);
2325
2326                        try {
2327                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2328                        } catch (PackageManagerException e) {
2329                            Slog.e(TAG, "Failed to parse original system package: "
2330                                    + e.getMessage());
2331                        }
2332                    }
2333                }
2334            }
2335            mExpectingBetter.clear();
2336
2337            // Now that we know all of the shared libraries, update all clients to have
2338            // the correct library paths.
2339            updateAllSharedLibrariesLPw();
2340
2341            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2342                // NOTE: We ignore potential failures here during a system scan (like
2343                // the rest of the commands above) because there's precious little we
2344                // can do about it. A settings error is reported, though.
2345                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2346                        false /* boot complete */);
2347            }
2348
2349            // Now that we know all the packages we are keeping,
2350            // read and update their last usage times.
2351            mPackageUsage.readLP();
2352
2353            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2354                    SystemClock.uptimeMillis());
2355            Slog.i(TAG, "Time to scan packages: "
2356                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2357                    + " seconds");
2358
2359            // If the platform SDK has changed since the last time we booted,
2360            // we need to re-grant app permission to catch any new ones that
2361            // appear.  This is really a hack, and means that apps can in some
2362            // cases get permissions that the user didn't initially explicitly
2363            // allow...  it would be nice to have some better way to handle
2364            // this situation.
2365            int updateFlags = UPDATE_PERMISSIONS_ALL;
2366            if (ver.sdkVersion != mSdkVersion) {
2367                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2368                        + mSdkVersion + "; regranting permissions for internal storage");
2369                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2370            }
2371            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2372            ver.sdkVersion = mSdkVersion;
2373
2374            // If this is the first boot or an update from pre-M, and it is a normal
2375            // boot, then we need to initialize the default preferred apps across
2376            // all defined users.
2377            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2378                for (UserInfo user : sUserManager.getUsers(true)) {
2379                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2380                    applyFactoryDefaultBrowserLPw(user.id);
2381                    primeDomainVerificationsLPw(user.id);
2382                }
2383            }
2384
2385            // Prepare storage for system user really early during boot,
2386            // since core system apps like SettingsProvider and SystemUI
2387            // can't wait for user to start
2388            final int storageFlags;
2389            if (StorageManager.isFileBasedEncryptionEnabled()) {
2390                storageFlags = StorageManager.FLAG_STORAGE_DE;
2391            } else {
2392                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2393            }
2394            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2395                    storageFlags);
2396
2397            if (!StorageManager.isFileBasedEncryptionEnabled()
2398                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2399                // When upgrading a non-FBE device, we might need to shuffle
2400                // around the default storage location of system apps
2401                final List<UserInfo> users = sUserManager.getUsers(true);
2402                for (PackageSetting ps : mSettings.mPackages.values()) {
2403                    if (ps.pkg == null || !ps.isSystem()) continue;
2404                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2405                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2406                    for (UserInfo user : users) {
2407                        if (ps.getInstalled(user.id)) {
2408                            try {
2409                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2410                                        ps.name, user.id, storageTarget);
2411                            } catch (InstallerException e) {
2412                                logCriticalInfo(Log.WARN,
2413                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2414                            }
2415                            // We may have just shuffled around app data
2416                            // directories, so prepare it one more time
2417                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2418                                    storageFlags, ps.pkg, false);
2419                        }
2420                    }
2421                }
2422            }
2423
2424            // If this is first boot after an OTA, and a normal boot, then
2425            // we need to clear code cache directories.
2426            if (mIsUpgrade && !onlyCore) {
2427                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2428                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2429                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2430                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2431                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2432                    }
2433                }
2434                ver.fingerprint = Build.FINGERPRINT;
2435            }
2436
2437            checkDefaultBrowser();
2438
2439            // clear only after permissions and other defaults have been updated
2440            mExistingSystemPackages.clear();
2441            mPromoteSystemApps = false;
2442
2443            // All the changes are done during package scanning.
2444            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2445
2446            // can downgrade to reader
2447            mSettings.writeLPr();
2448
2449            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2450                    SystemClock.uptimeMillis());
2451
2452            if (!mOnlyCore) {
2453                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2454                mRequiredInstallerPackage = getRequiredInstallerLPr();
2455                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2456                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2457                        mIntentFilterVerifierComponent);
2458            } else {
2459                mRequiredVerifierPackage = null;
2460                mRequiredInstallerPackage = null;
2461                mIntentFilterVerifierComponent = null;
2462                mIntentFilterVerifier = null;
2463            }
2464
2465            mInstallerService = new PackageInstallerService(context, this);
2466
2467            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2468            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2469            // both the installer and resolver must be present to enable ephemeral
2470            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2471                if (DEBUG_EPHEMERAL) {
2472                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2473                            + " installer:" + ephemeralInstallerComponent);
2474                }
2475                mEphemeralResolverComponent = ephemeralResolverComponent;
2476                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2477                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2478                mEphemeralResolverConnection =
2479                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2480            } else {
2481                if (DEBUG_EPHEMERAL) {
2482                    final String missingComponent =
2483                            (ephemeralResolverComponent == null)
2484                            ? (ephemeralInstallerComponent == null)
2485                                    ? "resolver and installer"
2486                                    : "resolver"
2487                            : "installer";
2488                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2489                }
2490                mEphemeralResolverComponent = null;
2491                mEphemeralInstallerComponent = null;
2492                mEphemeralResolverConnection = null;
2493            }
2494
2495            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2496        } // synchronized (mPackages)
2497        } // synchronized (mInstallLock)
2498
2499        // Now after opening every single application zip, make sure they
2500        // are all flushed.  Not really needed, but keeps things nice and
2501        // tidy.
2502        Runtime.getRuntime().gc();
2503
2504        // The initial scanning above does many calls into installd while
2505        // holding the mPackages lock, but we're mostly interested in yelling
2506        // once we have a booted system.
2507        mInstaller.setWarnIfHeld(mPackages);
2508
2509        // Expose private service for system components to use.
2510        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2511    }
2512
2513    @Override
2514    public boolean isFirstBoot() {
2515        return !mRestoredSettings;
2516    }
2517
2518    @Override
2519    public boolean isOnlyCoreApps() {
2520        return mOnlyCore;
2521    }
2522
2523    @Override
2524    public boolean isUpgrade() {
2525        return mIsUpgrade;
2526    }
2527
2528    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2529        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2530
2531        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2532                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2533        if (matches.size() == 1) {
2534            return matches.get(0).getComponentInfo().packageName;
2535        } else {
2536            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2537            return null;
2538        }
2539    }
2540
2541    private @NonNull String getRequiredInstallerLPr() {
2542        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2543        intent.addCategory(Intent.CATEGORY_DEFAULT);
2544        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2545
2546        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2547                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2548        if (matches.size() == 1) {
2549            return matches.get(0).getComponentInfo().packageName;
2550        } else {
2551            throw new RuntimeException("There must be exactly one installer; found " + matches);
2552        }
2553    }
2554
2555    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2556        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2557
2558        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2559                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2560        ResolveInfo best = null;
2561        final int N = matches.size();
2562        for (int i = 0; i < N; i++) {
2563            final ResolveInfo cur = matches.get(i);
2564            final String packageName = cur.getComponentInfo().packageName;
2565            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2566                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2567                continue;
2568            }
2569
2570            if (best == null || cur.priority > best.priority) {
2571                best = cur;
2572            }
2573        }
2574
2575        if (best != null) {
2576            return best.getComponentInfo().getComponentName();
2577        } else {
2578            throw new RuntimeException("There must be at least one intent filter verifier");
2579        }
2580    }
2581
2582    private @Nullable ComponentName getEphemeralResolverLPr() {
2583        final String[] packageArray =
2584                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2585        if (packageArray.length == 0) {
2586            if (DEBUG_EPHEMERAL) {
2587                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2588            }
2589            return null;
2590        }
2591
2592        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2593        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2594                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2595
2596        final int N = resolvers.size();
2597        if (N == 0) {
2598            if (DEBUG_EPHEMERAL) {
2599                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2600            }
2601            return null;
2602        }
2603
2604        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2605        for (int i = 0; i < N; i++) {
2606            final ResolveInfo info = resolvers.get(i);
2607
2608            if (info.serviceInfo == null) {
2609                continue;
2610            }
2611
2612            final String packageName = info.serviceInfo.packageName;
2613            if (!possiblePackages.contains(packageName)) {
2614                if (DEBUG_EPHEMERAL) {
2615                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2616                            + " pkg: " + packageName + ", info:" + info);
2617                }
2618                continue;
2619            }
2620
2621            if (DEBUG_EPHEMERAL) {
2622                Slog.v(TAG, "Ephemeral resolver found;"
2623                        + " pkg: " + packageName + ", info:" + info);
2624            }
2625            return new ComponentName(packageName, info.serviceInfo.name);
2626        }
2627        if (DEBUG_EPHEMERAL) {
2628            Slog.v(TAG, "Ephemeral resolver NOT found");
2629        }
2630        return null;
2631    }
2632
2633    private @Nullable ComponentName getEphemeralInstallerLPr() {
2634        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2635        intent.addCategory(Intent.CATEGORY_DEFAULT);
2636        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2637
2638        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2639                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2640        if (matches.size() == 0) {
2641            return null;
2642        } else if (matches.size() == 1) {
2643            return matches.get(0).getComponentInfo().getComponentName();
2644        } else {
2645            throw new RuntimeException(
2646                    "There must be at most one ephemeral installer; found " + matches);
2647        }
2648    }
2649
2650    private void primeDomainVerificationsLPw(int userId) {
2651        if (DEBUG_DOMAIN_VERIFICATION) {
2652            Slog.d(TAG, "Priming domain verifications in user " + userId);
2653        }
2654
2655        SystemConfig systemConfig = SystemConfig.getInstance();
2656        ArraySet<String> packages = systemConfig.getLinkedApps();
2657        ArraySet<String> domains = new ArraySet<String>();
2658
2659        for (String packageName : packages) {
2660            PackageParser.Package pkg = mPackages.get(packageName);
2661            if (pkg != null) {
2662                if (!pkg.isSystemApp()) {
2663                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2664                    continue;
2665                }
2666
2667                domains.clear();
2668                for (PackageParser.Activity a : pkg.activities) {
2669                    for (ActivityIntentInfo filter : a.intents) {
2670                        if (hasValidDomains(filter)) {
2671                            domains.addAll(filter.getHostsList());
2672                        }
2673                    }
2674                }
2675
2676                if (domains.size() > 0) {
2677                    if (DEBUG_DOMAIN_VERIFICATION) {
2678                        Slog.v(TAG, "      + " + packageName);
2679                    }
2680                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2681                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2682                    // and then 'always' in the per-user state actually used for intent resolution.
2683                    final IntentFilterVerificationInfo ivi;
2684                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2685                            new ArrayList<String>(domains));
2686                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2687                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2688                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2689                } else {
2690                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2691                            + "' does not handle web links");
2692                }
2693            } else {
2694                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2695            }
2696        }
2697
2698        scheduleWritePackageRestrictionsLocked(userId);
2699        scheduleWriteSettingsLocked();
2700    }
2701
2702    private void applyFactoryDefaultBrowserLPw(int userId) {
2703        // The default browser app's package name is stored in a string resource,
2704        // with a product-specific overlay used for vendor customization.
2705        String browserPkg = mContext.getResources().getString(
2706                com.android.internal.R.string.default_browser);
2707        if (!TextUtils.isEmpty(browserPkg)) {
2708            // non-empty string => required to be a known package
2709            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2710            if (ps == null) {
2711                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2712                browserPkg = null;
2713            } else {
2714                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2715            }
2716        }
2717
2718        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2719        // default.  If there's more than one, just leave everything alone.
2720        if (browserPkg == null) {
2721            calculateDefaultBrowserLPw(userId);
2722        }
2723    }
2724
2725    private void calculateDefaultBrowserLPw(int userId) {
2726        List<String> allBrowsers = resolveAllBrowserApps(userId);
2727        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2728        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2729    }
2730
2731    private List<String> resolveAllBrowserApps(int userId) {
2732        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2733        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2734                PackageManager.MATCH_ALL, userId);
2735
2736        final int count = list.size();
2737        List<String> result = new ArrayList<String>(count);
2738        for (int i=0; i<count; i++) {
2739            ResolveInfo info = list.get(i);
2740            if (info.activityInfo == null
2741                    || !info.handleAllWebDataURI
2742                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2743                    || result.contains(info.activityInfo.packageName)) {
2744                continue;
2745            }
2746            result.add(info.activityInfo.packageName);
2747        }
2748
2749        return result;
2750    }
2751
2752    private boolean packageIsBrowser(String packageName, int userId) {
2753        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2754                PackageManager.MATCH_ALL, userId);
2755        final int N = list.size();
2756        for (int i = 0; i < N; i++) {
2757            ResolveInfo info = list.get(i);
2758            if (packageName.equals(info.activityInfo.packageName)) {
2759                return true;
2760            }
2761        }
2762        return false;
2763    }
2764
2765    private void checkDefaultBrowser() {
2766        final int myUserId = UserHandle.myUserId();
2767        final String packageName = getDefaultBrowserPackageName(myUserId);
2768        if (packageName != null) {
2769            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2770            if (info == null) {
2771                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2772                synchronized (mPackages) {
2773                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2774                }
2775            }
2776        }
2777    }
2778
2779    @Override
2780    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2781            throws RemoteException {
2782        try {
2783            return super.onTransact(code, data, reply, flags);
2784        } catch (RuntimeException e) {
2785            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2786                Slog.wtf(TAG, "Package Manager Crash", e);
2787            }
2788            throw e;
2789        }
2790    }
2791
2792    void cleanupInstallFailedPackage(PackageSetting ps) {
2793        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2794
2795        removeDataDirsLI(ps.volumeUuid, ps.name);
2796        if (ps.codePath != null) {
2797            removeCodePathLI(ps.codePath);
2798        }
2799        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2800            if (ps.resourcePath.isDirectory()) {
2801                FileUtils.deleteContents(ps.resourcePath);
2802            }
2803            ps.resourcePath.delete();
2804        }
2805        mSettings.removePackageLPw(ps.name);
2806    }
2807
2808    static int[] appendInts(int[] cur, int[] add) {
2809        if (add == null) return cur;
2810        if (cur == null) return add;
2811        final int N = add.length;
2812        for (int i=0; i<N; i++) {
2813            cur = appendInt(cur, add[i]);
2814        }
2815        return cur;
2816    }
2817
2818    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2819        if (!sUserManager.exists(userId)) return null;
2820        final PackageSetting ps = (PackageSetting) p.mExtras;
2821        if (ps == null) {
2822            return null;
2823        }
2824
2825        final PermissionsState permissionsState = ps.getPermissionsState();
2826
2827        final int[] gids = permissionsState.computeGids(userId);
2828        final Set<String> permissions = permissionsState.getPermissions(userId);
2829        final PackageUserState state = ps.readUserState(userId);
2830
2831        return PackageParser.generatePackageInfo(p, gids, flags,
2832                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2833    }
2834
2835    @Override
2836    public void checkPackageStartable(String packageName, int userId) {
2837        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2838
2839        synchronized (mPackages) {
2840            final PackageSetting ps = mSettings.mPackages.get(packageName);
2841            if (ps == null) {
2842                throw new SecurityException("Package " + packageName + " was not found!");
2843            }
2844
2845            if (ps.frozen) {
2846                throw new SecurityException("Package " + packageName + " is currently frozen!");
2847            }
2848
2849            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2850                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2851                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2852            }
2853        }
2854    }
2855
2856    @Override
2857    public boolean isPackageAvailable(String packageName, int userId) {
2858        if (!sUserManager.exists(userId)) return false;
2859        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2860        synchronized (mPackages) {
2861            PackageParser.Package p = mPackages.get(packageName);
2862            if (p != null) {
2863                final PackageSetting ps = (PackageSetting) p.mExtras;
2864                if (ps != null) {
2865                    final PackageUserState state = ps.readUserState(userId);
2866                    if (state != null) {
2867                        return PackageParser.isAvailable(state);
2868                    }
2869                }
2870            }
2871        }
2872        return false;
2873    }
2874
2875    @Override
2876    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2877        if (!sUserManager.exists(userId)) return null;
2878        flags = updateFlagsForPackage(flags, userId, packageName);
2879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2880        // reader
2881        synchronized (mPackages) {
2882            PackageParser.Package p = mPackages.get(packageName);
2883            if (DEBUG_PACKAGE_INFO)
2884                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2885            if (p != null) {
2886                return generatePackageInfo(p, flags, userId);
2887            }
2888            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2889                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2890            }
2891        }
2892        return null;
2893    }
2894
2895    @Override
2896    public String[] currentToCanonicalPackageNames(String[] names) {
2897        String[] out = new String[names.length];
2898        // reader
2899        synchronized (mPackages) {
2900            for (int i=names.length-1; i>=0; i--) {
2901                PackageSetting ps = mSettings.mPackages.get(names[i]);
2902                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2903            }
2904        }
2905        return out;
2906    }
2907
2908    @Override
2909    public String[] canonicalToCurrentPackageNames(String[] names) {
2910        String[] out = new String[names.length];
2911        // reader
2912        synchronized (mPackages) {
2913            for (int i=names.length-1; i>=0; i--) {
2914                String cur = mSettings.mRenamedPackages.get(names[i]);
2915                out[i] = cur != null ? cur : names[i];
2916            }
2917        }
2918        return out;
2919    }
2920
2921    @Override
2922    public int getPackageUid(String packageName, int flags, int userId) {
2923        if (!sUserManager.exists(userId)) return -1;
2924        flags = updateFlagsForPackage(flags, userId, packageName);
2925        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2926
2927        // reader
2928        synchronized (mPackages) {
2929            final PackageParser.Package p = mPackages.get(packageName);
2930            if (p != null && p.isMatch(flags)) {
2931                return UserHandle.getUid(userId, p.applicationInfo.uid);
2932            }
2933            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2934                final PackageSetting ps = mSettings.mPackages.get(packageName);
2935                if (ps != null && ps.isMatch(flags)) {
2936                    return UserHandle.getUid(userId, ps.appId);
2937                }
2938            }
2939        }
2940
2941        return -1;
2942    }
2943
2944    @Override
2945    public int[] getPackageGids(String packageName, int flags, int userId) {
2946        if (!sUserManager.exists(userId)) return null;
2947        flags = updateFlagsForPackage(flags, userId, packageName);
2948        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2949                "getPackageGids");
2950
2951        // reader
2952        synchronized (mPackages) {
2953            final PackageParser.Package p = mPackages.get(packageName);
2954            if (p != null && p.isMatch(flags)) {
2955                PackageSetting ps = (PackageSetting) p.mExtras;
2956                return ps.getPermissionsState().computeGids(userId);
2957            }
2958            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2959                final PackageSetting ps = mSettings.mPackages.get(packageName);
2960                if (ps != null && ps.isMatch(flags)) {
2961                    return ps.getPermissionsState().computeGids(userId);
2962                }
2963            }
2964        }
2965
2966        return null;
2967    }
2968
2969    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2970        if (bp.perm != null) {
2971            return PackageParser.generatePermissionInfo(bp.perm, flags);
2972        }
2973        PermissionInfo pi = new PermissionInfo();
2974        pi.name = bp.name;
2975        pi.packageName = bp.sourcePackage;
2976        pi.nonLocalizedLabel = bp.name;
2977        pi.protectionLevel = bp.protectionLevel;
2978        return pi;
2979    }
2980
2981    @Override
2982    public PermissionInfo getPermissionInfo(String name, int flags) {
2983        // reader
2984        synchronized (mPackages) {
2985            final BasePermission p = mSettings.mPermissions.get(name);
2986            if (p != null) {
2987                return generatePermissionInfo(p, flags);
2988            }
2989            return null;
2990        }
2991    }
2992
2993    @Override
2994    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2995        // reader
2996        synchronized (mPackages) {
2997            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2998            for (BasePermission p : mSettings.mPermissions.values()) {
2999                if (group == null) {
3000                    if (p.perm == null || p.perm.info.group == null) {
3001                        out.add(generatePermissionInfo(p, flags));
3002                    }
3003                } else {
3004                    if (p.perm != null && group.equals(p.perm.info.group)) {
3005                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3006                    }
3007                }
3008            }
3009
3010            if (out.size() > 0) {
3011                return out;
3012            }
3013            return mPermissionGroups.containsKey(group) ? out : null;
3014        }
3015    }
3016
3017    @Override
3018    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3019        // reader
3020        synchronized (mPackages) {
3021            return PackageParser.generatePermissionGroupInfo(
3022                    mPermissionGroups.get(name), flags);
3023        }
3024    }
3025
3026    @Override
3027    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3028        // reader
3029        synchronized (mPackages) {
3030            final int N = mPermissionGroups.size();
3031            ArrayList<PermissionGroupInfo> out
3032                    = new ArrayList<PermissionGroupInfo>(N);
3033            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3034                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3035            }
3036            return out;
3037        }
3038    }
3039
3040    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3041            int userId) {
3042        if (!sUserManager.exists(userId)) return null;
3043        PackageSetting ps = mSettings.mPackages.get(packageName);
3044        if (ps != null) {
3045            if (ps.pkg == null) {
3046                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3047                        flags, userId);
3048                if (pInfo != null) {
3049                    return pInfo.applicationInfo;
3050                }
3051                return null;
3052            }
3053            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3054                    ps.readUserState(userId), userId);
3055        }
3056        return null;
3057    }
3058
3059    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3060            int userId) {
3061        if (!sUserManager.exists(userId)) return null;
3062        PackageSetting ps = mSettings.mPackages.get(packageName);
3063        if (ps != null) {
3064            PackageParser.Package pkg = ps.pkg;
3065            if (pkg == null) {
3066                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3067                    return null;
3068                }
3069                // Only data remains, so we aren't worried about code paths
3070                pkg = new PackageParser.Package(packageName);
3071                pkg.applicationInfo.packageName = packageName;
3072                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3073                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3074                pkg.applicationInfo.uid = ps.appId;
3075                pkg.applicationInfo.initForUser(userId);
3076                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3077                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3078            }
3079            return generatePackageInfo(pkg, flags, userId);
3080        }
3081        return null;
3082    }
3083
3084    @Override
3085    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3086        if (!sUserManager.exists(userId)) return null;
3087        flags = updateFlagsForApplication(flags, userId, packageName);
3088        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3089        // writer
3090        synchronized (mPackages) {
3091            PackageParser.Package p = mPackages.get(packageName);
3092            if (DEBUG_PACKAGE_INFO) Log.v(
3093                    TAG, "getApplicationInfo " + packageName
3094                    + ": " + p);
3095            if (p != null) {
3096                PackageSetting ps = mSettings.mPackages.get(packageName);
3097                if (ps == null) return null;
3098                // Note: isEnabledLP() does not apply here - always return info
3099                return PackageParser.generateApplicationInfo(
3100                        p, flags, ps.readUserState(userId), userId);
3101            }
3102            if ("android".equals(packageName)||"system".equals(packageName)) {
3103                return mAndroidApplication;
3104            }
3105            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3106                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3107            }
3108        }
3109        return null;
3110    }
3111
3112    @Override
3113    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3114            final IPackageDataObserver observer) {
3115        mContext.enforceCallingOrSelfPermission(
3116                android.Manifest.permission.CLEAR_APP_CACHE, null);
3117        // Queue up an async operation since clearing cache may take a little while.
3118        mHandler.post(new Runnable() {
3119            public void run() {
3120                mHandler.removeCallbacks(this);
3121                boolean success = true;
3122                synchronized (mInstallLock) {
3123                    try {
3124                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3125                    } catch (InstallerException e) {
3126                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3127                        success = false;
3128                    }
3129                }
3130                if (observer != null) {
3131                    try {
3132                        observer.onRemoveCompleted(null, success);
3133                    } catch (RemoteException e) {
3134                        Slog.w(TAG, "RemoveException when invoking call back");
3135                    }
3136                }
3137            }
3138        });
3139    }
3140
3141    @Override
3142    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3143            final IntentSender pi) {
3144        mContext.enforceCallingOrSelfPermission(
3145                android.Manifest.permission.CLEAR_APP_CACHE, null);
3146        // Queue up an async operation since clearing cache may take a little while.
3147        mHandler.post(new Runnable() {
3148            public void run() {
3149                mHandler.removeCallbacks(this);
3150                boolean success = true;
3151                synchronized (mInstallLock) {
3152                    try {
3153                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3154                    } catch (InstallerException e) {
3155                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3156                        success = false;
3157                    }
3158                }
3159                if(pi != null) {
3160                    try {
3161                        // Callback via pending intent
3162                        int code = success ? 1 : 0;
3163                        pi.sendIntent(null, code, null,
3164                                null, null);
3165                    } catch (SendIntentException e1) {
3166                        Slog.i(TAG, "Failed to send pending intent");
3167                    }
3168                }
3169            }
3170        });
3171    }
3172
3173    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3174        synchronized (mInstallLock) {
3175            try {
3176                mInstaller.freeCache(volumeUuid, freeStorageSize);
3177            } catch (InstallerException e) {
3178                throw new IOException("Failed to free enough space", e);
3179            }
3180        }
3181    }
3182
3183    /**
3184     * Return if the user key is currently unlocked.
3185     */
3186    private boolean isUserKeyUnlocked(int userId) {
3187        if (StorageManager.isFileBasedEncryptionEnabled()) {
3188            final IMountService mount = IMountService.Stub
3189                    .asInterface(ServiceManager.getService("mount"));
3190            if (mount == null) {
3191                Slog.w(TAG, "Early during boot, assuming locked");
3192                return false;
3193            }
3194            final long token = Binder.clearCallingIdentity();
3195            try {
3196                return mount.isUserKeyUnlocked(userId);
3197            } catch (RemoteException e) {
3198                throw e.rethrowAsRuntimeException();
3199            } finally {
3200                Binder.restoreCallingIdentity(token);
3201            }
3202        } else {
3203            return true;
3204        }
3205    }
3206
3207    /**
3208     * Update given flags based on encryption status of current user.
3209     */
3210    private int updateFlags(int flags, int userId) {
3211        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3212                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3213            // Caller expressed an explicit opinion about what encryption
3214            // aware/unaware components they want to see, so fall through and
3215            // give them what they want
3216        } else {
3217            // Caller expressed no opinion, so match based on user state
3218            if (isUserKeyUnlocked(userId)) {
3219                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3220            } else {
3221                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3222            }
3223        }
3224
3225        // Safe mode means we should ignore any third-party apps
3226        if (mSafeMode) {
3227            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3228        }
3229
3230        return flags;
3231    }
3232
3233    /**
3234     * Update given flags when being used to request {@link PackageInfo}.
3235     */
3236    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3237        boolean triaged = true;
3238        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3239                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3240            // Caller is asking for component details, so they'd better be
3241            // asking for specific encryption matching behavior, or be triaged
3242            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3243                    | PackageManager.MATCH_ENCRYPTION_AWARE
3244                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3245                triaged = false;
3246            }
3247        }
3248        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3249                | PackageManager.MATCH_SYSTEM_ONLY
3250                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3251            triaged = false;
3252        }
3253        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3254            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3255                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3256        }
3257        return updateFlags(flags, userId);
3258    }
3259
3260    /**
3261     * Update given flags when being used to request {@link ApplicationInfo}.
3262     */
3263    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3264        return updateFlagsForPackage(flags, userId, cookie);
3265    }
3266
3267    /**
3268     * Update given flags when being used to request {@link ComponentInfo}.
3269     */
3270    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3271        if (cookie instanceof Intent) {
3272            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3273                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3274            }
3275        }
3276
3277        boolean triaged = true;
3278        // Caller is asking for component details, so they'd better be
3279        // asking for specific encryption matching behavior, or be triaged
3280        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3281                | PackageManager.MATCH_ENCRYPTION_AWARE
3282                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3283            triaged = false;
3284        }
3285        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3286            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3287                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3288        }
3289        return updateFlags(flags, userId);
3290    }
3291
3292    /**
3293     * Update given flags when being used to request {@link ResolveInfo}.
3294     */
3295    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3296        return updateFlagsForComponent(flags, userId, cookie);
3297    }
3298
3299    @Override
3300    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3301        if (!sUserManager.exists(userId)) return null;
3302        flags = updateFlagsForComponent(flags, userId, component);
3303        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3304        synchronized (mPackages) {
3305            PackageParser.Activity a = mActivities.mActivities.get(component);
3306
3307            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3308            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3309                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3310                if (ps == null) return null;
3311                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3312                        userId);
3313            }
3314            if (mResolveComponentName.equals(component)) {
3315                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3316                        new PackageUserState(), userId);
3317            }
3318        }
3319        return null;
3320    }
3321
3322    @Override
3323    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3324            String resolvedType) {
3325        synchronized (mPackages) {
3326            if (component.equals(mResolveComponentName)) {
3327                // The resolver supports EVERYTHING!
3328                return true;
3329            }
3330            PackageParser.Activity a = mActivities.mActivities.get(component);
3331            if (a == null) {
3332                return false;
3333            }
3334            for (int i=0; i<a.intents.size(); i++) {
3335                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3336                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3337                    return true;
3338                }
3339            }
3340            return false;
3341        }
3342    }
3343
3344    @Override
3345    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3346        if (!sUserManager.exists(userId)) return null;
3347        flags = updateFlagsForComponent(flags, userId, component);
3348        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3349        synchronized (mPackages) {
3350            PackageParser.Activity a = mReceivers.mActivities.get(component);
3351            if (DEBUG_PACKAGE_INFO) Log.v(
3352                TAG, "getReceiverInfo " + component + ": " + a);
3353            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3354                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3355                if (ps == null) return null;
3356                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3357                        userId);
3358            }
3359        }
3360        return null;
3361    }
3362
3363    @Override
3364    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3365        if (!sUserManager.exists(userId)) return null;
3366        flags = updateFlagsForComponent(flags, userId, component);
3367        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3368        synchronized (mPackages) {
3369            PackageParser.Service s = mServices.mServices.get(component);
3370            if (DEBUG_PACKAGE_INFO) Log.v(
3371                TAG, "getServiceInfo " + component + ": " + s);
3372            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3373                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3374                if (ps == null) return null;
3375                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3376                        userId);
3377            }
3378        }
3379        return null;
3380    }
3381
3382    @Override
3383    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3384        if (!sUserManager.exists(userId)) return null;
3385        flags = updateFlagsForComponent(flags, userId, component);
3386        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3387        synchronized (mPackages) {
3388            PackageParser.Provider p = mProviders.mProviders.get(component);
3389            if (DEBUG_PACKAGE_INFO) Log.v(
3390                TAG, "getProviderInfo " + component + ": " + p);
3391            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3392                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3393                if (ps == null) return null;
3394                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3395                        userId);
3396            }
3397        }
3398        return null;
3399    }
3400
3401    @Override
3402    public String[] getSystemSharedLibraryNames() {
3403        Set<String> libSet;
3404        synchronized (mPackages) {
3405            libSet = mSharedLibraries.keySet();
3406            int size = libSet.size();
3407            if (size > 0) {
3408                String[] libs = new String[size];
3409                libSet.toArray(libs);
3410                return libs;
3411            }
3412        }
3413        return null;
3414    }
3415
3416    @Override
3417    public FeatureInfo[] getSystemAvailableFeatures() {
3418        Collection<FeatureInfo> featSet;
3419        synchronized (mPackages) {
3420            featSet = mAvailableFeatures.values();
3421            int size = featSet.size();
3422            if (size > 0) {
3423                FeatureInfo[] features = new FeatureInfo[size+1];
3424                featSet.toArray(features);
3425                FeatureInfo fi = new FeatureInfo();
3426                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3427                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3428                features[size] = fi;
3429                return features;
3430            }
3431        }
3432        return null;
3433    }
3434
3435    @Override
3436    public boolean hasSystemFeature(String name) {
3437        synchronized (mPackages) {
3438            return mAvailableFeatures.containsKey(name);
3439        }
3440    }
3441
3442    @Override
3443    public int checkPermission(String permName, String pkgName, int userId) {
3444        if (!sUserManager.exists(userId)) {
3445            return PackageManager.PERMISSION_DENIED;
3446        }
3447
3448        synchronized (mPackages) {
3449            final PackageParser.Package p = mPackages.get(pkgName);
3450            if (p != null && p.mExtras != null) {
3451                final PackageSetting ps = (PackageSetting) p.mExtras;
3452                final PermissionsState permissionsState = ps.getPermissionsState();
3453                if (permissionsState.hasPermission(permName, userId)) {
3454                    return PackageManager.PERMISSION_GRANTED;
3455                }
3456                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3457                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3458                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3459                    return PackageManager.PERMISSION_GRANTED;
3460                }
3461            }
3462        }
3463
3464        return PackageManager.PERMISSION_DENIED;
3465    }
3466
3467    @Override
3468    public int checkUidPermission(String permName, int uid) {
3469        final int userId = UserHandle.getUserId(uid);
3470
3471        if (!sUserManager.exists(userId)) {
3472            return PackageManager.PERMISSION_DENIED;
3473        }
3474
3475        synchronized (mPackages) {
3476            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3477            if (obj != null) {
3478                final SettingBase ps = (SettingBase) obj;
3479                final PermissionsState permissionsState = ps.getPermissionsState();
3480                if (permissionsState.hasPermission(permName, userId)) {
3481                    return PackageManager.PERMISSION_GRANTED;
3482                }
3483                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3484                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3485                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3486                    return PackageManager.PERMISSION_GRANTED;
3487                }
3488            } else {
3489                ArraySet<String> perms = mSystemPermissions.get(uid);
3490                if (perms != null) {
3491                    if (perms.contains(permName)) {
3492                        return PackageManager.PERMISSION_GRANTED;
3493                    }
3494                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3495                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3496                        return PackageManager.PERMISSION_GRANTED;
3497                    }
3498                }
3499            }
3500        }
3501
3502        return PackageManager.PERMISSION_DENIED;
3503    }
3504
3505    @Override
3506    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3507        if (UserHandle.getCallingUserId() != userId) {
3508            mContext.enforceCallingPermission(
3509                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3510                    "isPermissionRevokedByPolicy for user " + userId);
3511        }
3512
3513        if (checkPermission(permission, packageName, userId)
3514                == PackageManager.PERMISSION_GRANTED) {
3515            return false;
3516        }
3517
3518        final long identity = Binder.clearCallingIdentity();
3519        try {
3520            final int flags = getPermissionFlags(permission, packageName, userId);
3521            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3522        } finally {
3523            Binder.restoreCallingIdentity(identity);
3524        }
3525    }
3526
3527    @Override
3528    public String getPermissionControllerPackageName() {
3529        synchronized (mPackages) {
3530            return mRequiredInstallerPackage;
3531        }
3532    }
3533
3534    /**
3535     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3536     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3537     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3538     * @param message the message to log on security exception
3539     */
3540    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3541            boolean checkShell, String message) {
3542        if (userId < 0) {
3543            throw new IllegalArgumentException("Invalid userId " + userId);
3544        }
3545        if (checkShell) {
3546            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3547        }
3548        if (userId == UserHandle.getUserId(callingUid)) return;
3549        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3550            if (requireFullPermission) {
3551                mContext.enforceCallingOrSelfPermission(
3552                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3553            } else {
3554                try {
3555                    mContext.enforceCallingOrSelfPermission(
3556                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3557                } catch (SecurityException se) {
3558                    mContext.enforceCallingOrSelfPermission(
3559                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3560                }
3561            }
3562        }
3563    }
3564
3565    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3566        if (callingUid == Process.SHELL_UID) {
3567            if (userHandle >= 0
3568                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3569                throw new SecurityException("Shell does not have permission to access user "
3570                        + userHandle);
3571            } else if (userHandle < 0) {
3572                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3573                        + Debug.getCallers(3));
3574            }
3575        }
3576    }
3577
3578    private BasePermission findPermissionTreeLP(String permName) {
3579        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3580            if (permName.startsWith(bp.name) &&
3581                    permName.length() > bp.name.length() &&
3582                    permName.charAt(bp.name.length()) == '.') {
3583                return bp;
3584            }
3585        }
3586        return null;
3587    }
3588
3589    private BasePermission checkPermissionTreeLP(String permName) {
3590        if (permName != null) {
3591            BasePermission bp = findPermissionTreeLP(permName);
3592            if (bp != null) {
3593                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3594                    return bp;
3595                }
3596                throw new SecurityException("Calling uid "
3597                        + Binder.getCallingUid()
3598                        + " is not allowed to add to permission tree "
3599                        + bp.name + " owned by uid " + bp.uid);
3600            }
3601        }
3602        throw new SecurityException("No permission tree found for " + permName);
3603    }
3604
3605    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3606        if (s1 == null) {
3607            return s2 == null;
3608        }
3609        if (s2 == null) {
3610            return false;
3611        }
3612        if (s1.getClass() != s2.getClass()) {
3613            return false;
3614        }
3615        return s1.equals(s2);
3616    }
3617
3618    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3619        if (pi1.icon != pi2.icon) return false;
3620        if (pi1.logo != pi2.logo) return false;
3621        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3622        if (!compareStrings(pi1.name, pi2.name)) return false;
3623        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3624        // We'll take care of setting this one.
3625        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3626        // These are not currently stored in settings.
3627        //if (!compareStrings(pi1.group, pi2.group)) return false;
3628        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3629        //if (pi1.labelRes != pi2.labelRes) return false;
3630        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3631        return true;
3632    }
3633
3634    int permissionInfoFootprint(PermissionInfo info) {
3635        int size = info.name.length();
3636        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3637        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3638        return size;
3639    }
3640
3641    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3642        int size = 0;
3643        for (BasePermission perm : mSettings.mPermissions.values()) {
3644            if (perm.uid == tree.uid) {
3645                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3646            }
3647        }
3648        return size;
3649    }
3650
3651    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3652        // We calculate the max size of permissions defined by this uid and throw
3653        // if that plus the size of 'info' would exceed our stated maximum.
3654        if (tree.uid != Process.SYSTEM_UID) {
3655            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3656            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3657                throw new SecurityException("Permission tree size cap exceeded");
3658            }
3659        }
3660    }
3661
3662    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3663        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3664            throw new SecurityException("Label must be specified in permission");
3665        }
3666        BasePermission tree = checkPermissionTreeLP(info.name);
3667        BasePermission bp = mSettings.mPermissions.get(info.name);
3668        boolean added = bp == null;
3669        boolean changed = true;
3670        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3671        if (added) {
3672            enforcePermissionCapLocked(info, tree);
3673            bp = new BasePermission(info.name, tree.sourcePackage,
3674                    BasePermission.TYPE_DYNAMIC);
3675        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3676            throw new SecurityException(
3677                    "Not allowed to modify non-dynamic permission "
3678                    + info.name);
3679        } else {
3680            if (bp.protectionLevel == fixedLevel
3681                    && bp.perm.owner.equals(tree.perm.owner)
3682                    && bp.uid == tree.uid
3683                    && comparePermissionInfos(bp.perm.info, info)) {
3684                changed = false;
3685            }
3686        }
3687        bp.protectionLevel = fixedLevel;
3688        info = new PermissionInfo(info);
3689        info.protectionLevel = fixedLevel;
3690        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3691        bp.perm.info.packageName = tree.perm.info.packageName;
3692        bp.uid = tree.uid;
3693        if (added) {
3694            mSettings.mPermissions.put(info.name, bp);
3695        }
3696        if (changed) {
3697            if (!async) {
3698                mSettings.writeLPr();
3699            } else {
3700                scheduleWriteSettingsLocked();
3701            }
3702        }
3703        return added;
3704    }
3705
3706    @Override
3707    public boolean addPermission(PermissionInfo info) {
3708        synchronized (mPackages) {
3709            return addPermissionLocked(info, false);
3710        }
3711    }
3712
3713    @Override
3714    public boolean addPermissionAsync(PermissionInfo info) {
3715        synchronized (mPackages) {
3716            return addPermissionLocked(info, true);
3717        }
3718    }
3719
3720    @Override
3721    public void removePermission(String name) {
3722        synchronized (mPackages) {
3723            checkPermissionTreeLP(name);
3724            BasePermission bp = mSettings.mPermissions.get(name);
3725            if (bp != null) {
3726                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3727                    throw new SecurityException(
3728                            "Not allowed to modify non-dynamic permission "
3729                            + name);
3730                }
3731                mSettings.mPermissions.remove(name);
3732                mSettings.writeLPr();
3733            }
3734        }
3735    }
3736
3737    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3738            BasePermission bp) {
3739        int index = pkg.requestedPermissions.indexOf(bp.name);
3740        if (index == -1) {
3741            throw new SecurityException("Package " + pkg.packageName
3742                    + " has not requested permission " + bp.name);
3743        }
3744        if (!bp.isRuntime() && !bp.isDevelopment()) {
3745            throw new SecurityException("Permission " + bp.name
3746                    + " is not a changeable permission type");
3747        }
3748    }
3749
3750    @Override
3751    public void grantRuntimePermission(String packageName, String name, final int userId) {
3752        if (!sUserManager.exists(userId)) {
3753            Log.e(TAG, "No such user:" + userId);
3754            return;
3755        }
3756
3757        mContext.enforceCallingOrSelfPermission(
3758                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3759                "grantRuntimePermission");
3760
3761        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3762                "grantRuntimePermission");
3763
3764        final int uid;
3765        final SettingBase sb;
3766
3767        synchronized (mPackages) {
3768            final PackageParser.Package pkg = mPackages.get(packageName);
3769            if (pkg == null) {
3770                throw new IllegalArgumentException("Unknown package: " + packageName);
3771            }
3772
3773            final BasePermission bp = mSettings.mPermissions.get(name);
3774            if (bp == null) {
3775                throw new IllegalArgumentException("Unknown permission: " + name);
3776            }
3777
3778            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3779
3780            // If a permission review is required for legacy apps we represent
3781            // their permissions as always granted runtime ones since we need
3782            // to keep the review required permission flag per user while an
3783            // install permission's state is shared across all users.
3784            if (Build.PERMISSIONS_REVIEW_REQUIRED
3785                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3786                    && bp.isRuntime()) {
3787                return;
3788            }
3789
3790            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3791            sb = (SettingBase) pkg.mExtras;
3792            if (sb == null) {
3793                throw new IllegalArgumentException("Unknown package: " + packageName);
3794            }
3795
3796            final PermissionsState permissionsState = sb.getPermissionsState();
3797
3798            final int flags = permissionsState.getPermissionFlags(name, userId);
3799            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3800                throw new SecurityException("Cannot grant system fixed permission "
3801                        + name + " for package " + packageName);
3802            }
3803
3804            if (bp.isDevelopment()) {
3805                // Development permissions must be handled specially, since they are not
3806                // normal runtime permissions.  For now they apply to all users.
3807                if (permissionsState.grantInstallPermission(bp) !=
3808                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3809                    scheduleWriteSettingsLocked();
3810                }
3811                return;
3812            }
3813
3814            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3815                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3816                return;
3817            }
3818
3819            final int result = permissionsState.grantRuntimePermission(bp, userId);
3820            switch (result) {
3821                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3822                    return;
3823                }
3824
3825                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3826                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3827                    mHandler.post(new Runnable() {
3828                        @Override
3829                        public void run() {
3830                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3831                        }
3832                    });
3833                }
3834                break;
3835            }
3836
3837            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3838
3839            // Not critical if that is lost - app has to request again.
3840            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3841        }
3842
3843        // Only need to do this if user is initialized. Otherwise it's a new user
3844        // and there are no processes running as the user yet and there's no need
3845        // to make an expensive call to remount processes for the changed permissions.
3846        if (READ_EXTERNAL_STORAGE.equals(name)
3847                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3848            final long token = Binder.clearCallingIdentity();
3849            try {
3850                if (sUserManager.isInitialized(userId)) {
3851                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3852                            MountServiceInternal.class);
3853                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3854                }
3855            } finally {
3856                Binder.restoreCallingIdentity(token);
3857            }
3858        }
3859    }
3860
3861    @Override
3862    public void revokeRuntimePermission(String packageName, String name, int userId) {
3863        if (!sUserManager.exists(userId)) {
3864            Log.e(TAG, "No such user:" + userId);
3865            return;
3866        }
3867
3868        mContext.enforceCallingOrSelfPermission(
3869                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3870                "revokeRuntimePermission");
3871
3872        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3873                "revokeRuntimePermission");
3874
3875        final int appId;
3876
3877        synchronized (mPackages) {
3878            final PackageParser.Package pkg = mPackages.get(packageName);
3879            if (pkg == null) {
3880                throw new IllegalArgumentException("Unknown package: " + packageName);
3881            }
3882
3883            final BasePermission bp = mSettings.mPermissions.get(name);
3884            if (bp == null) {
3885                throw new IllegalArgumentException("Unknown permission: " + name);
3886            }
3887
3888            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3889
3890            // If a permission review is required for legacy apps we represent
3891            // their permissions as always granted runtime ones since we need
3892            // to keep the review required permission flag per user while an
3893            // install permission's state is shared across all users.
3894            if (Build.PERMISSIONS_REVIEW_REQUIRED
3895                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3896                    && bp.isRuntime()) {
3897                return;
3898            }
3899
3900            SettingBase sb = (SettingBase) pkg.mExtras;
3901            if (sb == null) {
3902                throw new IllegalArgumentException("Unknown package: " + packageName);
3903            }
3904
3905            final PermissionsState permissionsState = sb.getPermissionsState();
3906
3907            final int flags = permissionsState.getPermissionFlags(name, userId);
3908            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3909                throw new SecurityException("Cannot revoke system fixed permission "
3910                        + name + " for package " + packageName);
3911            }
3912
3913            if (bp.isDevelopment()) {
3914                // Development permissions must be handled specially, since they are not
3915                // normal runtime permissions.  For now they apply to all users.
3916                if (permissionsState.revokeInstallPermission(bp) !=
3917                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3918                    scheduleWriteSettingsLocked();
3919                }
3920                return;
3921            }
3922
3923            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3924                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3925                return;
3926            }
3927
3928            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3929
3930            // Critical, after this call app should never have the permission.
3931            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3932
3933            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3934        }
3935
3936        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3937    }
3938
3939    @Override
3940    public void resetRuntimePermissions() {
3941        mContext.enforceCallingOrSelfPermission(
3942                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3943                "revokeRuntimePermission");
3944
3945        int callingUid = Binder.getCallingUid();
3946        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3947            mContext.enforceCallingOrSelfPermission(
3948                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3949                    "resetRuntimePermissions");
3950        }
3951
3952        synchronized (mPackages) {
3953            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3954            for (int userId : UserManagerService.getInstance().getUserIds()) {
3955                final int packageCount = mPackages.size();
3956                for (int i = 0; i < packageCount; i++) {
3957                    PackageParser.Package pkg = mPackages.valueAt(i);
3958                    if (!(pkg.mExtras instanceof PackageSetting)) {
3959                        continue;
3960                    }
3961                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3962                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3963                }
3964            }
3965        }
3966    }
3967
3968    @Override
3969    public int getPermissionFlags(String name, String packageName, int userId) {
3970        if (!sUserManager.exists(userId)) {
3971            return 0;
3972        }
3973
3974        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3975
3976        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3977                "getPermissionFlags");
3978
3979        synchronized (mPackages) {
3980            final PackageParser.Package pkg = mPackages.get(packageName);
3981            if (pkg == null) {
3982                throw new IllegalArgumentException("Unknown package: " + packageName);
3983            }
3984
3985            final BasePermission bp = mSettings.mPermissions.get(name);
3986            if (bp == null) {
3987                throw new IllegalArgumentException("Unknown permission: " + name);
3988            }
3989
3990            SettingBase sb = (SettingBase) pkg.mExtras;
3991            if (sb == null) {
3992                throw new IllegalArgumentException("Unknown package: " + packageName);
3993            }
3994
3995            PermissionsState permissionsState = sb.getPermissionsState();
3996            return permissionsState.getPermissionFlags(name, userId);
3997        }
3998    }
3999
4000    @Override
4001    public void updatePermissionFlags(String name, String packageName, int flagMask,
4002            int flagValues, int userId) {
4003        if (!sUserManager.exists(userId)) {
4004            return;
4005        }
4006
4007        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4008
4009        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4010                "updatePermissionFlags");
4011
4012        // Only the system can change these flags and nothing else.
4013        if (getCallingUid() != Process.SYSTEM_UID) {
4014            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4015            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4016            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4017            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4018            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4019        }
4020
4021        synchronized (mPackages) {
4022            final PackageParser.Package pkg = mPackages.get(packageName);
4023            if (pkg == null) {
4024                throw new IllegalArgumentException("Unknown package: " + packageName);
4025            }
4026
4027            final BasePermission bp = mSettings.mPermissions.get(name);
4028            if (bp == null) {
4029                throw new IllegalArgumentException("Unknown permission: " + name);
4030            }
4031
4032            SettingBase sb = (SettingBase) pkg.mExtras;
4033            if (sb == null) {
4034                throw new IllegalArgumentException("Unknown package: " + packageName);
4035            }
4036
4037            PermissionsState permissionsState = sb.getPermissionsState();
4038
4039            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4040
4041            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4042                // Install and runtime permissions are stored in different places,
4043                // so figure out what permission changed and persist the change.
4044                if (permissionsState.getInstallPermissionState(name) != null) {
4045                    scheduleWriteSettingsLocked();
4046                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4047                        || hadState) {
4048                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4049                }
4050            }
4051        }
4052    }
4053
4054    /**
4055     * Update the permission flags for all packages and runtime permissions of a user in order
4056     * to allow device or profile owner to remove POLICY_FIXED.
4057     */
4058    @Override
4059    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4060        if (!sUserManager.exists(userId)) {
4061            return;
4062        }
4063
4064        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4065
4066        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4067                "updatePermissionFlagsForAllApps");
4068
4069        // Only the system can change system fixed flags.
4070        if (getCallingUid() != Process.SYSTEM_UID) {
4071            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4072            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4073        }
4074
4075        synchronized (mPackages) {
4076            boolean changed = false;
4077            final int packageCount = mPackages.size();
4078            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4079                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4080                SettingBase sb = (SettingBase) pkg.mExtras;
4081                if (sb == null) {
4082                    continue;
4083                }
4084                PermissionsState permissionsState = sb.getPermissionsState();
4085                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4086                        userId, flagMask, flagValues);
4087            }
4088            if (changed) {
4089                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4090            }
4091        }
4092    }
4093
4094    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4095        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4096                != PackageManager.PERMISSION_GRANTED
4097            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4098                != PackageManager.PERMISSION_GRANTED) {
4099            throw new SecurityException(message + " requires "
4100                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4101                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4102        }
4103    }
4104
4105    @Override
4106    public boolean shouldShowRequestPermissionRationale(String permissionName,
4107            String packageName, int userId) {
4108        if (UserHandle.getCallingUserId() != userId) {
4109            mContext.enforceCallingPermission(
4110                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4111                    "canShowRequestPermissionRationale for user " + userId);
4112        }
4113
4114        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4115        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4116            return false;
4117        }
4118
4119        if (checkPermission(permissionName, packageName, userId)
4120                == PackageManager.PERMISSION_GRANTED) {
4121            return false;
4122        }
4123
4124        final int flags;
4125
4126        final long identity = Binder.clearCallingIdentity();
4127        try {
4128            flags = getPermissionFlags(permissionName,
4129                    packageName, userId);
4130        } finally {
4131            Binder.restoreCallingIdentity(identity);
4132        }
4133
4134        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4135                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4136                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4137
4138        if ((flags & fixedFlags) != 0) {
4139            return false;
4140        }
4141
4142        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4143    }
4144
4145    @Override
4146    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4147        mContext.enforceCallingOrSelfPermission(
4148                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4149                "addOnPermissionsChangeListener");
4150
4151        synchronized (mPackages) {
4152            mOnPermissionChangeListeners.addListenerLocked(listener);
4153        }
4154    }
4155
4156    @Override
4157    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4158        synchronized (mPackages) {
4159            mOnPermissionChangeListeners.removeListenerLocked(listener);
4160        }
4161    }
4162
4163    @Override
4164    public boolean isProtectedBroadcast(String actionName) {
4165        synchronized (mPackages) {
4166            if (mProtectedBroadcasts.contains(actionName)) {
4167                return true;
4168            } else if (actionName != null) {
4169                // TODO: remove these terrible hacks
4170                if (actionName.startsWith("android.net.netmon.lingerExpired")
4171                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4172                    return true;
4173                }
4174            }
4175        }
4176        return false;
4177    }
4178
4179    @Override
4180    public int checkSignatures(String pkg1, String pkg2) {
4181        synchronized (mPackages) {
4182            final PackageParser.Package p1 = mPackages.get(pkg1);
4183            final PackageParser.Package p2 = mPackages.get(pkg2);
4184            if (p1 == null || p1.mExtras == null
4185                    || p2 == null || p2.mExtras == null) {
4186                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4187            }
4188            return compareSignatures(p1.mSignatures, p2.mSignatures);
4189        }
4190    }
4191
4192    @Override
4193    public int checkUidSignatures(int uid1, int uid2) {
4194        // Map to base uids.
4195        uid1 = UserHandle.getAppId(uid1);
4196        uid2 = UserHandle.getAppId(uid2);
4197        // reader
4198        synchronized (mPackages) {
4199            Signature[] s1;
4200            Signature[] s2;
4201            Object obj = mSettings.getUserIdLPr(uid1);
4202            if (obj != null) {
4203                if (obj instanceof SharedUserSetting) {
4204                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4205                } else if (obj instanceof PackageSetting) {
4206                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4207                } else {
4208                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4209                }
4210            } else {
4211                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4212            }
4213            obj = mSettings.getUserIdLPr(uid2);
4214            if (obj != null) {
4215                if (obj instanceof SharedUserSetting) {
4216                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4217                } else if (obj instanceof PackageSetting) {
4218                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4219                } else {
4220                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4221                }
4222            } else {
4223                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4224            }
4225            return compareSignatures(s1, s2);
4226        }
4227    }
4228
4229    private void killUid(int appId, int userId, String reason) {
4230        final long identity = Binder.clearCallingIdentity();
4231        try {
4232            IActivityManager am = ActivityManagerNative.getDefault();
4233            if (am != null) {
4234                try {
4235                    am.killUid(appId, userId, reason);
4236                } catch (RemoteException e) {
4237                    /* ignore - same process */
4238                }
4239            }
4240        } finally {
4241            Binder.restoreCallingIdentity(identity);
4242        }
4243    }
4244
4245    /**
4246     * Compares two sets of signatures. Returns:
4247     * <br />
4248     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4249     * <br />
4250     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4251     * <br />
4252     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4253     * <br />
4254     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4255     * <br />
4256     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4257     */
4258    static int compareSignatures(Signature[] s1, Signature[] s2) {
4259        if (s1 == null) {
4260            return s2 == null
4261                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4262                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4263        }
4264
4265        if (s2 == null) {
4266            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4267        }
4268
4269        if (s1.length != s2.length) {
4270            return PackageManager.SIGNATURE_NO_MATCH;
4271        }
4272
4273        // Since both signature sets are of size 1, we can compare without HashSets.
4274        if (s1.length == 1) {
4275            return s1[0].equals(s2[0]) ?
4276                    PackageManager.SIGNATURE_MATCH :
4277                    PackageManager.SIGNATURE_NO_MATCH;
4278        }
4279
4280        ArraySet<Signature> set1 = new ArraySet<Signature>();
4281        for (Signature sig : s1) {
4282            set1.add(sig);
4283        }
4284        ArraySet<Signature> set2 = new ArraySet<Signature>();
4285        for (Signature sig : s2) {
4286            set2.add(sig);
4287        }
4288        // Make sure s2 contains all signatures in s1.
4289        if (set1.equals(set2)) {
4290            return PackageManager.SIGNATURE_MATCH;
4291        }
4292        return PackageManager.SIGNATURE_NO_MATCH;
4293    }
4294
4295    /**
4296     * If the database version for this type of package (internal storage or
4297     * external storage) is less than the version where package signatures
4298     * were updated, return true.
4299     */
4300    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4301        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4302        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4303    }
4304
4305    /**
4306     * Used for backward compatibility to make sure any packages with
4307     * certificate chains get upgraded to the new style. {@code existingSigs}
4308     * will be in the old format (since they were stored on disk from before the
4309     * system upgrade) and {@code scannedSigs} will be in the newer format.
4310     */
4311    private int compareSignaturesCompat(PackageSignatures existingSigs,
4312            PackageParser.Package scannedPkg) {
4313        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4314            return PackageManager.SIGNATURE_NO_MATCH;
4315        }
4316
4317        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4318        for (Signature sig : existingSigs.mSignatures) {
4319            existingSet.add(sig);
4320        }
4321        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4322        for (Signature sig : scannedPkg.mSignatures) {
4323            try {
4324                Signature[] chainSignatures = sig.getChainSignatures();
4325                for (Signature chainSig : chainSignatures) {
4326                    scannedCompatSet.add(chainSig);
4327                }
4328            } catch (CertificateEncodingException e) {
4329                scannedCompatSet.add(sig);
4330            }
4331        }
4332        /*
4333         * Make sure the expanded scanned set contains all signatures in the
4334         * existing one.
4335         */
4336        if (scannedCompatSet.equals(existingSet)) {
4337            // Migrate the old signatures to the new scheme.
4338            existingSigs.assignSignatures(scannedPkg.mSignatures);
4339            // The new KeySets will be re-added later in the scanning process.
4340            synchronized (mPackages) {
4341                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4342            }
4343            return PackageManager.SIGNATURE_MATCH;
4344        }
4345        return PackageManager.SIGNATURE_NO_MATCH;
4346    }
4347
4348    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4349        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4350        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4351    }
4352
4353    private int compareSignaturesRecover(PackageSignatures existingSigs,
4354            PackageParser.Package scannedPkg) {
4355        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4356            return PackageManager.SIGNATURE_NO_MATCH;
4357        }
4358
4359        String msg = null;
4360        try {
4361            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4362                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4363                        + scannedPkg.packageName);
4364                return PackageManager.SIGNATURE_MATCH;
4365            }
4366        } catch (CertificateException e) {
4367            msg = e.getMessage();
4368        }
4369
4370        logCriticalInfo(Log.INFO,
4371                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4372        return PackageManager.SIGNATURE_NO_MATCH;
4373    }
4374
4375    @Override
4376    public String[] getPackagesForUid(int uid) {
4377        uid = UserHandle.getAppId(uid);
4378        // reader
4379        synchronized (mPackages) {
4380            Object obj = mSettings.getUserIdLPr(uid);
4381            if (obj instanceof SharedUserSetting) {
4382                final SharedUserSetting sus = (SharedUserSetting) obj;
4383                final int N = sus.packages.size();
4384                final String[] res = new String[N];
4385                final Iterator<PackageSetting> it = sus.packages.iterator();
4386                int i = 0;
4387                while (it.hasNext()) {
4388                    res[i++] = it.next().name;
4389                }
4390                return res;
4391            } else if (obj instanceof PackageSetting) {
4392                final PackageSetting ps = (PackageSetting) obj;
4393                return new String[] { ps.name };
4394            }
4395        }
4396        return null;
4397    }
4398
4399    @Override
4400    public String getNameForUid(int uid) {
4401        // reader
4402        synchronized (mPackages) {
4403            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4404            if (obj instanceof SharedUserSetting) {
4405                final SharedUserSetting sus = (SharedUserSetting) obj;
4406                return sus.name + ":" + sus.userId;
4407            } else if (obj instanceof PackageSetting) {
4408                final PackageSetting ps = (PackageSetting) obj;
4409                return ps.name;
4410            }
4411        }
4412        return null;
4413    }
4414
4415    @Override
4416    public int getUidForSharedUser(String sharedUserName) {
4417        if(sharedUserName == null) {
4418            return -1;
4419        }
4420        // reader
4421        synchronized (mPackages) {
4422            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4423            if (suid == null) {
4424                return -1;
4425            }
4426            return suid.userId;
4427        }
4428    }
4429
4430    @Override
4431    public int getFlagsForUid(int uid) {
4432        synchronized (mPackages) {
4433            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4434            if (obj instanceof SharedUserSetting) {
4435                final SharedUserSetting sus = (SharedUserSetting) obj;
4436                return sus.pkgFlags;
4437            } else if (obj instanceof PackageSetting) {
4438                final PackageSetting ps = (PackageSetting) obj;
4439                return ps.pkgFlags;
4440            }
4441        }
4442        return 0;
4443    }
4444
4445    @Override
4446    public int getPrivateFlagsForUid(int uid) {
4447        synchronized (mPackages) {
4448            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4449            if (obj instanceof SharedUserSetting) {
4450                final SharedUserSetting sus = (SharedUserSetting) obj;
4451                return sus.pkgPrivateFlags;
4452            } else if (obj instanceof PackageSetting) {
4453                final PackageSetting ps = (PackageSetting) obj;
4454                return ps.pkgPrivateFlags;
4455            }
4456        }
4457        return 0;
4458    }
4459
4460    @Override
4461    public boolean isUidPrivileged(int uid) {
4462        uid = UserHandle.getAppId(uid);
4463        // reader
4464        synchronized (mPackages) {
4465            Object obj = mSettings.getUserIdLPr(uid);
4466            if (obj instanceof SharedUserSetting) {
4467                final SharedUserSetting sus = (SharedUserSetting) obj;
4468                final Iterator<PackageSetting> it = sus.packages.iterator();
4469                while (it.hasNext()) {
4470                    if (it.next().isPrivileged()) {
4471                        return true;
4472                    }
4473                }
4474            } else if (obj instanceof PackageSetting) {
4475                final PackageSetting ps = (PackageSetting) obj;
4476                return ps.isPrivileged();
4477            }
4478        }
4479        return false;
4480    }
4481
4482    @Override
4483    public String[] getAppOpPermissionPackages(String permissionName) {
4484        synchronized (mPackages) {
4485            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4486            if (pkgs == null) {
4487                return null;
4488            }
4489            return pkgs.toArray(new String[pkgs.size()]);
4490        }
4491    }
4492
4493    @Override
4494    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4495            int flags, int userId) {
4496        if (!sUserManager.exists(userId)) return null;
4497        flags = updateFlagsForResolve(flags, userId, intent);
4498        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4499        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4500        final ResolveInfo bestChoice =
4501                chooseBestActivity(intent, resolvedType, flags, query, userId);
4502
4503        if (isEphemeralAllowed(intent, query, userId)) {
4504            final EphemeralResolveInfo ai =
4505                    getEphemeralResolveInfo(intent, resolvedType, userId);
4506            if (ai != null) {
4507                if (DEBUG_EPHEMERAL) {
4508                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4509                }
4510                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4511                bestChoice.ephemeralResolveInfo = ai;
4512            }
4513        }
4514        return bestChoice;
4515    }
4516
4517    @Override
4518    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4519            IntentFilter filter, int match, ComponentName activity) {
4520        final int userId = UserHandle.getCallingUserId();
4521        if (DEBUG_PREFERRED) {
4522            Log.v(TAG, "setLastChosenActivity intent=" + intent
4523                + " resolvedType=" + resolvedType
4524                + " flags=" + flags
4525                + " filter=" + filter
4526                + " match=" + match
4527                + " activity=" + activity);
4528            filter.dump(new PrintStreamPrinter(System.out), "    ");
4529        }
4530        intent.setComponent(null);
4531        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4532        // Find any earlier preferred or last chosen entries and nuke them
4533        findPreferredActivity(intent, resolvedType,
4534                flags, query, 0, false, true, false, userId);
4535        // Add the new activity as the last chosen for this filter
4536        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4537                "Setting last chosen");
4538    }
4539
4540    @Override
4541    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4542        final int userId = UserHandle.getCallingUserId();
4543        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4544        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4545        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4546                false, false, false, userId);
4547    }
4548
4549
4550    private boolean isEphemeralAllowed(
4551            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4552        // Short circuit and return early if possible.
4553        if (DISABLE_EPHEMERAL_APPS) {
4554            return false;
4555        }
4556        final int callingUser = UserHandle.getCallingUserId();
4557        if (callingUser != UserHandle.USER_SYSTEM) {
4558            return false;
4559        }
4560        if (mEphemeralResolverConnection == null) {
4561            return false;
4562        }
4563        if (intent.getComponent() != null) {
4564            return false;
4565        }
4566        if (intent.getPackage() != null) {
4567            return false;
4568        }
4569        final boolean isWebUri = hasWebURI(intent);
4570        if (!isWebUri) {
4571            return false;
4572        }
4573        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4574        synchronized (mPackages) {
4575            final int count = resolvedActivites.size();
4576            for (int n = 0; n < count; n++) {
4577                ResolveInfo info = resolvedActivites.get(n);
4578                String packageName = info.activityInfo.packageName;
4579                PackageSetting ps = mSettings.mPackages.get(packageName);
4580                if (ps != null) {
4581                    // Try to get the status from User settings first
4582                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4583                    int status = (int) (packedStatus >> 32);
4584                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4585                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4586                        if (DEBUG_EPHEMERAL) {
4587                            Slog.v(TAG, "DENY ephemeral apps;"
4588                                + " pkg: " + packageName + ", status: " + status);
4589                        }
4590                        return false;
4591                    }
4592                }
4593            }
4594        }
4595        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4596        return true;
4597    }
4598
4599    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4600            int userId) {
4601        MessageDigest digest = null;
4602        try {
4603            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4604        } catch (NoSuchAlgorithmException e) {
4605            // If we can't create a digest, ignore ephemeral apps.
4606            return null;
4607        }
4608
4609        final byte[] hostBytes = intent.getData().getHost().getBytes();
4610        final byte[] digestBytes = digest.digest(hostBytes);
4611        int shaPrefix =
4612                digestBytes[0] << 24
4613                | digestBytes[1] << 16
4614                | digestBytes[2] << 8
4615                | digestBytes[3] << 0;
4616        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4617                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4618        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4619            // No hash prefix match; there are no ephemeral apps for this domain.
4620            return null;
4621        }
4622        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4623            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4624            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4625                continue;
4626            }
4627            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4628            // No filters; this should never happen.
4629            if (filters.isEmpty()) {
4630                continue;
4631            }
4632            // We have a domain match; resolve the filters to see if anything matches.
4633            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4634            for (int j = filters.size() - 1; j >= 0; --j) {
4635                final EphemeralResolveIntentInfo intentInfo =
4636                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4637                ephemeralResolver.addFilter(intentInfo);
4638            }
4639            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4640                    intent, resolvedType, false /*defaultOnly*/, userId);
4641            if (!matchedResolveInfoList.isEmpty()) {
4642                return matchedResolveInfoList.get(0);
4643            }
4644        }
4645        // Hash or filter mis-match; no ephemeral apps for this domain.
4646        return null;
4647    }
4648
4649    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4650            int flags, List<ResolveInfo> query, int userId) {
4651        if (query != null) {
4652            final int N = query.size();
4653            if (N == 1) {
4654                return query.get(0);
4655            } else if (N > 1) {
4656                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4657                // If there is more than one activity with the same priority,
4658                // then let the user decide between them.
4659                ResolveInfo r0 = query.get(0);
4660                ResolveInfo r1 = query.get(1);
4661                if (DEBUG_INTENT_MATCHING || debug) {
4662                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4663                            + r1.activityInfo.name + "=" + r1.priority);
4664                }
4665                // If the first activity has a higher priority, or a different
4666                // default, then it is always desirable to pick it.
4667                if (r0.priority != r1.priority
4668                        || r0.preferredOrder != r1.preferredOrder
4669                        || r0.isDefault != r1.isDefault) {
4670                    return query.get(0);
4671                }
4672                // If we have saved a preference for a preferred activity for
4673                // this Intent, use that.
4674                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4675                        flags, query, r0.priority, true, false, debug, userId);
4676                if (ri != null) {
4677                    return ri;
4678                }
4679                ri = new ResolveInfo(mResolveInfo);
4680                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4681                ri.activityInfo.applicationInfo = new ApplicationInfo(
4682                        ri.activityInfo.applicationInfo);
4683                if (userId != 0) {
4684                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4685                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4686                }
4687                // Make sure that the resolver is displayable in car mode
4688                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4689                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4690                return ri;
4691            }
4692        }
4693        return null;
4694    }
4695
4696    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4697            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4698        final int N = query.size();
4699        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4700                .get(userId);
4701        // Get the list of persistent preferred activities that handle the intent
4702        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4703        List<PersistentPreferredActivity> pprefs = ppir != null
4704                ? ppir.queryIntent(intent, resolvedType,
4705                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4706                : null;
4707        if (pprefs != null && pprefs.size() > 0) {
4708            final int M = pprefs.size();
4709            for (int i=0; i<M; i++) {
4710                final PersistentPreferredActivity ppa = pprefs.get(i);
4711                if (DEBUG_PREFERRED || debug) {
4712                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4713                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4714                            + "\n  component=" + ppa.mComponent);
4715                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4716                }
4717                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4718                        flags | MATCH_DISABLED_COMPONENTS, userId);
4719                if (DEBUG_PREFERRED || debug) {
4720                    Slog.v(TAG, "Found persistent preferred activity:");
4721                    if (ai != null) {
4722                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4723                    } else {
4724                        Slog.v(TAG, "  null");
4725                    }
4726                }
4727                if (ai == null) {
4728                    // This previously registered persistent preferred activity
4729                    // component is no longer known. Ignore it and do NOT remove it.
4730                    continue;
4731                }
4732                for (int j=0; j<N; j++) {
4733                    final ResolveInfo ri = query.get(j);
4734                    if (!ri.activityInfo.applicationInfo.packageName
4735                            .equals(ai.applicationInfo.packageName)) {
4736                        continue;
4737                    }
4738                    if (!ri.activityInfo.name.equals(ai.name)) {
4739                        continue;
4740                    }
4741                    //  Found a persistent preference that can handle the intent.
4742                    if (DEBUG_PREFERRED || debug) {
4743                        Slog.v(TAG, "Returning persistent preferred activity: " +
4744                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4745                    }
4746                    return ri;
4747                }
4748            }
4749        }
4750        return null;
4751    }
4752
4753    // TODO: handle preferred activities missing while user has amnesia
4754    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4755            List<ResolveInfo> query, int priority, boolean always,
4756            boolean removeMatches, boolean debug, int userId) {
4757        if (!sUserManager.exists(userId)) return null;
4758        flags = updateFlagsForResolve(flags, userId, intent);
4759        // writer
4760        synchronized (mPackages) {
4761            if (intent.getSelector() != null) {
4762                intent = intent.getSelector();
4763            }
4764            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4765
4766            // Try to find a matching persistent preferred activity.
4767            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4768                    debug, userId);
4769
4770            // If a persistent preferred activity matched, use it.
4771            if (pri != null) {
4772                return pri;
4773            }
4774
4775            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4776            // Get the list of preferred activities that handle the intent
4777            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4778            List<PreferredActivity> prefs = pir != null
4779                    ? pir.queryIntent(intent, resolvedType,
4780                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4781                    : null;
4782            if (prefs != null && prefs.size() > 0) {
4783                boolean changed = false;
4784                try {
4785                    // First figure out how good the original match set is.
4786                    // We will only allow preferred activities that came
4787                    // from the same match quality.
4788                    int match = 0;
4789
4790                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4791
4792                    final int N = query.size();
4793                    for (int j=0; j<N; j++) {
4794                        final ResolveInfo ri = query.get(j);
4795                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4796                                + ": 0x" + Integer.toHexString(match));
4797                        if (ri.match > match) {
4798                            match = ri.match;
4799                        }
4800                    }
4801
4802                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4803                            + Integer.toHexString(match));
4804
4805                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4806                    final int M = prefs.size();
4807                    for (int i=0; i<M; i++) {
4808                        final PreferredActivity pa = prefs.get(i);
4809                        if (DEBUG_PREFERRED || debug) {
4810                            Slog.v(TAG, "Checking PreferredActivity ds="
4811                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4812                                    + "\n  component=" + pa.mPref.mComponent);
4813                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4814                        }
4815                        if (pa.mPref.mMatch != match) {
4816                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4817                                    + Integer.toHexString(pa.mPref.mMatch));
4818                            continue;
4819                        }
4820                        // If it's not an "always" type preferred activity and that's what we're
4821                        // looking for, skip it.
4822                        if (always && !pa.mPref.mAlways) {
4823                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4824                            continue;
4825                        }
4826                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4827                                flags | MATCH_DISABLED_COMPONENTS, userId);
4828                        if (DEBUG_PREFERRED || debug) {
4829                            Slog.v(TAG, "Found preferred activity:");
4830                            if (ai != null) {
4831                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4832                            } else {
4833                                Slog.v(TAG, "  null");
4834                            }
4835                        }
4836                        if (ai == null) {
4837                            // This previously registered preferred activity
4838                            // component is no longer known.  Most likely an update
4839                            // to the app was installed and in the new version this
4840                            // component no longer exists.  Clean it up by removing
4841                            // it from the preferred activities list, and skip it.
4842                            Slog.w(TAG, "Removing dangling preferred activity: "
4843                                    + pa.mPref.mComponent);
4844                            pir.removeFilter(pa);
4845                            changed = true;
4846                            continue;
4847                        }
4848                        for (int j=0; j<N; j++) {
4849                            final ResolveInfo ri = query.get(j);
4850                            if (!ri.activityInfo.applicationInfo.packageName
4851                                    .equals(ai.applicationInfo.packageName)) {
4852                                continue;
4853                            }
4854                            if (!ri.activityInfo.name.equals(ai.name)) {
4855                                continue;
4856                            }
4857
4858                            if (removeMatches) {
4859                                pir.removeFilter(pa);
4860                                changed = true;
4861                                if (DEBUG_PREFERRED) {
4862                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4863                                }
4864                                break;
4865                            }
4866
4867                            // Okay we found a previously set preferred or last chosen app.
4868                            // If the result set is different from when this
4869                            // was created, we need to clear it and re-ask the
4870                            // user their preference, if we're looking for an "always" type entry.
4871                            if (always && !pa.mPref.sameSet(query)) {
4872                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4873                                        + intent + " type " + resolvedType);
4874                                if (DEBUG_PREFERRED) {
4875                                    Slog.v(TAG, "Removing preferred activity since set changed "
4876                                            + pa.mPref.mComponent);
4877                                }
4878                                pir.removeFilter(pa);
4879                                // Re-add the filter as a "last chosen" entry (!always)
4880                                PreferredActivity lastChosen = new PreferredActivity(
4881                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4882                                pir.addFilter(lastChosen);
4883                                changed = true;
4884                                return null;
4885                            }
4886
4887                            // Yay! Either the set matched or we're looking for the last chosen
4888                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4889                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4890                            return ri;
4891                        }
4892                    }
4893                } finally {
4894                    if (changed) {
4895                        if (DEBUG_PREFERRED) {
4896                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4897                        }
4898                        scheduleWritePackageRestrictionsLocked(userId);
4899                    }
4900                }
4901            }
4902        }
4903        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4904        return null;
4905    }
4906
4907    /*
4908     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4909     */
4910    @Override
4911    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4912            int targetUserId) {
4913        mContext.enforceCallingOrSelfPermission(
4914                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4915        List<CrossProfileIntentFilter> matches =
4916                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4917        if (matches != null) {
4918            int size = matches.size();
4919            for (int i = 0; i < size; i++) {
4920                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4921            }
4922        }
4923        if (hasWebURI(intent)) {
4924            // cross-profile app linking works only towards the parent.
4925            final UserInfo parent = getProfileParent(sourceUserId);
4926            synchronized(mPackages) {
4927                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4928                        intent, resolvedType, 0, sourceUserId, parent.id);
4929                return xpDomainInfo != null;
4930            }
4931        }
4932        return false;
4933    }
4934
4935    private UserInfo getProfileParent(int userId) {
4936        final long identity = Binder.clearCallingIdentity();
4937        try {
4938            return sUserManager.getProfileParent(userId);
4939        } finally {
4940            Binder.restoreCallingIdentity(identity);
4941        }
4942    }
4943
4944    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4945            String resolvedType, int userId) {
4946        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4947        if (resolver != null) {
4948            return resolver.queryIntent(intent, resolvedType, false, userId);
4949        }
4950        return null;
4951    }
4952
4953    @Override
4954    public List<ResolveInfo> queryIntentActivities(Intent intent,
4955            String resolvedType, int flags, int userId) {
4956        if (!sUserManager.exists(userId)) return Collections.emptyList();
4957        flags = updateFlagsForResolve(flags, userId, intent);
4958        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4959        ComponentName comp = intent.getComponent();
4960        if (comp == null) {
4961            if (intent.getSelector() != null) {
4962                intent = intent.getSelector();
4963                comp = intent.getComponent();
4964            }
4965        }
4966
4967        if (comp != null) {
4968            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4969            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4970            if (ai != null) {
4971                final ResolveInfo ri = new ResolveInfo();
4972                ri.activityInfo = ai;
4973                list.add(ri);
4974            }
4975            return list;
4976        }
4977
4978        // reader
4979        synchronized (mPackages) {
4980            final String pkgName = intent.getPackage();
4981            if (pkgName == null) {
4982                List<CrossProfileIntentFilter> matchingFilters =
4983                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4984                // Check for results that need to skip the current profile.
4985                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4986                        resolvedType, flags, userId);
4987                if (xpResolveInfo != null) {
4988                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4989                    result.add(xpResolveInfo);
4990                    return filterIfNotSystemUser(result, userId);
4991                }
4992
4993                // Check for results in the current profile.
4994                List<ResolveInfo> result = mActivities.queryIntent(
4995                        intent, resolvedType, flags, userId);
4996                result = filterIfNotSystemUser(result, userId);
4997
4998                // Check for cross profile results.
4999                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5000                xpResolveInfo = queryCrossProfileIntents(
5001                        matchingFilters, intent, resolvedType, flags, userId,
5002                        hasNonNegativePriorityResult);
5003                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5004                    boolean isVisibleToUser = filterIfNotSystemUser(
5005                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5006                    if (isVisibleToUser) {
5007                        result.add(xpResolveInfo);
5008                        Collections.sort(result, mResolvePrioritySorter);
5009                    }
5010                }
5011                if (hasWebURI(intent)) {
5012                    CrossProfileDomainInfo xpDomainInfo = null;
5013                    final UserInfo parent = getProfileParent(userId);
5014                    if (parent != null) {
5015                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5016                                flags, userId, parent.id);
5017                    }
5018                    if (xpDomainInfo != null) {
5019                        if (xpResolveInfo != null) {
5020                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5021                            // in the result.
5022                            result.remove(xpResolveInfo);
5023                        }
5024                        if (result.size() == 0) {
5025                            result.add(xpDomainInfo.resolveInfo);
5026                            return result;
5027                        }
5028                    } else if (result.size() <= 1) {
5029                        return result;
5030                    }
5031                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5032                            xpDomainInfo, userId);
5033                    Collections.sort(result, mResolvePrioritySorter);
5034                }
5035                return result;
5036            }
5037            final PackageParser.Package pkg = mPackages.get(pkgName);
5038            if (pkg != null) {
5039                return filterIfNotSystemUser(
5040                        mActivities.queryIntentForPackage(
5041                                intent, resolvedType, flags, pkg.activities, userId),
5042                        userId);
5043            }
5044            return new ArrayList<ResolveInfo>();
5045        }
5046    }
5047
5048    private static class CrossProfileDomainInfo {
5049        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5050        ResolveInfo resolveInfo;
5051        /* Best domain verification status of the activities found in the other profile */
5052        int bestDomainVerificationStatus;
5053    }
5054
5055    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5056            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5057        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5058                sourceUserId)) {
5059            return null;
5060        }
5061        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5062                resolvedType, flags, parentUserId);
5063
5064        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5065            return null;
5066        }
5067        CrossProfileDomainInfo result = null;
5068        int size = resultTargetUser.size();
5069        for (int i = 0; i < size; i++) {
5070            ResolveInfo riTargetUser = resultTargetUser.get(i);
5071            // Intent filter verification is only for filters that specify a host. So don't return
5072            // those that handle all web uris.
5073            if (riTargetUser.handleAllWebDataURI) {
5074                continue;
5075            }
5076            String packageName = riTargetUser.activityInfo.packageName;
5077            PackageSetting ps = mSettings.mPackages.get(packageName);
5078            if (ps == null) {
5079                continue;
5080            }
5081            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5082            int status = (int)(verificationState >> 32);
5083            if (result == null) {
5084                result = new CrossProfileDomainInfo();
5085                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5086                        sourceUserId, parentUserId);
5087                result.bestDomainVerificationStatus = status;
5088            } else {
5089                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5090                        result.bestDomainVerificationStatus);
5091            }
5092        }
5093        // Don't consider matches with status NEVER across profiles.
5094        if (result != null && result.bestDomainVerificationStatus
5095                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5096            return null;
5097        }
5098        return result;
5099    }
5100
5101    /**
5102     * Verification statuses are ordered from the worse to the best, except for
5103     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5104     */
5105    private int bestDomainVerificationStatus(int status1, int status2) {
5106        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5107            return status2;
5108        }
5109        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5110            return status1;
5111        }
5112        return (int) MathUtils.max(status1, status2);
5113    }
5114
5115    private boolean isUserEnabled(int userId) {
5116        long callingId = Binder.clearCallingIdentity();
5117        try {
5118            UserInfo userInfo = sUserManager.getUserInfo(userId);
5119            return userInfo != null && userInfo.isEnabled();
5120        } finally {
5121            Binder.restoreCallingIdentity(callingId);
5122        }
5123    }
5124
5125    /**
5126     * Filter out activities with systemUserOnly flag set, when current user is not System.
5127     *
5128     * @return filtered list
5129     */
5130    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5131        if (userId == UserHandle.USER_SYSTEM) {
5132            return resolveInfos;
5133        }
5134        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5135            ResolveInfo info = resolveInfos.get(i);
5136            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5137                resolveInfos.remove(i);
5138            }
5139        }
5140        return resolveInfos;
5141    }
5142
5143    /**
5144     * @param resolveInfos list of resolve infos in descending priority order
5145     * @return if the list contains a resolve info with non-negative priority
5146     */
5147    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5148        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5149    }
5150
5151    private static boolean hasWebURI(Intent intent) {
5152        if (intent.getData() == null) {
5153            return false;
5154        }
5155        final String scheme = intent.getScheme();
5156        if (TextUtils.isEmpty(scheme)) {
5157            return false;
5158        }
5159        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5160    }
5161
5162    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5163            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5164            int userId) {
5165        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5166
5167        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5168            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5169                    candidates.size());
5170        }
5171
5172        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5173        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5174        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5175        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5176        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5177        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5178
5179        synchronized (mPackages) {
5180            final int count = candidates.size();
5181            // First, try to use linked apps. Partition the candidates into four lists:
5182            // one for the final results, one for the "do not use ever", one for "undefined status"
5183            // and finally one for "browser app type".
5184            for (int n=0; n<count; n++) {
5185                ResolveInfo info = candidates.get(n);
5186                String packageName = info.activityInfo.packageName;
5187                PackageSetting ps = mSettings.mPackages.get(packageName);
5188                if (ps != null) {
5189                    // Add to the special match all list (Browser use case)
5190                    if (info.handleAllWebDataURI) {
5191                        matchAllList.add(info);
5192                        continue;
5193                    }
5194                    // Try to get the status from User settings first
5195                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5196                    int status = (int)(packedStatus >> 32);
5197                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5198                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5199                        if (DEBUG_DOMAIN_VERIFICATION) {
5200                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5201                                    + " : linkgen=" + linkGeneration);
5202                        }
5203                        // Use link-enabled generation as preferredOrder, i.e.
5204                        // prefer newly-enabled over earlier-enabled.
5205                        info.preferredOrder = linkGeneration;
5206                        alwaysList.add(info);
5207                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5208                        if (DEBUG_DOMAIN_VERIFICATION) {
5209                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5210                        }
5211                        neverList.add(info);
5212                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5213                        if (DEBUG_DOMAIN_VERIFICATION) {
5214                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5215                        }
5216                        alwaysAskList.add(info);
5217                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5218                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5219                        if (DEBUG_DOMAIN_VERIFICATION) {
5220                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5221                        }
5222                        undefinedList.add(info);
5223                    }
5224                }
5225            }
5226
5227            // We'll want to include browser possibilities in a few cases
5228            boolean includeBrowser = false;
5229
5230            // First try to add the "always" resolution(s) for the current user, if any
5231            if (alwaysList.size() > 0) {
5232                result.addAll(alwaysList);
5233            } else {
5234                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5235                result.addAll(undefinedList);
5236                // Maybe add one for the other profile.
5237                if (xpDomainInfo != null && (
5238                        xpDomainInfo.bestDomainVerificationStatus
5239                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5240                    result.add(xpDomainInfo.resolveInfo);
5241                }
5242                includeBrowser = true;
5243            }
5244
5245            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5246            // If there were 'always' entries their preferred order has been set, so we also
5247            // back that off to make the alternatives equivalent
5248            if (alwaysAskList.size() > 0) {
5249                for (ResolveInfo i : result) {
5250                    i.preferredOrder = 0;
5251                }
5252                result.addAll(alwaysAskList);
5253                includeBrowser = true;
5254            }
5255
5256            if (includeBrowser) {
5257                // Also add browsers (all of them or only the default one)
5258                if (DEBUG_DOMAIN_VERIFICATION) {
5259                    Slog.v(TAG, "   ...including browsers in candidate set");
5260                }
5261                if ((matchFlags & MATCH_ALL) != 0) {
5262                    result.addAll(matchAllList);
5263                } else {
5264                    // Browser/generic handling case.  If there's a default browser, go straight
5265                    // to that (but only if there is no other higher-priority match).
5266                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5267                    int maxMatchPrio = 0;
5268                    ResolveInfo defaultBrowserMatch = null;
5269                    final int numCandidates = matchAllList.size();
5270                    for (int n = 0; n < numCandidates; n++) {
5271                        ResolveInfo info = matchAllList.get(n);
5272                        // track the highest overall match priority...
5273                        if (info.priority > maxMatchPrio) {
5274                            maxMatchPrio = info.priority;
5275                        }
5276                        // ...and the highest-priority default browser match
5277                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5278                            if (defaultBrowserMatch == null
5279                                    || (defaultBrowserMatch.priority < info.priority)) {
5280                                if (debug) {
5281                                    Slog.v(TAG, "Considering default browser match " + info);
5282                                }
5283                                defaultBrowserMatch = info;
5284                            }
5285                        }
5286                    }
5287                    if (defaultBrowserMatch != null
5288                            && defaultBrowserMatch.priority >= maxMatchPrio
5289                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5290                    {
5291                        if (debug) {
5292                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5293                        }
5294                        result.add(defaultBrowserMatch);
5295                    } else {
5296                        result.addAll(matchAllList);
5297                    }
5298                }
5299
5300                // If there is nothing selected, add all candidates and remove the ones that the user
5301                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5302                if (result.size() == 0) {
5303                    result.addAll(candidates);
5304                    result.removeAll(neverList);
5305                }
5306            }
5307        }
5308        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5309            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5310                    result.size());
5311            for (ResolveInfo info : result) {
5312                Slog.v(TAG, "  + " + info.activityInfo);
5313            }
5314        }
5315        return result;
5316    }
5317
5318    // Returns a packed value as a long:
5319    //
5320    // high 'int'-sized word: link status: undefined/ask/never/always.
5321    // low 'int'-sized word: relative priority among 'always' results.
5322    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5323        long result = ps.getDomainVerificationStatusForUser(userId);
5324        // if none available, get the master status
5325        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5326            if (ps.getIntentFilterVerificationInfo() != null) {
5327                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5328            }
5329        }
5330        return result;
5331    }
5332
5333    private ResolveInfo querySkipCurrentProfileIntents(
5334            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5335            int flags, int sourceUserId) {
5336        if (matchingFilters != null) {
5337            int size = matchingFilters.size();
5338            for (int i = 0; i < size; i ++) {
5339                CrossProfileIntentFilter filter = matchingFilters.get(i);
5340                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5341                    // Checking if there are activities in the target user that can handle the
5342                    // intent.
5343                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5344                            resolvedType, flags, sourceUserId);
5345                    if (resolveInfo != null) {
5346                        return resolveInfo;
5347                    }
5348                }
5349            }
5350        }
5351        return null;
5352    }
5353
5354    // Return matching ResolveInfo in target user if any.
5355    private ResolveInfo queryCrossProfileIntents(
5356            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5357            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5358        if (matchingFilters != null) {
5359            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5360            // match the same intent. For performance reasons, it is better not to
5361            // run queryIntent twice for the same userId
5362            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5363            int size = matchingFilters.size();
5364            for (int i = 0; i < size; i++) {
5365                CrossProfileIntentFilter filter = matchingFilters.get(i);
5366                int targetUserId = filter.getTargetUserId();
5367                boolean skipCurrentProfile =
5368                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5369                boolean skipCurrentProfileIfNoMatchFound =
5370                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5371                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5372                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5373                    // Checking if there are activities in the target user that can handle the
5374                    // intent.
5375                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5376                            resolvedType, flags, sourceUserId);
5377                    if (resolveInfo != null) return resolveInfo;
5378                    alreadyTriedUserIds.put(targetUserId, true);
5379                }
5380            }
5381        }
5382        return null;
5383    }
5384
5385    /**
5386     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5387     * will forward the intent to the filter's target user.
5388     * Otherwise, returns null.
5389     */
5390    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5391            String resolvedType, int flags, int sourceUserId) {
5392        int targetUserId = filter.getTargetUserId();
5393        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5394                resolvedType, flags, targetUserId);
5395        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5396            // If all the matches in the target profile are suspended, return null.
5397            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5398                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5399                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5400                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5401                            targetUserId);
5402                }
5403            }
5404        }
5405        return null;
5406    }
5407
5408    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5409            int sourceUserId, int targetUserId) {
5410        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5411        long ident = Binder.clearCallingIdentity();
5412        boolean targetIsProfile;
5413        try {
5414            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5415        } finally {
5416            Binder.restoreCallingIdentity(ident);
5417        }
5418        String className;
5419        if (targetIsProfile) {
5420            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5421        } else {
5422            className = FORWARD_INTENT_TO_PARENT;
5423        }
5424        ComponentName forwardingActivityComponentName = new ComponentName(
5425                mAndroidApplication.packageName, className);
5426        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5427                sourceUserId);
5428        if (!targetIsProfile) {
5429            forwardingActivityInfo.showUserIcon = targetUserId;
5430            forwardingResolveInfo.noResourceId = true;
5431        }
5432        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5433        forwardingResolveInfo.priority = 0;
5434        forwardingResolveInfo.preferredOrder = 0;
5435        forwardingResolveInfo.match = 0;
5436        forwardingResolveInfo.isDefault = true;
5437        forwardingResolveInfo.filter = filter;
5438        forwardingResolveInfo.targetUserId = targetUserId;
5439        return forwardingResolveInfo;
5440    }
5441
5442    @Override
5443    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5444            Intent[] specifics, String[] specificTypes, Intent intent,
5445            String resolvedType, int flags, int userId) {
5446        if (!sUserManager.exists(userId)) return Collections.emptyList();
5447        flags = updateFlagsForResolve(flags, userId, intent);
5448        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5449                false, "query intent activity options");
5450        final String resultsAction = intent.getAction();
5451
5452        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5453                | PackageManager.GET_RESOLVED_FILTER, userId);
5454
5455        if (DEBUG_INTENT_MATCHING) {
5456            Log.v(TAG, "Query " + intent + ": " + results);
5457        }
5458
5459        int specificsPos = 0;
5460        int N;
5461
5462        // todo: note that the algorithm used here is O(N^2).  This
5463        // isn't a problem in our current environment, but if we start running
5464        // into situations where we have more than 5 or 10 matches then this
5465        // should probably be changed to something smarter...
5466
5467        // First we go through and resolve each of the specific items
5468        // that were supplied, taking care of removing any corresponding
5469        // duplicate items in the generic resolve list.
5470        if (specifics != null) {
5471            for (int i=0; i<specifics.length; i++) {
5472                final Intent sintent = specifics[i];
5473                if (sintent == null) {
5474                    continue;
5475                }
5476
5477                if (DEBUG_INTENT_MATCHING) {
5478                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5479                }
5480
5481                String action = sintent.getAction();
5482                if (resultsAction != null && resultsAction.equals(action)) {
5483                    // If this action was explicitly requested, then don't
5484                    // remove things that have it.
5485                    action = null;
5486                }
5487
5488                ResolveInfo ri = null;
5489                ActivityInfo ai = null;
5490
5491                ComponentName comp = sintent.getComponent();
5492                if (comp == null) {
5493                    ri = resolveIntent(
5494                        sintent,
5495                        specificTypes != null ? specificTypes[i] : null,
5496                            flags, userId);
5497                    if (ri == null) {
5498                        continue;
5499                    }
5500                    if (ri == mResolveInfo) {
5501                        // ACK!  Must do something better with this.
5502                    }
5503                    ai = ri.activityInfo;
5504                    comp = new ComponentName(ai.applicationInfo.packageName,
5505                            ai.name);
5506                } else {
5507                    ai = getActivityInfo(comp, flags, userId);
5508                    if (ai == null) {
5509                        continue;
5510                    }
5511                }
5512
5513                // Look for any generic query activities that are duplicates
5514                // of this specific one, and remove them from the results.
5515                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5516                N = results.size();
5517                int j;
5518                for (j=specificsPos; j<N; j++) {
5519                    ResolveInfo sri = results.get(j);
5520                    if ((sri.activityInfo.name.equals(comp.getClassName())
5521                            && sri.activityInfo.applicationInfo.packageName.equals(
5522                                    comp.getPackageName()))
5523                        || (action != null && sri.filter.matchAction(action))) {
5524                        results.remove(j);
5525                        if (DEBUG_INTENT_MATCHING) Log.v(
5526                            TAG, "Removing duplicate item from " + j
5527                            + " due to specific " + specificsPos);
5528                        if (ri == null) {
5529                            ri = sri;
5530                        }
5531                        j--;
5532                        N--;
5533                    }
5534                }
5535
5536                // Add this specific item to its proper place.
5537                if (ri == null) {
5538                    ri = new ResolveInfo();
5539                    ri.activityInfo = ai;
5540                }
5541                results.add(specificsPos, ri);
5542                ri.specificIndex = i;
5543                specificsPos++;
5544            }
5545        }
5546
5547        // Now we go through the remaining generic results and remove any
5548        // duplicate actions that are found here.
5549        N = results.size();
5550        for (int i=specificsPos; i<N-1; i++) {
5551            final ResolveInfo rii = results.get(i);
5552            if (rii.filter == null) {
5553                continue;
5554            }
5555
5556            // Iterate over all of the actions of this result's intent
5557            // filter...  typically this should be just one.
5558            final Iterator<String> it = rii.filter.actionsIterator();
5559            if (it == null) {
5560                continue;
5561            }
5562            while (it.hasNext()) {
5563                final String action = it.next();
5564                if (resultsAction != null && resultsAction.equals(action)) {
5565                    // If this action was explicitly requested, then don't
5566                    // remove things that have it.
5567                    continue;
5568                }
5569                for (int j=i+1; j<N; j++) {
5570                    final ResolveInfo rij = results.get(j);
5571                    if (rij.filter != null && rij.filter.hasAction(action)) {
5572                        results.remove(j);
5573                        if (DEBUG_INTENT_MATCHING) Log.v(
5574                            TAG, "Removing duplicate item from " + j
5575                            + " due to action " + action + " at " + i);
5576                        j--;
5577                        N--;
5578                    }
5579                }
5580            }
5581
5582            // If the caller didn't request filter information, drop it now
5583            // so we don't have to marshall/unmarshall it.
5584            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5585                rii.filter = null;
5586            }
5587        }
5588
5589        // Filter out the caller activity if so requested.
5590        if (caller != null) {
5591            N = results.size();
5592            for (int i=0; i<N; i++) {
5593                ActivityInfo ainfo = results.get(i).activityInfo;
5594                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5595                        && caller.getClassName().equals(ainfo.name)) {
5596                    results.remove(i);
5597                    break;
5598                }
5599            }
5600        }
5601
5602        // If the caller didn't request filter information,
5603        // drop them now so we don't have to
5604        // marshall/unmarshall it.
5605        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5606            N = results.size();
5607            for (int i=0; i<N; i++) {
5608                results.get(i).filter = null;
5609            }
5610        }
5611
5612        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5613        return results;
5614    }
5615
5616    @Override
5617    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5618            int userId) {
5619        if (!sUserManager.exists(userId)) return Collections.emptyList();
5620        flags = updateFlagsForResolve(flags, userId, intent);
5621        ComponentName comp = intent.getComponent();
5622        if (comp == null) {
5623            if (intent.getSelector() != null) {
5624                intent = intent.getSelector();
5625                comp = intent.getComponent();
5626            }
5627        }
5628        if (comp != null) {
5629            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5630            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5631            if (ai != null) {
5632                ResolveInfo ri = new ResolveInfo();
5633                ri.activityInfo = ai;
5634                list.add(ri);
5635            }
5636            return list;
5637        }
5638
5639        // reader
5640        synchronized (mPackages) {
5641            String pkgName = intent.getPackage();
5642            if (pkgName == null) {
5643                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5644            }
5645            final PackageParser.Package pkg = mPackages.get(pkgName);
5646            if (pkg != null) {
5647                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5648                        userId);
5649            }
5650            return null;
5651        }
5652    }
5653
5654    @Override
5655    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5656        if (!sUserManager.exists(userId)) return null;
5657        flags = updateFlagsForResolve(flags, userId, intent);
5658        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5659        if (query != null) {
5660            if (query.size() >= 1) {
5661                // If there is more than one service with the same priority,
5662                // just arbitrarily pick the first one.
5663                return query.get(0);
5664            }
5665        }
5666        return null;
5667    }
5668
5669    @Override
5670    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5671            int userId) {
5672        if (!sUserManager.exists(userId)) return Collections.emptyList();
5673        flags = updateFlagsForResolve(flags, userId, intent);
5674        ComponentName comp = intent.getComponent();
5675        if (comp == null) {
5676            if (intent.getSelector() != null) {
5677                intent = intent.getSelector();
5678                comp = intent.getComponent();
5679            }
5680        }
5681        if (comp != null) {
5682            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5683            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5684            if (si != null) {
5685                final ResolveInfo ri = new ResolveInfo();
5686                ri.serviceInfo = si;
5687                list.add(ri);
5688            }
5689            return list;
5690        }
5691
5692        // reader
5693        synchronized (mPackages) {
5694            String pkgName = intent.getPackage();
5695            if (pkgName == null) {
5696                return mServices.queryIntent(intent, resolvedType, flags, userId);
5697            }
5698            final PackageParser.Package pkg = mPackages.get(pkgName);
5699            if (pkg != null) {
5700                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5701                        userId);
5702            }
5703            return null;
5704        }
5705    }
5706
5707    @Override
5708    public List<ResolveInfo> queryIntentContentProviders(
5709            Intent intent, String resolvedType, int flags, int userId) {
5710        if (!sUserManager.exists(userId)) return Collections.emptyList();
5711        flags = updateFlagsForResolve(flags, userId, intent);
5712        ComponentName comp = intent.getComponent();
5713        if (comp == null) {
5714            if (intent.getSelector() != null) {
5715                intent = intent.getSelector();
5716                comp = intent.getComponent();
5717            }
5718        }
5719        if (comp != null) {
5720            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5721            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5722            if (pi != null) {
5723                final ResolveInfo ri = new ResolveInfo();
5724                ri.providerInfo = pi;
5725                list.add(ri);
5726            }
5727            return list;
5728        }
5729
5730        // reader
5731        synchronized (mPackages) {
5732            String pkgName = intent.getPackage();
5733            if (pkgName == null) {
5734                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5735            }
5736            final PackageParser.Package pkg = mPackages.get(pkgName);
5737            if (pkg != null) {
5738                return mProviders.queryIntentForPackage(
5739                        intent, resolvedType, flags, pkg.providers, userId);
5740            }
5741            return null;
5742        }
5743    }
5744
5745    @Override
5746    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5747        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5748        flags = updateFlagsForPackage(flags, userId, null);
5749        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5750        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5751
5752        // writer
5753        synchronized (mPackages) {
5754            ArrayList<PackageInfo> list;
5755            if (listUninstalled) {
5756                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5757                for (PackageSetting ps : mSettings.mPackages.values()) {
5758                    PackageInfo pi;
5759                    if (ps.pkg != null) {
5760                        pi = generatePackageInfo(ps.pkg, flags, userId);
5761                    } else {
5762                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5763                    }
5764                    if (pi != null) {
5765                        list.add(pi);
5766                    }
5767                }
5768            } else {
5769                list = new ArrayList<PackageInfo>(mPackages.size());
5770                for (PackageParser.Package p : mPackages.values()) {
5771                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5772                    if (pi != null) {
5773                        list.add(pi);
5774                    }
5775                }
5776            }
5777
5778            return new ParceledListSlice<PackageInfo>(list);
5779        }
5780    }
5781
5782    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5783            String[] permissions, boolean[] tmp, int flags, int userId) {
5784        int numMatch = 0;
5785        final PermissionsState permissionsState = ps.getPermissionsState();
5786        for (int i=0; i<permissions.length; i++) {
5787            final String permission = permissions[i];
5788            if (permissionsState.hasPermission(permission, userId)) {
5789                tmp[i] = true;
5790                numMatch++;
5791            } else {
5792                tmp[i] = false;
5793            }
5794        }
5795        if (numMatch == 0) {
5796            return;
5797        }
5798        PackageInfo pi;
5799        if (ps.pkg != null) {
5800            pi = generatePackageInfo(ps.pkg, flags, userId);
5801        } else {
5802            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5803        }
5804        // The above might return null in cases of uninstalled apps or install-state
5805        // skew across users/profiles.
5806        if (pi != null) {
5807            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5808                if (numMatch == permissions.length) {
5809                    pi.requestedPermissions = permissions;
5810                } else {
5811                    pi.requestedPermissions = new String[numMatch];
5812                    numMatch = 0;
5813                    for (int i=0; i<permissions.length; i++) {
5814                        if (tmp[i]) {
5815                            pi.requestedPermissions[numMatch] = permissions[i];
5816                            numMatch++;
5817                        }
5818                    }
5819                }
5820            }
5821            list.add(pi);
5822        }
5823    }
5824
5825    @Override
5826    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5827            String[] permissions, int flags, int userId) {
5828        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5829        flags = updateFlagsForPackage(flags, userId, permissions);
5830        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5831
5832        // writer
5833        synchronized (mPackages) {
5834            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5835            boolean[] tmpBools = new boolean[permissions.length];
5836            if (listUninstalled) {
5837                for (PackageSetting ps : mSettings.mPackages.values()) {
5838                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5839                }
5840            } else {
5841                for (PackageParser.Package pkg : mPackages.values()) {
5842                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5843                    if (ps != null) {
5844                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5845                                userId);
5846                    }
5847                }
5848            }
5849
5850            return new ParceledListSlice<PackageInfo>(list);
5851        }
5852    }
5853
5854    @Override
5855    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5856        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5857        flags = updateFlagsForApplication(flags, userId, null);
5858        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5859
5860        // writer
5861        synchronized (mPackages) {
5862            ArrayList<ApplicationInfo> list;
5863            if (listUninstalled) {
5864                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5865                for (PackageSetting ps : mSettings.mPackages.values()) {
5866                    ApplicationInfo ai;
5867                    if (ps.pkg != null) {
5868                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5869                                ps.readUserState(userId), userId);
5870                    } else {
5871                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5872                    }
5873                    if (ai != null) {
5874                        list.add(ai);
5875                    }
5876                }
5877            } else {
5878                list = new ArrayList<ApplicationInfo>(mPackages.size());
5879                for (PackageParser.Package p : mPackages.values()) {
5880                    if (p.mExtras != null) {
5881                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5882                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5883                        if (ai != null) {
5884                            list.add(ai);
5885                        }
5886                    }
5887                }
5888            }
5889
5890            return new ParceledListSlice<ApplicationInfo>(list);
5891        }
5892    }
5893
5894    @Override
5895    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5896        if (DISABLE_EPHEMERAL_APPS) {
5897            return null;
5898        }
5899
5900        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5901                "getEphemeralApplications");
5902        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5903                "getEphemeralApplications");
5904        synchronized (mPackages) {
5905            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5906                    .getEphemeralApplicationsLPw(userId);
5907            if (ephemeralApps != null) {
5908                return new ParceledListSlice<>(ephemeralApps);
5909            }
5910        }
5911        return null;
5912    }
5913
5914    @Override
5915    public boolean isEphemeralApplication(String packageName, int userId) {
5916        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5917                "isEphemeral");
5918        if (DISABLE_EPHEMERAL_APPS) {
5919            return false;
5920        }
5921
5922        if (!isCallerSameApp(packageName)) {
5923            return false;
5924        }
5925        synchronized (mPackages) {
5926            PackageParser.Package pkg = mPackages.get(packageName);
5927            if (pkg != null) {
5928                return pkg.applicationInfo.isEphemeralApp();
5929            }
5930        }
5931        return false;
5932    }
5933
5934    @Override
5935    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5936        if (DISABLE_EPHEMERAL_APPS) {
5937            return null;
5938        }
5939
5940        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5941                "getCookie");
5942        if (!isCallerSameApp(packageName)) {
5943            return null;
5944        }
5945        synchronized (mPackages) {
5946            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5947                    packageName, userId);
5948        }
5949    }
5950
5951    @Override
5952    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5953        if (DISABLE_EPHEMERAL_APPS) {
5954            return true;
5955        }
5956
5957        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5958                "setCookie");
5959        if (!isCallerSameApp(packageName)) {
5960            return false;
5961        }
5962        synchronized (mPackages) {
5963            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5964                    packageName, cookie, userId);
5965        }
5966    }
5967
5968    @Override
5969    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5970        if (DISABLE_EPHEMERAL_APPS) {
5971            return null;
5972        }
5973
5974        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5975                "getEphemeralApplicationIcon");
5976        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5977                "getEphemeralApplicationIcon");
5978        synchronized (mPackages) {
5979            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5980                    packageName, userId);
5981        }
5982    }
5983
5984    private boolean isCallerSameApp(String packageName) {
5985        PackageParser.Package pkg = mPackages.get(packageName);
5986        return pkg != null
5987                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5988    }
5989
5990    public List<ApplicationInfo> getPersistentApplications(int flags) {
5991        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5992
5993        // reader
5994        synchronized (mPackages) {
5995            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5996            final int userId = UserHandle.getCallingUserId();
5997            while (i.hasNext()) {
5998                final PackageParser.Package p = i.next();
5999                if (p.applicationInfo != null
6000                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6001                        && (!mSafeMode || isSystemApp(p))) {
6002                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6003                    if (ps != null) {
6004                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6005                                ps.readUserState(userId), userId);
6006                        if (ai != null) {
6007                            finalList.add(ai);
6008                        }
6009                    }
6010                }
6011            }
6012        }
6013
6014        return finalList;
6015    }
6016
6017    @Override
6018    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6019        if (!sUserManager.exists(userId)) return null;
6020        flags = updateFlagsForComponent(flags, userId, name);
6021        // reader
6022        synchronized (mPackages) {
6023            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6024            PackageSetting ps = provider != null
6025                    ? mSettings.mPackages.get(provider.owner.packageName)
6026                    : null;
6027            return ps != null
6028                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6029                    ? PackageParser.generateProviderInfo(provider, flags,
6030                            ps.readUserState(userId), userId)
6031                    : null;
6032        }
6033    }
6034
6035    /**
6036     * @deprecated
6037     */
6038    @Deprecated
6039    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6040        // reader
6041        synchronized (mPackages) {
6042            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6043                    .entrySet().iterator();
6044            final int userId = UserHandle.getCallingUserId();
6045            while (i.hasNext()) {
6046                Map.Entry<String, PackageParser.Provider> entry = i.next();
6047                PackageParser.Provider p = entry.getValue();
6048                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6049
6050                if (ps != null && p.syncable
6051                        && (!mSafeMode || (p.info.applicationInfo.flags
6052                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6053                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6054                            ps.readUserState(userId), userId);
6055                    if (info != null) {
6056                        outNames.add(entry.getKey());
6057                        outInfo.add(info);
6058                    }
6059                }
6060            }
6061        }
6062    }
6063
6064    @Override
6065    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6066            int uid, int flags) {
6067        final int userId = processName != null ? UserHandle.getUserId(uid)
6068                : UserHandle.getCallingUserId();
6069        if (!sUserManager.exists(userId)) return null;
6070        flags = updateFlagsForComponent(flags, userId, processName);
6071
6072        ArrayList<ProviderInfo> finalList = null;
6073        // reader
6074        synchronized (mPackages) {
6075            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6076            while (i.hasNext()) {
6077                final PackageParser.Provider p = i.next();
6078                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6079                if (ps != null && p.info.authority != null
6080                        && (processName == null
6081                                || (p.info.processName.equals(processName)
6082                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6083                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6084                    if (finalList == null) {
6085                        finalList = new ArrayList<ProviderInfo>(3);
6086                    }
6087                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6088                            ps.readUserState(userId), userId);
6089                    if (info != null) {
6090                        finalList.add(info);
6091                    }
6092                }
6093            }
6094        }
6095
6096        if (finalList != null) {
6097            Collections.sort(finalList, mProviderInitOrderSorter);
6098            return new ParceledListSlice<ProviderInfo>(finalList);
6099        }
6100
6101        return null;
6102    }
6103
6104    @Override
6105    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6106        // reader
6107        synchronized (mPackages) {
6108            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6109            return PackageParser.generateInstrumentationInfo(i, flags);
6110        }
6111    }
6112
6113    @Override
6114    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6115            int flags) {
6116        ArrayList<InstrumentationInfo> finalList =
6117            new ArrayList<InstrumentationInfo>();
6118
6119        // reader
6120        synchronized (mPackages) {
6121            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6122            while (i.hasNext()) {
6123                final PackageParser.Instrumentation p = i.next();
6124                if (targetPackage == null
6125                        || targetPackage.equals(p.info.targetPackage)) {
6126                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6127                            flags);
6128                    if (ii != null) {
6129                        finalList.add(ii);
6130                    }
6131                }
6132            }
6133        }
6134
6135        return finalList;
6136    }
6137
6138    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6139        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6140        if (overlays == null) {
6141            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6142            return;
6143        }
6144        for (PackageParser.Package opkg : overlays.values()) {
6145            // Not much to do if idmap fails: we already logged the error
6146            // and we certainly don't want to abort installation of pkg simply
6147            // because an overlay didn't fit properly. For these reasons,
6148            // ignore the return value of createIdmapForPackagePairLI.
6149            createIdmapForPackagePairLI(pkg, opkg);
6150        }
6151    }
6152
6153    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6154            PackageParser.Package opkg) {
6155        if (!opkg.mTrustedOverlay) {
6156            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6157                    opkg.baseCodePath + ": overlay not trusted");
6158            return false;
6159        }
6160        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6161        if (overlaySet == null) {
6162            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6163                    opkg.baseCodePath + " but target package has no known overlays");
6164            return false;
6165        }
6166        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6167        // TODO: generate idmap for split APKs
6168        try {
6169            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6170        } catch (InstallerException e) {
6171            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6172                    + opkg.baseCodePath);
6173            return false;
6174        }
6175        PackageParser.Package[] overlayArray =
6176            overlaySet.values().toArray(new PackageParser.Package[0]);
6177        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6178            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6179                return p1.mOverlayPriority - p2.mOverlayPriority;
6180            }
6181        };
6182        Arrays.sort(overlayArray, cmp);
6183
6184        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6185        int i = 0;
6186        for (PackageParser.Package p : overlayArray) {
6187            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6188        }
6189        return true;
6190    }
6191
6192    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6194        try {
6195            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6196        } finally {
6197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6198        }
6199    }
6200
6201    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6202        final File[] files = dir.listFiles();
6203        if (ArrayUtils.isEmpty(files)) {
6204            Log.d(TAG, "No files in app dir " + dir);
6205            return;
6206        }
6207
6208        if (DEBUG_PACKAGE_SCANNING) {
6209            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6210                    + " flags=0x" + Integer.toHexString(parseFlags));
6211        }
6212
6213        for (File file : files) {
6214            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6215                    && !PackageInstallerService.isStageName(file.getName());
6216            if (!isPackage) {
6217                // Ignore entries which are not packages
6218                continue;
6219            }
6220            try {
6221                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6222                        scanFlags, currentTime, null);
6223            } catch (PackageManagerException e) {
6224                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6225
6226                // Delete invalid userdata apps
6227                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6228                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6229                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6230                    removeCodePathLI(file);
6231                }
6232            }
6233        }
6234    }
6235
6236    private static File getSettingsProblemFile() {
6237        File dataDir = Environment.getDataDirectory();
6238        File systemDir = new File(dataDir, "system");
6239        File fname = new File(systemDir, "uiderrors.txt");
6240        return fname;
6241    }
6242
6243    static void reportSettingsProblem(int priority, String msg) {
6244        logCriticalInfo(priority, msg);
6245    }
6246
6247    static void logCriticalInfo(int priority, String msg) {
6248        Slog.println(priority, TAG, msg);
6249        EventLogTags.writePmCriticalInfo(msg);
6250        try {
6251            File fname = getSettingsProblemFile();
6252            FileOutputStream out = new FileOutputStream(fname, true);
6253            PrintWriter pw = new FastPrintWriter(out);
6254            SimpleDateFormat formatter = new SimpleDateFormat();
6255            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6256            pw.println(dateString + ": " + msg);
6257            pw.close();
6258            FileUtils.setPermissions(
6259                    fname.toString(),
6260                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6261                    -1, -1);
6262        } catch (java.io.IOException e) {
6263        }
6264    }
6265
6266    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6267            PackageParser.Package pkg, File srcFile, int parseFlags)
6268            throws PackageManagerException {
6269        if (ps != null
6270                && ps.codePath.equals(srcFile)
6271                && ps.timeStamp == srcFile.lastModified()
6272                && !isCompatSignatureUpdateNeeded(pkg)
6273                && !isRecoverSignatureUpdateNeeded(pkg)) {
6274            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6275            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6276            ArraySet<PublicKey> signingKs;
6277            synchronized (mPackages) {
6278                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6279            }
6280            if (ps.signatures.mSignatures != null
6281                    && ps.signatures.mSignatures.length != 0
6282                    && signingKs != null) {
6283                // Optimization: reuse the existing cached certificates
6284                // if the package appears to be unchanged.
6285                pkg.mSignatures = ps.signatures.mSignatures;
6286                pkg.mSigningKeys = signingKs;
6287                return;
6288            }
6289
6290            Slog.w(TAG, "PackageSetting for " + ps.name
6291                    + " is missing signatures.  Collecting certs again to recover them.");
6292        } else {
6293            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6294        }
6295
6296        try {
6297            pp.collectCertificates(pkg, parseFlags);
6298        } catch (PackageParserException e) {
6299            throw PackageManagerException.from(e);
6300        }
6301    }
6302
6303    /**
6304     *  Traces a package scan.
6305     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6306     */
6307    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6308            long currentTime, UserHandle user) throws PackageManagerException {
6309        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6310        try {
6311            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6312        } finally {
6313            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6314        }
6315    }
6316
6317    /**
6318     *  Scans a package and returns the newly parsed package.
6319     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6320     */
6321    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6322            long currentTime, UserHandle user) throws PackageManagerException {
6323        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6324        parseFlags |= mDefParseFlags;
6325        PackageParser pp = new PackageParser();
6326        pp.setSeparateProcesses(mSeparateProcesses);
6327        pp.setOnlyCoreApps(mOnlyCore);
6328        pp.setDisplayMetrics(mMetrics);
6329
6330        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6331            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6332        }
6333
6334        final PackageParser.Package pkg;
6335        try {
6336            pkg = pp.parsePackage(scanFile, parseFlags);
6337        } catch (PackageParserException e) {
6338            throw PackageManagerException.from(e);
6339        }
6340
6341        PackageSetting ps = null;
6342        PackageSetting updatedPkg;
6343        // reader
6344        synchronized (mPackages) {
6345            // Look to see if we already know about this package.
6346            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6347            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6348                // This package has been renamed to its original name.  Let's
6349                // use that.
6350                ps = mSettings.peekPackageLPr(oldName);
6351            }
6352            // If there was no original package, see one for the real package name.
6353            if (ps == null) {
6354                ps = mSettings.peekPackageLPr(pkg.packageName);
6355            }
6356            // Check to see if this package could be hiding/updating a system
6357            // package.  Must look for it either under the original or real
6358            // package name depending on our state.
6359            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6360            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6361        }
6362        boolean updatedPkgBetter = false;
6363        // First check if this is a system package that may involve an update
6364        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6365            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6366            // it needs to drop FLAG_PRIVILEGED.
6367            if (locationIsPrivileged(scanFile)) {
6368                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6369            } else {
6370                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6371            }
6372
6373            if (ps != null && !ps.codePath.equals(scanFile)) {
6374                // The path has changed from what was last scanned...  check the
6375                // version of the new path against what we have stored to determine
6376                // what to do.
6377                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6378                if (pkg.mVersionCode <= ps.versionCode) {
6379                    // The system package has been updated and the code path does not match
6380                    // Ignore entry. Skip it.
6381                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6382                            + " ignored: updated version " + ps.versionCode
6383                            + " better than this " + pkg.mVersionCode);
6384                    if (!updatedPkg.codePath.equals(scanFile)) {
6385                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6386                                + ps.name + " changing from " + updatedPkg.codePathString
6387                                + " to " + scanFile);
6388                        updatedPkg.codePath = scanFile;
6389                        updatedPkg.codePathString = scanFile.toString();
6390                        updatedPkg.resourcePath = scanFile;
6391                        updatedPkg.resourcePathString = scanFile.toString();
6392                    }
6393                    updatedPkg.pkg = pkg;
6394                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6395                            "Package " + ps.name + " at " + scanFile
6396                                    + " ignored: updated version " + ps.versionCode
6397                                    + " better than this " + pkg.mVersionCode);
6398                } else {
6399                    // The current app on the system partition is better than
6400                    // what we have updated to on the data partition; switch
6401                    // back to the system partition version.
6402                    // At this point, its safely assumed that package installation for
6403                    // apps in system partition will go through. If not there won't be a working
6404                    // version of the app
6405                    // writer
6406                    synchronized (mPackages) {
6407                        // Just remove the loaded entries from package lists.
6408                        mPackages.remove(ps.name);
6409                    }
6410
6411                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6412                            + " reverting from " + ps.codePathString
6413                            + ": new version " + pkg.mVersionCode
6414                            + " better than installed " + ps.versionCode);
6415
6416                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6417                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6418                    synchronized (mInstallLock) {
6419                        args.cleanUpResourcesLI();
6420                    }
6421                    synchronized (mPackages) {
6422                        mSettings.enableSystemPackageLPw(ps.name);
6423                    }
6424                    updatedPkgBetter = true;
6425                }
6426            }
6427        }
6428
6429        if (updatedPkg != null) {
6430            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6431            // initially
6432            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6433
6434            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6435            // flag set initially
6436            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6437                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6438            }
6439        }
6440
6441        // Verify certificates against what was last scanned
6442        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6443
6444        /*
6445         * A new system app appeared, but we already had a non-system one of the
6446         * same name installed earlier.
6447         */
6448        boolean shouldHideSystemApp = false;
6449        if (updatedPkg == null && ps != null
6450                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6451            /*
6452             * Check to make sure the signatures match first. If they don't,
6453             * wipe the installed application and its data.
6454             */
6455            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6456                    != PackageManager.SIGNATURE_MATCH) {
6457                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6458                        + " signatures don't match existing userdata copy; removing");
6459                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6460                ps = null;
6461            } else {
6462                /*
6463                 * If the newly-added system app is an older version than the
6464                 * already installed version, hide it. It will be scanned later
6465                 * and re-added like an update.
6466                 */
6467                if (pkg.mVersionCode <= ps.versionCode) {
6468                    shouldHideSystemApp = true;
6469                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6470                            + " but new version " + pkg.mVersionCode + " better than installed "
6471                            + ps.versionCode + "; hiding system");
6472                } else {
6473                    /*
6474                     * The newly found system app is a newer version that the
6475                     * one previously installed. Simply remove the
6476                     * already-installed application and replace it with our own
6477                     * while keeping the application data.
6478                     */
6479                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6480                            + " reverting from " + ps.codePathString + ": new version "
6481                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6482                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6483                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6484                    synchronized (mInstallLock) {
6485                        args.cleanUpResourcesLI();
6486                    }
6487                }
6488            }
6489        }
6490
6491        // The apk is forward locked (not public) if its code and resources
6492        // are kept in different files. (except for app in either system or
6493        // vendor path).
6494        // TODO grab this value from PackageSettings
6495        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6496            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6497                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6498            }
6499        }
6500
6501        // TODO: extend to support forward-locked splits
6502        String resourcePath = null;
6503        String baseResourcePath = null;
6504        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6505            if (ps != null && ps.resourcePathString != null) {
6506                resourcePath = ps.resourcePathString;
6507                baseResourcePath = ps.resourcePathString;
6508            } else {
6509                // Should not happen at all. Just log an error.
6510                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6511            }
6512        } else {
6513            resourcePath = pkg.codePath;
6514            baseResourcePath = pkg.baseCodePath;
6515        }
6516
6517        // Set application objects path explicitly.
6518        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6519        pkg.applicationInfo.setCodePath(pkg.codePath);
6520        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6521        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6522        pkg.applicationInfo.setResourcePath(resourcePath);
6523        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6524        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6525
6526        // Note that we invoke the following method only if we are about to unpack an application
6527        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6528                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6529
6530        /*
6531         * If the system app should be overridden by a previously installed
6532         * data, hide the system app now and let the /data/app scan pick it up
6533         * again.
6534         */
6535        if (shouldHideSystemApp) {
6536            synchronized (mPackages) {
6537                mSettings.disableSystemPackageLPw(pkg.packageName);
6538            }
6539        }
6540
6541        return scannedPkg;
6542    }
6543
6544    private static String fixProcessName(String defProcessName,
6545            String processName, int uid) {
6546        if (processName == null) {
6547            return defProcessName;
6548        }
6549        return processName;
6550    }
6551
6552    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6553            throws PackageManagerException {
6554        if (pkgSetting.signatures.mSignatures != null) {
6555            // Already existing package. Make sure signatures match
6556            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6557                    == PackageManager.SIGNATURE_MATCH;
6558            if (!match) {
6559                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6560                        == PackageManager.SIGNATURE_MATCH;
6561            }
6562            if (!match) {
6563                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6564                        == PackageManager.SIGNATURE_MATCH;
6565            }
6566            if (!match) {
6567                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6568                        + pkg.packageName + " signatures do not match the "
6569                        + "previously installed version; ignoring!");
6570            }
6571        }
6572
6573        // Check for shared user signatures
6574        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6575            // Already existing package. Make sure signatures match
6576            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6577                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6578            if (!match) {
6579                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6580                        == PackageManager.SIGNATURE_MATCH;
6581            }
6582            if (!match) {
6583                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6584                        == PackageManager.SIGNATURE_MATCH;
6585            }
6586            if (!match) {
6587                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6588                        "Package " + pkg.packageName
6589                        + " has no signatures that match those in shared user "
6590                        + pkgSetting.sharedUser.name + "; ignoring!");
6591            }
6592        }
6593    }
6594
6595    /**
6596     * Enforces that only the system UID or root's UID can call a method exposed
6597     * via Binder.
6598     *
6599     * @param message used as message if SecurityException is thrown
6600     * @throws SecurityException if the caller is not system or root
6601     */
6602    private static final void enforceSystemOrRoot(String message) {
6603        final int uid = Binder.getCallingUid();
6604        if (uid != Process.SYSTEM_UID && uid != 0) {
6605            throw new SecurityException(message);
6606        }
6607    }
6608
6609    @Override
6610    public void performFstrimIfNeeded() {
6611        enforceSystemOrRoot("Only the system can request fstrim");
6612
6613        // Before everything else, see whether we need to fstrim.
6614        try {
6615            IMountService ms = PackageHelper.getMountService();
6616            if (ms != null) {
6617                final boolean isUpgrade = isUpgrade();
6618                boolean doTrim = isUpgrade;
6619                if (doTrim) {
6620                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6621                } else {
6622                    final long interval = android.provider.Settings.Global.getLong(
6623                            mContext.getContentResolver(),
6624                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6625                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6626                    if (interval > 0) {
6627                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6628                        if (timeSinceLast > interval) {
6629                            doTrim = true;
6630                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6631                                    + "; running immediately");
6632                        }
6633                    }
6634                }
6635                if (doTrim) {
6636                    if (!isFirstBoot()) {
6637                        try {
6638                            ActivityManagerNative.getDefault().showBootMessage(
6639                                    mContext.getResources().getString(
6640                                            R.string.android_upgrading_fstrim), true);
6641                        } catch (RemoteException e) {
6642                        }
6643                    }
6644                    ms.runMaintenance();
6645                }
6646            } else {
6647                Slog.e(TAG, "Mount service unavailable!");
6648            }
6649        } catch (RemoteException e) {
6650            // Can't happen; MountService is local
6651        }
6652    }
6653
6654    @Override
6655    public void extractPackagesIfNeeded() {
6656        enforceSystemOrRoot("Only the system can request package extraction");
6657
6658        // Extract pacakges only if profile-guided compilation is enabled because
6659        // otherwise BackgroundDexOptService will not dexopt them later.
6660        if (mUseJitProfiles) {
6661            ArraySet<String> pkgs = getOptimizablePackages();
6662            if (pkgs != null) {
6663                for (String pkg : pkgs) {
6664                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6665                            true /* extractOnly */, false /* force */);
6666                }
6667            }
6668        }
6669    }
6670
6671    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6672        List<ResolveInfo> ris = null;
6673        try {
6674            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6675                    intent, null, 0, userId);
6676        } catch (RemoteException e) {
6677        }
6678        ArraySet<String> pkgNames = new ArraySet<String>();
6679        if (ris != null) {
6680            for (ResolveInfo ri : ris) {
6681                pkgNames.add(ri.activityInfo.packageName);
6682            }
6683        }
6684        return pkgNames;
6685    }
6686
6687    @Override
6688    public void notifyPackageUse(String packageName) {
6689        synchronized (mPackages) {
6690            PackageParser.Package p = mPackages.get(packageName);
6691            if (p == null) {
6692                return;
6693            }
6694            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6695        }
6696    }
6697
6698    // TODO: this is not used nor needed. Delete it.
6699    @Override
6700    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6701        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6702                false /* extractOnly */, false /* force */);
6703    }
6704
6705    @Override
6706    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6707            boolean extractOnly, boolean force) {
6708        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6709    }
6710
6711    private boolean performDexOptTraced(String packageName, String instructionSet,
6712                boolean useProfiles, boolean extractOnly, boolean force) {
6713        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6714        try {
6715            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6716                    force);
6717        } finally {
6718            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6719        }
6720    }
6721
6722    private boolean performDexOptInternal(String packageName, String instructionSet,
6723                boolean useProfiles, boolean extractOnly, boolean force) {
6724        PackageParser.Package p;
6725        final String targetInstructionSet;
6726        synchronized (mPackages) {
6727            p = mPackages.get(packageName);
6728            if (p == null) {
6729                return false;
6730            }
6731            mPackageUsage.write(false);
6732
6733            targetInstructionSet = instructionSet != null ? instructionSet :
6734                    getPrimaryInstructionSet(p.applicationInfo);
6735            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6736                // Skip only if we do not use profiles since they might trigger a recompilation.
6737                return false;
6738            }
6739        }
6740        long callingId = Binder.clearCallingIdentity();
6741        try {
6742            synchronized (mInstallLock) {
6743                final String[] instructionSets = new String[] { targetInstructionSet };
6744                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6745                        useProfiles, extractOnly, force);
6746                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6747            }
6748        } finally {
6749            Binder.restoreCallingIdentity(callingId);
6750        }
6751    }
6752
6753    public ArraySet<String> getOptimizablePackages() {
6754        ArraySet<String> pkgs = new ArraySet<String>();
6755        synchronized (mPackages) {
6756            for (PackageParser.Package p : mPackages.values()) {
6757                if (PackageDexOptimizer.canOptimizePackage(p)) {
6758                    pkgs.add(p.packageName);
6759                }
6760            }
6761        }
6762        return pkgs;
6763    }
6764
6765    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6766            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6767        // Select the dex optimizer based on the force parameter.
6768        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6769        //       allocate an object here.
6770        PackageDexOptimizer pdo = force
6771                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6772                : mPackageDexOptimizer;
6773
6774        // Optimize all dependencies first. Note: we ignore the return value and march on
6775        // on errors.
6776        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6777        if (!deps.isEmpty()) {
6778            for (PackageParser.Package depPackage : deps) {
6779                // TODO: Analyze and investigate if we (should) profile libraries.
6780                // Currently this will do a full compilation of the library.
6781                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6782                        false /* extractOnly */);
6783            }
6784        }
6785
6786        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6787    }
6788
6789    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6790        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6791            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6792            Set<String> collectedNames = new HashSet<>();
6793            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6794
6795            retValue.remove(p);
6796
6797            return retValue;
6798        } else {
6799            return Collections.emptyList();
6800        }
6801    }
6802
6803    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6804            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6805        if (!collectedNames.contains(p.packageName)) {
6806            collectedNames.add(p.packageName);
6807            collected.add(p);
6808
6809            if (p.usesLibraries != null) {
6810                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6811            }
6812            if (p.usesOptionalLibraries != null) {
6813                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6814                        collectedNames);
6815            }
6816        }
6817    }
6818
6819    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6820            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6821        for (String libName : libs) {
6822            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6823            if (libPkg != null) {
6824                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6825            }
6826        }
6827    }
6828
6829    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6830        synchronized (mPackages) {
6831            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6832            if (lib != null && lib.apk != null) {
6833                return mPackages.get(lib.apk);
6834            }
6835        }
6836        return null;
6837    }
6838
6839    public void shutdown() {
6840        mPackageUsage.write(true);
6841    }
6842
6843    @Override
6844    public void forceDexOpt(String packageName) {
6845        enforceSystemOrRoot("forceDexOpt");
6846
6847        PackageParser.Package pkg;
6848        synchronized (mPackages) {
6849            pkg = mPackages.get(packageName);
6850            if (pkg == null) {
6851                throw new IllegalArgumentException("Unknown package: " + packageName);
6852            }
6853        }
6854
6855        synchronized (mInstallLock) {
6856            final String[] instructionSets = new String[] {
6857                    getPrimaryInstructionSet(pkg.applicationInfo) };
6858
6859            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6860
6861            // Whoever is calling forceDexOpt wants a fully compiled package.
6862            // Don't use profiles since that may cause compilation to be skipped.
6863            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6864                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6865
6866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6867            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6868                throw new IllegalStateException("Failed to dexopt: " + res);
6869            }
6870        }
6871    }
6872
6873    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6874        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6875            Slog.w(TAG, "Unable to update from " + oldPkg.name
6876                    + " to " + newPkg.packageName
6877                    + ": old package not in system partition");
6878            return false;
6879        } else if (mPackages.get(oldPkg.name) != null) {
6880            Slog.w(TAG, "Unable to update from " + oldPkg.name
6881                    + " to " + newPkg.packageName
6882                    + ": old package still exists");
6883            return false;
6884        }
6885        return true;
6886    }
6887
6888    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6889        // TODO: triage flags as part of 26466827
6890        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6891
6892        boolean res = true;
6893        final int[] users = sUserManager.getUserIds();
6894        for (int user : users) {
6895            try {
6896                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6897            } catch (InstallerException e) {
6898                Slog.w(TAG, "Failed to delete data directory", e);
6899                res = false;
6900            }
6901        }
6902        return res;
6903    }
6904
6905    void removeCodePathLI(File codePath) {
6906        if (codePath.isDirectory()) {
6907            try {
6908                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6909            } catch (InstallerException e) {
6910                Slog.w(TAG, "Failed to remove code path", e);
6911            }
6912        } else {
6913            codePath.delete();
6914        }
6915    }
6916
6917    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6918        try {
6919            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6920        } catch (InstallerException e) {
6921            Slog.w(TAG, "Failed to destroy app data", e);
6922        }
6923    }
6924
6925    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6926            int appId, String seinfo) {
6927        try {
6928            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6929        } catch (InstallerException e) {
6930            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6931        }
6932    }
6933
6934    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6935        // TODO: triage flags as part of 26466827
6936        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6937
6938        final int[] users = sUserManager.getUserIds();
6939        for (int user : users) {
6940            try {
6941                mInstaller.clearAppData(volumeUuid, packageName, user,
6942                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6943            } catch (InstallerException e) {
6944                Slog.w(TAG, "Failed to delete code cache directory", e);
6945            }
6946        }
6947    }
6948
6949    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6950            PackageParser.Package changingLib) {
6951        if (file.path != null) {
6952            usesLibraryFiles.add(file.path);
6953            return;
6954        }
6955        PackageParser.Package p = mPackages.get(file.apk);
6956        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6957            // If we are doing this while in the middle of updating a library apk,
6958            // then we need to make sure to use that new apk for determining the
6959            // dependencies here.  (We haven't yet finished committing the new apk
6960            // to the package manager state.)
6961            if (p == null || p.packageName.equals(changingLib.packageName)) {
6962                p = changingLib;
6963            }
6964        }
6965        if (p != null) {
6966            usesLibraryFiles.addAll(p.getAllCodePaths());
6967        }
6968    }
6969
6970    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6971            PackageParser.Package changingLib) throws PackageManagerException {
6972        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6973            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6974            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6975            for (int i=0; i<N; i++) {
6976                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6977                if (file == null) {
6978                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6979                            "Package " + pkg.packageName + " requires unavailable shared library "
6980                            + pkg.usesLibraries.get(i) + "; failing!");
6981                }
6982                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6983            }
6984            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6985            for (int i=0; i<N; i++) {
6986                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6987                if (file == null) {
6988                    Slog.w(TAG, "Package " + pkg.packageName
6989                            + " desires unavailable shared library "
6990                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6991                } else {
6992                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6993                }
6994            }
6995            N = usesLibraryFiles.size();
6996            if (N > 0) {
6997                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6998            } else {
6999                pkg.usesLibraryFiles = null;
7000            }
7001        }
7002    }
7003
7004    private static boolean hasString(List<String> list, List<String> which) {
7005        if (list == null) {
7006            return false;
7007        }
7008        for (int i=list.size()-1; i>=0; i--) {
7009            for (int j=which.size()-1; j>=0; j--) {
7010                if (which.get(j).equals(list.get(i))) {
7011                    return true;
7012                }
7013            }
7014        }
7015        return false;
7016    }
7017
7018    private void updateAllSharedLibrariesLPw() {
7019        for (PackageParser.Package pkg : mPackages.values()) {
7020            try {
7021                updateSharedLibrariesLPw(pkg, null);
7022            } catch (PackageManagerException e) {
7023                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7024            }
7025        }
7026    }
7027
7028    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7029            PackageParser.Package changingPkg) {
7030        ArrayList<PackageParser.Package> res = null;
7031        for (PackageParser.Package pkg : mPackages.values()) {
7032            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7033                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7034                if (res == null) {
7035                    res = new ArrayList<PackageParser.Package>();
7036                }
7037                res.add(pkg);
7038                try {
7039                    updateSharedLibrariesLPw(pkg, changingPkg);
7040                } catch (PackageManagerException e) {
7041                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7042                }
7043            }
7044        }
7045        return res;
7046    }
7047
7048    /**
7049     * Derive the value of the {@code cpuAbiOverride} based on the provided
7050     * value and an optional stored value from the package settings.
7051     */
7052    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7053        String cpuAbiOverride = null;
7054
7055        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7056            cpuAbiOverride = null;
7057        } else if (abiOverride != null) {
7058            cpuAbiOverride = abiOverride;
7059        } else if (settings != null) {
7060            cpuAbiOverride = settings.cpuAbiOverrideString;
7061        }
7062
7063        return cpuAbiOverride;
7064    }
7065
7066    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7067            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7068        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7069        try {
7070            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7071        } finally {
7072            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7073        }
7074    }
7075
7076    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7077            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7078        boolean success = false;
7079        try {
7080            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7081                    currentTime, user);
7082            success = true;
7083            return res;
7084        } finally {
7085            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7086                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7087            }
7088        }
7089    }
7090
7091    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7092            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7093        final File scanFile = new File(pkg.codePath);
7094        if (pkg.applicationInfo.getCodePath() == null ||
7095                pkg.applicationInfo.getResourcePath() == null) {
7096            // Bail out. The resource and code paths haven't been set.
7097            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7098                    "Code and resource paths haven't been set correctly");
7099        }
7100
7101        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7102            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7103        } else {
7104            // Only allow system apps to be flagged as core apps.
7105            pkg.coreApp = false;
7106        }
7107
7108        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7109            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7110        }
7111
7112        if (mCustomResolverComponentName != null &&
7113                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7114            setUpCustomResolverActivity(pkg);
7115        }
7116
7117        if (pkg.packageName.equals("android")) {
7118            synchronized (mPackages) {
7119                if (mAndroidApplication != null) {
7120                    Slog.w(TAG, "*************************************************");
7121                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7122                    Slog.w(TAG, " file=" + scanFile);
7123                    Slog.w(TAG, "*************************************************");
7124                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7125                            "Core android package being redefined.  Skipping.");
7126                }
7127
7128                // Set up information for our fall-back user intent resolution activity.
7129                mPlatformPackage = pkg;
7130                pkg.mVersionCode = mSdkVersion;
7131                mAndroidApplication = pkg.applicationInfo;
7132
7133                if (!mResolverReplaced) {
7134                    mResolveActivity.applicationInfo = mAndroidApplication;
7135                    mResolveActivity.name = ResolverActivity.class.getName();
7136                    mResolveActivity.packageName = mAndroidApplication.packageName;
7137                    mResolveActivity.processName = "system:ui";
7138                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7139                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7140                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7141                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7142                    mResolveActivity.exported = true;
7143                    mResolveActivity.enabled = true;
7144                    mResolveInfo.activityInfo = mResolveActivity;
7145                    mResolveInfo.priority = 0;
7146                    mResolveInfo.preferredOrder = 0;
7147                    mResolveInfo.match = 0;
7148                    mResolveComponentName = new ComponentName(
7149                            mAndroidApplication.packageName, mResolveActivity.name);
7150                }
7151            }
7152        }
7153
7154        if (DEBUG_PACKAGE_SCANNING) {
7155            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7156                Log.d(TAG, "Scanning package " + pkg.packageName);
7157        }
7158
7159        if (mPackages.containsKey(pkg.packageName)
7160                || mSharedLibraries.containsKey(pkg.packageName)) {
7161            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7162                    "Application package " + pkg.packageName
7163                    + " already installed.  Skipping duplicate.");
7164        }
7165
7166        // If we're only installing presumed-existing packages, require that the
7167        // scanned APK is both already known and at the path previously established
7168        // for it.  Previously unknown packages we pick up normally, but if we have an
7169        // a priori expectation about this package's install presence, enforce it.
7170        // With a singular exception for new system packages. When an OTA contains
7171        // a new system package, we allow the codepath to change from a system location
7172        // to the user-installed location. If we don't allow this change, any newer,
7173        // user-installed version of the application will be ignored.
7174        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7175            if (mExpectingBetter.containsKey(pkg.packageName)) {
7176                logCriticalInfo(Log.WARN,
7177                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7178            } else {
7179                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7180                if (known != null) {
7181                    if (DEBUG_PACKAGE_SCANNING) {
7182                        Log.d(TAG, "Examining " + pkg.codePath
7183                                + " and requiring known paths " + known.codePathString
7184                                + " & " + known.resourcePathString);
7185                    }
7186                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7187                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7188                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7189                                "Application package " + pkg.packageName
7190                                + " found at " + pkg.applicationInfo.getCodePath()
7191                                + " but expected at " + known.codePathString + "; ignoring.");
7192                    }
7193                }
7194            }
7195        }
7196
7197        // Initialize package source and resource directories
7198        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7199        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7200
7201        SharedUserSetting suid = null;
7202        PackageSetting pkgSetting = null;
7203
7204        if (!isSystemApp(pkg)) {
7205            // Only system apps can use these features.
7206            pkg.mOriginalPackages = null;
7207            pkg.mRealPackage = null;
7208            pkg.mAdoptPermissions = null;
7209        }
7210
7211        // writer
7212        synchronized (mPackages) {
7213            if (pkg.mSharedUserId != null) {
7214                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7215                if (suid == null) {
7216                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7217                            "Creating application package " + pkg.packageName
7218                            + " for shared user failed");
7219                }
7220                if (DEBUG_PACKAGE_SCANNING) {
7221                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7222                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7223                                + "): packages=" + suid.packages);
7224                }
7225            }
7226
7227            // Check if we are renaming from an original package name.
7228            PackageSetting origPackage = null;
7229            String realName = null;
7230            if (pkg.mOriginalPackages != null) {
7231                // This package may need to be renamed to a previously
7232                // installed name.  Let's check on that...
7233                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7234                if (pkg.mOriginalPackages.contains(renamed)) {
7235                    // This package had originally been installed as the
7236                    // original name, and we have already taken care of
7237                    // transitioning to the new one.  Just update the new
7238                    // one to continue using the old name.
7239                    realName = pkg.mRealPackage;
7240                    if (!pkg.packageName.equals(renamed)) {
7241                        // Callers into this function may have already taken
7242                        // care of renaming the package; only do it here if
7243                        // it is not already done.
7244                        pkg.setPackageName(renamed);
7245                    }
7246
7247                } else {
7248                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7249                        if ((origPackage = mSettings.peekPackageLPr(
7250                                pkg.mOriginalPackages.get(i))) != null) {
7251                            // We do have the package already installed under its
7252                            // original name...  should we use it?
7253                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7254                                // New package is not compatible with original.
7255                                origPackage = null;
7256                                continue;
7257                            } else if (origPackage.sharedUser != null) {
7258                                // Make sure uid is compatible between packages.
7259                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7260                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7261                                            + " to " + pkg.packageName + ": old uid "
7262                                            + origPackage.sharedUser.name
7263                                            + " differs from " + pkg.mSharedUserId);
7264                                    origPackage = null;
7265                                    continue;
7266                                }
7267                            } else {
7268                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7269                                        + pkg.packageName + " to old name " + origPackage.name);
7270                            }
7271                            break;
7272                        }
7273                    }
7274                }
7275            }
7276
7277            if (mTransferedPackages.contains(pkg.packageName)) {
7278                Slog.w(TAG, "Package " + pkg.packageName
7279                        + " was transferred to another, but its .apk remains");
7280            }
7281
7282            // Just create the setting, don't add it yet. For already existing packages
7283            // the PkgSetting exists already and doesn't have to be created.
7284            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7285                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7286                    pkg.applicationInfo.primaryCpuAbi,
7287                    pkg.applicationInfo.secondaryCpuAbi,
7288                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7289                    user, false);
7290            if (pkgSetting == null) {
7291                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7292                        "Creating application package " + pkg.packageName + " failed");
7293            }
7294
7295            if (pkgSetting.origPackage != null) {
7296                // If we are first transitioning from an original package,
7297                // fix up the new package's name now.  We need to do this after
7298                // looking up the package under its new name, so getPackageLP
7299                // can take care of fiddling things correctly.
7300                pkg.setPackageName(origPackage.name);
7301
7302                // File a report about this.
7303                String msg = "New package " + pkgSetting.realName
7304                        + " renamed to replace old package " + pkgSetting.name;
7305                reportSettingsProblem(Log.WARN, msg);
7306
7307                // Make a note of it.
7308                mTransferedPackages.add(origPackage.name);
7309
7310                // No longer need to retain this.
7311                pkgSetting.origPackage = null;
7312            }
7313
7314            if (realName != null) {
7315                // Make a note of it.
7316                mTransferedPackages.add(pkg.packageName);
7317            }
7318
7319            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7320                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7321            }
7322
7323            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7324                // Check all shared libraries and map to their actual file path.
7325                // We only do this here for apps not on a system dir, because those
7326                // are the only ones that can fail an install due to this.  We
7327                // will take care of the system apps by updating all of their
7328                // library paths after the scan is done.
7329                updateSharedLibrariesLPw(pkg, null);
7330            }
7331
7332            if (mFoundPolicyFile) {
7333                SELinuxMMAC.assignSeinfoValue(pkg);
7334            }
7335
7336            pkg.applicationInfo.uid = pkgSetting.appId;
7337            pkg.mExtras = pkgSetting;
7338            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7339                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7340                    // We just determined the app is signed correctly, so bring
7341                    // over the latest parsed certs.
7342                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7343                } else {
7344                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7345                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7346                                "Package " + pkg.packageName + " upgrade keys do not match the "
7347                                + "previously installed version");
7348                    } else {
7349                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7350                        String msg = "System package " + pkg.packageName
7351                            + " signature changed; retaining data.";
7352                        reportSettingsProblem(Log.WARN, msg);
7353                    }
7354                }
7355            } else {
7356                try {
7357                    verifySignaturesLP(pkgSetting, pkg);
7358                    // We just determined the app is signed correctly, so bring
7359                    // over the latest parsed certs.
7360                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7361                } catch (PackageManagerException e) {
7362                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7363                        throw e;
7364                    }
7365                    // The signature has changed, but this package is in the system
7366                    // image...  let's recover!
7367                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7368                    // However...  if this package is part of a shared user, but it
7369                    // doesn't match the signature of the shared user, let's fail.
7370                    // What this means is that you can't change the signatures
7371                    // associated with an overall shared user, which doesn't seem all
7372                    // that unreasonable.
7373                    if (pkgSetting.sharedUser != null) {
7374                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7375                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7376                            throw new PackageManagerException(
7377                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7378                                            "Signature mismatch for shared user: "
7379                                            + pkgSetting.sharedUser);
7380                        }
7381                    }
7382                    // File a report about this.
7383                    String msg = "System package " + pkg.packageName
7384                        + " signature changed; retaining data.";
7385                    reportSettingsProblem(Log.WARN, msg);
7386                }
7387            }
7388            // Verify that this new package doesn't have any content providers
7389            // that conflict with existing packages.  Only do this if the
7390            // package isn't already installed, since we don't want to break
7391            // things that are installed.
7392            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7393                final int N = pkg.providers.size();
7394                int i;
7395                for (i=0; i<N; i++) {
7396                    PackageParser.Provider p = pkg.providers.get(i);
7397                    if (p.info.authority != null) {
7398                        String names[] = p.info.authority.split(";");
7399                        for (int j = 0; j < names.length; j++) {
7400                            if (mProvidersByAuthority.containsKey(names[j])) {
7401                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7402                                final String otherPackageName =
7403                                        ((other != null && other.getComponentName() != null) ?
7404                                                other.getComponentName().getPackageName() : "?");
7405                                throw new PackageManagerException(
7406                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7407                                                "Can't install because provider name " + names[j]
7408                                                + " (in package " + pkg.applicationInfo.packageName
7409                                                + ") is already used by " + otherPackageName);
7410                            }
7411                        }
7412                    }
7413                }
7414            }
7415
7416            if (pkg.mAdoptPermissions != null) {
7417                // This package wants to adopt ownership of permissions from
7418                // another package.
7419                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7420                    final String origName = pkg.mAdoptPermissions.get(i);
7421                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7422                    if (orig != null) {
7423                        if (verifyPackageUpdateLPr(orig, pkg)) {
7424                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7425                                    + pkg.packageName);
7426                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7427                        }
7428                    }
7429                }
7430            }
7431        }
7432
7433        final String pkgName = pkg.packageName;
7434
7435        final long scanFileTime = scanFile.lastModified();
7436        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7437        pkg.applicationInfo.processName = fixProcessName(
7438                pkg.applicationInfo.packageName,
7439                pkg.applicationInfo.processName,
7440                pkg.applicationInfo.uid);
7441
7442        if (pkg != mPlatformPackage) {
7443            // Get all of our default paths setup
7444            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7445        }
7446
7447        final String path = scanFile.getPath();
7448        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7449
7450        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7451            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7452
7453            // Some system apps still use directory structure for native libraries
7454            // in which case we might end up not detecting abi solely based on apk
7455            // structure. Try to detect abi based on directory structure.
7456            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7457                    pkg.applicationInfo.primaryCpuAbi == null) {
7458                setBundledAppAbisAndRoots(pkg, pkgSetting);
7459                setNativeLibraryPaths(pkg);
7460            }
7461
7462        } else {
7463            if ((scanFlags & SCAN_MOVE) != 0) {
7464                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7465                // but we already have this packages package info in the PackageSetting. We just
7466                // use that and derive the native library path based on the new codepath.
7467                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7468                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7469            }
7470
7471            // Set native library paths again. For moves, the path will be updated based on the
7472            // ABIs we've determined above. For non-moves, the path will be updated based on the
7473            // ABIs we determined during compilation, but the path will depend on the final
7474            // package path (after the rename away from the stage path).
7475            setNativeLibraryPaths(pkg);
7476        }
7477
7478        // This is a special case for the "system" package, where the ABI is
7479        // dictated by the zygote configuration (and init.rc). We should keep track
7480        // of this ABI so that we can deal with "normal" applications that run under
7481        // the same UID correctly.
7482        if (mPlatformPackage == pkg) {
7483            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7484                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7485        }
7486
7487        // If there's a mismatch between the abi-override in the package setting
7488        // and the abiOverride specified for the install. Warn about this because we
7489        // would've already compiled the app without taking the package setting into
7490        // account.
7491        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7492            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7493                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7494                        " for package " + pkg.packageName);
7495            }
7496        }
7497
7498        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7499        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7500        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7501
7502        // Copy the derived override back to the parsed package, so that we can
7503        // update the package settings accordingly.
7504        pkg.cpuAbiOverride = cpuAbiOverride;
7505
7506        if (DEBUG_ABI_SELECTION) {
7507            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7508                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7509                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7510        }
7511
7512        // Push the derived path down into PackageSettings so we know what to
7513        // clean up at uninstall time.
7514        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7515
7516        if (DEBUG_ABI_SELECTION) {
7517            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7518                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7519                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7520        }
7521
7522        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7523            // We don't do this here during boot because we can do it all
7524            // at once after scanning all existing packages.
7525            //
7526            // We also do this *before* we perform dexopt on this package, so that
7527            // we can avoid redundant dexopts, and also to make sure we've got the
7528            // code and package path correct.
7529            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7530                    pkg, true /* boot complete */);
7531        }
7532
7533        if (mFactoryTest && pkg.requestedPermissions.contains(
7534                android.Manifest.permission.FACTORY_TEST)) {
7535            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7536        }
7537
7538        ArrayList<PackageParser.Package> clientLibPkgs = null;
7539
7540        // writer
7541        synchronized (mPackages) {
7542            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7543                // Only system apps can add new shared libraries.
7544                if (pkg.libraryNames != null) {
7545                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7546                        String name = pkg.libraryNames.get(i);
7547                        boolean allowed = false;
7548                        if (pkg.isUpdatedSystemApp()) {
7549                            // New library entries can only be added through the
7550                            // system image.  This is important to get rid of a lot
7551                            // of nasty edge cases: for example if we allowed a non-
7552                            // system update of the app to add a library, then uninstalling
7553                            // the update would make the library go away, and assumptions
7554                            // we made such as through app install filtering would now
7555                            // have allowed apps on the device which aren't compatible
7556                            // with it.  Better to just have the restriction here, be
7557                            // conservative, and create many fewer cases that can negatively
7558                            // impact the user experience.
7559                            final PackageSetting sysPs = mSettings
7560                                    .getDisabledSystemPkgLPr(pkg.packageName);
7561                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7562                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7563                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7564                                        allowed = true;
7565                                        break;
7566                                    }
7567                                }
7568                            }
7569                        } else {
7570                            allowed = true;
7571                        }
7572                        if (allowed) {
7573                            if (!mSharedLibraries.containsKey(name)) {
7574                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7575                            } else if (!name.equals(pkg.packageName)) {
7576                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7577                                        + name + " already exists; skipping");
7578                            }
7579                        } else {
7580                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7581                                    + name + " that is not declared on system image; skipping");
7582                        }
7583                    }
7584                    if ((scanFlags & SCAN_BOOTING) == 0) {
7585                        // If we are not booting, we need to update any applications
7586                        // that are clients of our shared library.  If we are booting,
7587                        // this will all be done once the scan is complete.
7588                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7589                    }
7590                }
7591            }
7592        }
7593
7594        // Request the ActivityManager to kill the process(only for existing packages)
7595        // so that we do not end up in a confused state while the user is still using the older
7596        // version of the application while the new one gets installed.
7597        if ((scanFlags & SCAN_REPLACING) != 0) {
7598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7599
7600            killApplication(pkg.applicationInfo.packageName,
7601                        pkg.applicationInfo.uid, "replace pkg");
7602
7603            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7604        }
7605
7606        // Also need to kill any apps that are dependent on the library.
7607        if (clientLibPkgs != null) {
7608            for (int i=0; i<clientLibPkgs.size(); i++) {
7609                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7610                killApplication(clientPkg.applicationInfo.packageName,
7611                        clientPkg.applicationInfo.uid, "update lib");
7612            }
7613        }
7614
7615        // Make sure we're not adding any bogus keyset info
7616        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7617        ksms.assertScannedPackageValid(pkg);
7618
7619        // writer
7620        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7621
7622        boolean createIdmapFailed = false;
7623        synchronized (mPackages) {
7624            // We don't expect installation to fail beyond this point
7625
7626            // Add the new setting to mSettings
7627            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7628            // Add the new setting to mPackages
7629            mPackages.put(pkg.applicationInfo.packageName, pkg);
7630            // Make sure we don't accidentally delete its data.
7631            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7632            while (iter.hasNext()) {
7633                PackageCleanItem item = iter.next();
7634                if (pkgName.equals(item.packageName)) {
7635                    iter.remove();
7636                }
7637            }
7638
7639            // Take care of first install / last update times.
7640            if (currentTime != 0) {
7641                if (pkgSetting.firstInstallTime == 0) {
7642                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7643                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7644                    pkgSetting.lastUpdateTime = currentTime;
7645                }
7646            } else if (pkgSetting.firstInstallTime == 0) {
7647                // We need *something*.  Take time time stamp of the file.
7648                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7649            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7650                if (scanFileTime != pkgSetting.timeStamp) {
7651                    // A package on the system image has changed; consider this
7652                    // to be an update.
7653                    pkgSetting.lastUpdateTime = scanFileTime;
7654                }
7655            }
7656
7657            // Add the package's KeySets to the global KeySetManagerService
7658            ksms.addScannedPackageLPw(pkg);
7659
7660            int N = pkg.providers.size();
7661            StringBuilder r = null;
7662            int i;
7663            for (i=0; i<N; i++) {
7664                PackageParser.Provider p = pkg.providers.get(i);
7665                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7666                        p.info.processName, pkg.applicationInfo.uid);
7667                mProviders.addProvider(p);
7668                p.syncable = p.info.isSyncable;
7669                if (p.info.authority != null) {
7670                    String names[] = p.info.authority.split(";");
7671                    p.info.authority = null;
7672                    for (int j = 0; j < names.length; j++) {
7673                        if (j == 1 && p.syncable) {
7674                            // We only want the first authority for a provider to possibly be
7675                            // syncable, so if we already added this provider using a different
7676                            // authority clear the syncable flag. We copy the provider before
7677                            // changing it because the mProviders object contains a reference
7678                            // to a provider that we don't want to change.
7679                            // Only do this for the second authority since the resulting provider
7680                            // object can be the same for all future authorities for this provider.
7681                            p = new PackageParser.Provider(p);
7682                            p.syncable = false;
7683                        }
7684                        if (!mProvidersByAuthority.containsKey(names[j])) {
7685                            mProvidersByAuthority.put(names[j], p);
7686                            if (p.info.authority == null) {
7687                                p.info.authority = names[j];
7688                            } else {
7689                                p.info.authority = p.info.authority + ";" + names[j];
7690                            }
7691                            if (DEBUG_PACKAGE_SCANNING) {
7692                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7693                                    Log.d(TAG, "Registered content provider: " + names[j]
7694                                            + ", className = " + p.info.name + ", isSyncable = "
7695                                            + p.info.isSyncable);
7696                            }
7697                        } else {
7698                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7699                            Slog.w(TAG, "Skipping provider name " + names[j] +
7700                                    " (in package " + pkg.applicationInfo.packageName +
7701                                    "): name already used by "
7702                                    + ((other != null && other.getComponentName() != null)
7703                                            ? other.getComponentName().getPackageName() : "?"));
7704                        }
7705                    }
7706                }
7707                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7708                    if (r == null) {
7709                        r = new StringBuilder(256);
7710                    } else {
7711                        r.append(' ');
7712                    }
7713                    r.append(p.info.name);
7714                }
7715            }
7716            if (r != null) {
7717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7718            }
7719
7720            N = pkg.services.size();
7721            r = null;
7722            for (i=0; i<N; i++) {
7723                PackageParser.Service s = pkg.services.get(i);
7724                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7725                        s.info.processName, pkg.applicationInfo.uid);
7726                mServices.addService(s);
7727                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7728                    if (r == null) {
7729                        r = new StringBuilder(256);
7730                    } else {
7731                        r.append(' ');
7732                    }
7733                    r.append(s.info.name);
7734                }
7735            }
7736            if (r != null) {
7737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7738            }
7739
7740            N = pkg.receivers.size();
7741            r = null;
7742            for (i=0; i<N; i++) {
7743                PackageParser.Activity a = pkg.receivers.get(i);
7744                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7745                        a.info.processName, pkg.applicationInfo.uid);
7746                mReceivers.addActivity(a, "receiver");
7747                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7748                    if (r == null) {
7749                        r = new StringBuilder(256);
7750                    } else {
7751                        r.append(' ');
7752                    }
7753                    r.append(a.info.name);
7754                }
7755            }
7756            if (r != null) {
7757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7758            }
7759
7760            N = pkg.activities.size();
7761            r = null;
7762            for (i=0; i<N; i++) {
7763                PackageParser.Activity a = pkg.activities.get(i);
7764                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7765                        a.info.processName, pkg.applicationInfo.uid);
7766                mActivities.addActivity(a, "activity");
7767                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7768                    if (r == null) {
7769                        r = new StringBuilder(256);
7770                    } else {
7771                        r.append(' ');
7772                    }
7773                    r.append(a.info.name);
7774                }
7775            }
7776            if (r != null) {
7777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7778            }
7779
7780            N = pkg.permissionGroups.size();
7781            r = null;
7782            for (i=0; i<N; i++) {
7783                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7784                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7785                if (cur == null) {
7786                    mPermissionGroups.put(pg.info.name, pg);
7787                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7788                        if (r == null) {
7789                            r = new StringBuilder(256);
7790                        } else {
7791                            r.append(' ');
7792                        }
7793                        r.append(pg.info.name);
7794                    }
7795                } else {
7796                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7797                            + pg.info.packageName + " ignored: original from "
7798                            + cur.info.packageName);
7799                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7800                        if (r == null) {
7801                            r = new StringBuilder(256);
7802                        } else {
7803                            r.append(' ');
7804                        }
7805                        r.append("DUP:");
7806                        r.append(pg.info.name);
7807                    }
7808                }
7809            }
7810            if (r != null) {
7811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7812            }
7813
7814            N = pkg.permissions.size();
7815            r = null;
7816            for (i=0; i<N; i++) {
7817                PackageParser.Permission p = pkg.permissions.get(i);
7818
7819                // Assume by default that we did not install this permission into the system.
7820                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7821
7822                // Now that permission groups have a special meaning, we ignore permission
7823                // groups for legacy apps to prevent unexpected behavior. In particular,
7824                // permissions for one app being granted to someone just becuase they happen
7825                // to be in a group defined by another app (before this had no implications).
7826                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7827                    p.group = mPermissionGroups.get(p.info.group);
7828                    // Warn for a permission in an unknown group.
7829                    if (p.info.group != null && p.group == null) {
7830                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7831                                + p.info.packageName + " in an unknown group " + p.info.group);
7832                    }
7833                }
7834
7835                ArrayMap<String, BasePermission> permissionMap =
7836                        p.tree ? mSettings.mPermissionTrees
7837                                : mSettings.mPermissions;
7838                BasePermission bp = permissionMap.get(p.info.name);
7839
7840                // Allow system apps to redefine non-system permissions
7841                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7842                    final boolean currentOwnerIsSystem = (bp.perm != null
7843                            && isSystemApp(bp.perm.owner));
7844                    if (isSystemApp(p.owner)) {
7845                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7846                            // It's a built-in permission and no owner, take ownership now
7847                            bp.packageSetting = pkgSetting;
7848                            bp.perm = p;
7849                            bp.uid = pkg.applicationInfo.uid;
7850                            bp.sourcePackage = p.info.packageName;
7851                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7852                        } else if (!currentOwnerIsSystem) {
7853                            String msg = "New decl " + p.owner + " of permission  "
7854                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7855                            reportSettingsProblem(Log.WARN, msg);
7856                            bp = null;
7857                        }
7858                    }
7859                }
7860
7861                if (bp == null) {
7862                    bp = new BasePermission(p.info.name, p.info.packageName,
7863                            BasePermission.TYPE_NORMAL);
7864                    permissionMap.put(p.info.name, bp);
7865                }
7866
7867                if (bp.perm == null) {
7868                    if (bp.sourcePackage == null
7869                            || bp.sourcePackage.equals(p.info.packageName)) {
7870                        BasePermission tree = findPermissionTreeLP(p.info.name);
7871                        if (tree == null
7872                                || tree.sourcePackage.equals(p.info.packageName)) {
7873                            bp.packageSetting = pkgSetting;
7874                            bp.perm = p;
7875                            bp.uid = pkg.applicationInfo.uid;
7876                            bp.sourcePackage = p.info.packageName;
7877                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7878                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7879                                if (r == null) {
7880                                    r = new StringBuilder(256);
7881                                } else {
7882                                    r.append(' ');
7883                                }
7884                                r.append(p.info.name);
7885                            }
7886                        } else {
7887                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7888                                    + p.info.packageName + " ignored: base tree "
7889                                    + tree.name + " is from package "
7890                                    + tree.sourcePackage);
7891                        }
7892                    } else {
7893                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7894                                + p.info.packageName + " ignored: original from "
7895                                + bp.sourcePackage);
7896                    }
7897                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7898                    if (r == null) {
7899                        r = new StringBuilder(256);
7900                    } else {
7901                        r.append(' ');
7902                    }
7903                    r.append("DUP:");
7904                    r.append(p.info.name);
7905                }
7906                if (bp.perm == p) {
7907                    bp.protectionLevel = p.info.protectionLevel;
7908                }
7909            }
7910
7911            if (r != null) {
7912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7913            }
7914
7915            N = pkg.instrumentation.size();
7916            r = null;
7917            for (i=0; i<N; i++) {
7918                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7919                a.info.packageName = pkg.applicationInfo.packageName;
7920                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7921                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7922                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7923                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7924                a.info.dataDir = pkg.applicationInfo.dataDir;
7925                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7926                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7927
7928                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7929                // need other information about the application, like the ABI and what not ?
7930                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7931                mInstrumentation.put(a.getComponentName(), a);
7932                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7933                    if (r == null) {
7934                        r = new StringBuilder(256);
7935                    } else {
7936                        r.append(' ');
7937                    }
7938                    r.append(a.info.name);
7939                }
7940            }
7941            if (r != null) {
7942                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7943            }
7944
7945            if (pkg.protectedBroadcasts != null) {
7946                N = pkg.protectedBroadcasts.size();
7947                for (i=0; i<N; i++) {
7948                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7949                }
7950            }
7951
7952            pkgSetting.setTimeStamp(scanFileTime);
7953
7954            // Create idmap files for pairs of (packages, overlay packages).
7955            // Note: "android", ie framework-res.apk, is handled by native layers.
7956            if (pkg.mOverlayTarget != null) {
7957                // This is an overlay package.
7958                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7959                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7960                        mOverlays.put(pkg.mOverlayTarget,
7961                                new ArrayMap<String, PackageParser.Package>());
7962                    }
7963                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7964                    map.put(pkg.packageName, pkg);
7965                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7966                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7967                        createIdmapFailed = true;
7968                    }
7969                }
7970            } else if (mOverlays.containsKey(pkg.packageName) &&
7971                    !pkg.packageName.equals("android")) {
7972                // This is a regular package, with one or more known overlay packages.
7973                createIdmapsForPackageLI(pkg);
7974            }
7975        }
7976
7977        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7978
7979        if (createIdmapFailed) {
7980            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7981                    "scanPackageLI failed to createIdmap");
7982        }
7983        return pkg;
7984    }
7985
7986    /**
7987     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7988     * is derived purely on the basis of the contents of {@code scanFile} and
7989     * {@code cpuAbiOverride}.
7990     *
7991     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7992     */
7993    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7994                                 String cpuAbiOverride, boolean extractLibs)
7995            throws PackageManagerException {
7996        // TODO: We can probably be smarter about this stuff. For installed apps,
7997        // we can calculate this information at install time once and for all. For
7998        // system apps, we can probably assume that this information doesn't change
7999        // after the first boot scan. As things stand, we do lots of unnecessary work.
8000
8001        // Give ourselves some initial paths; we'll come back for another
8002        // pass once we've determined ABI below.
8003        setNativeLibraryPaths(pkg);
8004
8005        // We would never need to extract libs for forward-locked and external packages,
8006        // since the container service will do it for us. We shouldn't attempt to
8007        // extract libs from system app when it was not updated.
8008        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8009                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8010            extractLibs = false;
8011        }
8012
8013        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8014        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8015
8016        NativeLibraryHelper.Handle handle = null;
8017        try {
8018            handle = NativeLibraryHelper.Handle.create(pkg);
8019            // TODO(multiArch): This can be null for apps that didn't go through the
8020            // usual installation process. We can calculate it again, like we
8021            // do during install time.
8022            //
8023            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8024            // unnecessary.
8025            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8026
8027            // Null out the abis so that they can be recalculated.
8028            pkg.applicationInfo.primaryCpuAbi = null;
8029            pkg.applicationInfo.secondaryCpuAbi = null;
8030            if (isMultiArch(pkg.applicationInfo)) {
8031                // Warn if we've set an abiOverride for multi-lib packages..
8032                // By definition, we need to copy both 32 and 64 bit libraries for
8033                // such packages.
8034                if (pkg.cpuAbiOverride != null
8035                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8036                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8037                }
8038
8039                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8040                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8041                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8042                    if (extractLibs) {
8043                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8044                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8045                                useIsaSpecificSubdirs);
8046                    } else {
8047                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8048                    }
8049                }
8050
8051                maybeThrowExceptionForMultiArchCopy(
8052                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8053
8054                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8055                    if (extractLibs) {
8056                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8057                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8058                                useIsaSpecificSubdirs);
8059                    } else {
8060                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8061                    }
8062                }
8063
8064                maybeThrowExceptionForMultiArchCopy(
8065                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8066
8067                if (abi64 >= 0) {
8068                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8069                }
8070
8071                if (abi32 >= 0) {
8072                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8073                    if (abi64 >= 0) {
8074                        pkg.applicationInfo.secondaryCpuAbi = abi;
8075                    } else {
8076                        pkg.applicationInfo.primaryCpuAbi = abi;
8077                    }
8078                }
8079                if (cpuAbiOverride != null &&
8080                        cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) {
8081                    pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8082                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8083                }
8084            } else {
8085                String[] abiList = (cpuAbiOverride != null) ?
8086                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8087
8088                // Enable gross and lame hacks for apps that are built with old
8089                // SDK tools. We must scan their APKs for renderscript bitcode and
8090                // not launch them if it's present. Don't bother checking on devices
8091                // that don't have 64 bit support.
8092                boolean needsRenderScriptOverride = false;
8093                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8094                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8095                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8096                    needsRenderScriptOverride = true;
8097                }
8098
8099                final int copyRet;
8100                if (extractLibs) {
8101                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8102                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8103                } else {
8104                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8105                }
8106
8107                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8108                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8109                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8110                }
8111
8112                if (copyRet >= 0) {
8113                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8114                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8115                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8116                } else if (needsRenderScriptOverride) {
8117                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8118                }
8119            }
8120        } catch (IOException ioe) {
8121            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8122        } finally {
8123            IoUtils.closeQuietly(handle);
8124        }
8125
8126        // Now that we've calculated the ABIs and determined if it's an internal app,
8127        // we will go ahead and populate the nativeLibraryPath.
8128        setNativeLibraryPaths(pkg);
8129    }
8130
8131    /**
8132     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8133     * i.e, so that all packages can be run inside a single process if required.
8134     *
8135     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8136     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8137     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8138     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8139     * updating a package that belongs to a shared user.
8140     *
8141     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8142     * adds unnecessary complexity.
8143     */
8144    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8145            PackageParser.Package scannedPackage, boolean bootComplete) {
8146        String requiredInstructionSet = null;
8147        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8148            requiredInstructionSet = VMRuntime.getInstructionSet(
8149                     scannedPackage.applicationInfo.primaryCpuAbi);
8150        }
8151
8152        PackageSetting requirer = null;
8153        for (PackageSetting ps : packagesForUser) {
8154            // If packagesForUser contains scannedPackage, we skip it. This will happen
8155            // when scannedPackage is an update of an existing package. Without this check,
8156            // we will never be able to change the ABI of any package belonging to a shared
8157            // user, even if it's compatible with other packages.
8158            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8159                if (ps.primaryCpuAbiString == null) {
8160                    continue;
8161                }
8162
8163                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8164                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8165                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8166                    // this but there's not much we can do.
8167                    String errorMessage = "Instruction set mismatch, "
8168                            + ((requirer == null) ? "[caller]" : requirer)
8169                            + " requires " + requiredInstructionSet + " whereas " + ps
8170                            + " requires " + instructionSet;
8171                    Slog.w(TAG, errorMessage);
8172                }
8173
8174                if (requiredInstructionSet == null) {
8175                    requiredInstructionSet = instructionSet;
8176                    requirer = ps;
8177                }
8178            }
8179        }
8180
8181        if (requiredInstructionSet != null) {
8182            String adjustedAbi;
8183            if (requirer != null) {
8184                // requirer != null implies that either scannedPackage was null or that scannedPackage
8185                // did not require an ABI, in which case we have to adjust scannedPackage to match
8186                // the ABI of the set (which is the same as requirer's ABI)
8187                adjustedAbi = requirer.primaryCpuAbiString;
8188                if (scannedPackage != null) {
8189                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8190                }
8191            } else {
8192                // requirer == null implies that we're updating all ABIs in the set to
8193                // match scannedPackage.
8194                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8195            }
8196
8197            for (PackageSetting ps : packagesForUser) {
8198                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8199                    if (ps.primaryCpuAbiString != null) {
8200                        continue;
8201                    }
8202
8203                    ps.primaryCpuAbiString = adjustedAbi;
8204                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8205                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8206                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8207                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8208                                + " (requirer="
8209                                + (requirer == null ? "null" : requirer.pkg.packageName)
8210                                + ", scannedPackage="
8211                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8212                                + ")");
8213                        try {
8214                            mInstaller.rmdex(ps.codePathString,
8215                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8216                        } catch (InstallerException ignored) {
8217                        }
8218                    }
8219                }
8220            }
8221        }
8222    }
8223
8224    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8225        synchronized (mPackages) {
8226            mResolverReplaced = true;
8227            // Set up information for custom user intent resolution activity.
8228            mResolveActivity.applicationInfo = pkg.applicationInfo;
8229            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8230            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8231            mResolveActivity.processName = pkg.applicationInfo.packageName;
8232            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8233            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8234                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8235            mResolveActivity.theme = 0;
8236            mResolveActivity.exported = true;
8237            mResolveActivity.enabled = true;
8238            mResolveInfo.activityInfo = mResolveActivity;
8239            mResolveInfo.priority = 0;
8240            mResolveInfo.preferredOrder = 0;
8241            mResolveInfo.match = 0;
8242            mResolveComponentName = mCustomResolverComponentName;
8243            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8244                    mResolveComponentName);
8245        }
8246    }
8247
8248    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8249        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8250
8251        // Set up information for ephemeral installer activity
8252        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8253        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8254        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8255        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8256        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8257        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8258                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8259        mEphemeralInstallerActivity.theme = 0;
8260        mEphemeralInstallerActivity.exported = true;
8261        mEphemeralInstallerActivity.enabled = true;
8262        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8263        mEphemeralInstallerInfo.priority = 0;
8264        mEphemeralInstallerInfo.preferredOrder = 0;
8265        mEphemeralInstallerInfo.match = 0;
8266
8267        if (DEBUG_EPHEMERAL) {
8268            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8269        }
8270    }
8271
8272    private static String calculateBundledApkRoot(final String codePathString) {
8273        final File codePath = new File(codePathString);
8274        final File codeRoot;
8275        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8276            codeRoot = Environment.getRootDirectory();
8277        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8278            codeRoot = Environment.getOemDirectory();
8279        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8280            codeRoot = Environment.getVendorDirectory();
8281        } else {
8282            // Unrecognized code path; take its top real segment as the apk root:
8283            // e.g. /something/app/blah.apk => /something
8284            try {
8285                File f = codePath.getCanonicalFile();
8286                File parent = f.getParentFile();    // non-null because codePath is a file
8287                File tmp;
8288                while ((tmp = parent.getParentFile()) != null) {
8289                    f = parent;
8290                    parent = tmp;
8291                }
8292                codeRoot = f;
8293                Slog.w(TAG, "Unrecognized code path "
8294                        + codePath + " - using " + codeRoot);
8295            } catch (IOException e) {
8296                // Can't canonicalize the code path -- shenanigans?
8297                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8298                return Environment.getRootDirectory().getPath();
8299            }
8300        }
8301        return codeRoot.getPath();
8302    }
8303
8304    /**
8305     * Derive and set the location of native libraries for the given package,
8306     * which varies depending on where and how the package was installed.
8307     */
8308    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8309        final ApplicationInfo info = pkg.applicationInfo;
8310        final String codePath = pkg.codePath;
8311        final File codeFile = new File(codePath);
8312        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8313        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8314
8315        info.nativeLibraryRootDir = null;
8316        info.nativeLibraryRootRequiresIsa = false;
8317        info.nativeLibraryDir = null;
8318        info.secondaryNativeLibraryDir = null;
8319
8320        if (isApkFile(codeFile)) {
8321            // Monolithic install
8322            if (bundledApp) {
8323                // If "/system/lib64/apkname" exists, assume that is the per-package
8324                // native library directory to use; otherwise use "/system/lib/apkname".
8325                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8326                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8327                        getPrimaryInstructionSet(info));
8328
8329                // This is a bundled system app so choose the path based on the ABI.
8330                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8331                // is just the default path.
8332                final String apkName = deriveCodePathName(codePath);
8333                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8334                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8335                        apkName).getAbsolutePath();
8336
8337                if (info.secondaryCpuAbi != null) {
8338                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8339                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8340                            secondaryLibDir, apkName).getAbsolutePath();
8341                }
8342            } else if (asecApp) {
8343                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8344                        .getAbsolutePath();
8345            } else {
8346                final String apkName = deriveCodePathName(codePath);
8347                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8348                        .getAbsolutePath();
8349            }
8350
8351            info.nativeLibraryRootRequiresIsa = false;
8352            info.nativeLibraryDir = info.nativeLibraryRootDir;
8353        } else {
8354            // Cluster install
8355            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8356            info.nativeLibraryRootRequiresIsa = true;
8357
8358            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8359                    getPrimaryInstructionSet(info)).getAbsolutePath();
8360
8361            if (info.secondaryCpuAbi != null) {
8362                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8363                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8364            }
8365        }
8366    }
8367
8368    /**
8369     * Calculate the abis and roots for a bundled app. These can uniquely
8370     * be determined from the contents of the system partition, i.e whether
8371     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8372     * of this information, and instead assume that the system was built
8373     * sensibly.
8374     */
8375    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8376                                           PackageSetting pkgSetting) {
8377        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8378
8379        // If "/system/lib64/apkname" exists, assume that is the per-package
8380        // native library directory to use; otherwise use "/system/lib/apkname".
8381        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8382        setBundledAppAbi(pkg, apkRoot, apkName);
8383        // pkgSetting might be null during rescan following uninstall of updates
8384        // to a bundled app, so accommodate that possibility.  The settings in
8385        // that case will be established later from the parsed package.
8386        //
8387        // If the settings aren't null, sync them up with what we've just derived.
8388        // note that apkRoot isn't stored in the package settings.
8389        if (pkgSetting != null) {
8390            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8391            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8392        }
8393    }
8394
8395    /**
8396     * Deduces the ABI of a bundled app and sets the relevant fields on the
8397     * parsed pkg object.
8398     *
8399     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8400     *        under which system libraries are installed.
8401     * @param apkName the name of the installed package.
8402     */
8403    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8404        final File codeFile = new File(pkg.codePath);
8405
8406        final boolean has64BitLibs;
8407        final boolean has32BitLibs;
8408        if (isApkFile(codeFile)) {
8409            // Monolithic install
8410            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8411            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8412        } else {
8413            // Cluster install
8414            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8415            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8416                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8417                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8418                has64BitLibs = (new File(rootDir, isa)).exists();
8419            } else {
8420                has64BitLibs = false;
8421            }
8422            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8423                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8424                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8425                has32BitLibs = (new File(rootDir, isa)).exists();
8426            } else {
8427                has32BitLibs = false;
8428            }
8429        }
8430
8431        if (has64BitLibs && !has32BitLibs) {
8432            // The package has 64 bit libs, but not 32 bit libs. Its primary
8433            // ABI should be 64 bit. We can safely assume here that the bundled
8434            // native libraries correspond to the most preferred ABI in the list.
8435
8436            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8437            pkg.applicationInfo.secondaryCpuAbi = null;
8438        } else if (has32BitLibs && !has64BitLibs) {
8439            // The package has 32 bit libs but not 64 bit libs. Its primary
8440            // ABI should be 32 bit.
8441
8442            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8443            pkg.applicationInfo.secondaryCpuAbi = null;
8444        } else if (has32BitLibs && has64BitLibs) {
8445            // The application has both 64 and 32 bit bundled libraries. We check
8446            // here that the app declares multiArch support, and warn if it doesn't.
8447            //
8448            // We will be lenient here and record both ABIs. The primary will be the
8449            // ABI that's higher on the list, i.e, a device that's configured to prefer
8450            // 64 bit apps will see a 64 bit primary ABI,
8451
8452            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8453                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8454            }
8455
8456            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8457                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8458                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8459            } else {
8460                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8461                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8462            }
8463        } else {
8464            pkg.applicationInfo.primaryCpuAbi = null;
8465            pkg.applicationInfo.secondaryCpuAbi = null;
8466        }
8467    }
8468
8469    private void killApplication(String pkgName, int appId, String reason) {
8470        // Request the ActivityManager to kill the process(only for existing packages)
8471        // so that we do not end up in a confused state while the user is still using the older
8472        // version of the application while the new one gets installed.
8473        IActivityManager am = ActivityManagerNative.getDefault();
8474        if (am != null) {
8475            try {
8476                am.killApplicationWithAppId(pkgName, appId, reason);
8477            } catch (RemoteException e) {
8478            }
8479        }
8480    }
8481
8482    void removePackageLI(PackageSetting ps, boolean chatty) {
8483        if (DEBUG_INSTALL) {
8484            if (chatty)
8485                Log.d(TAG, "Removing package " + ps.name);
8486        }
8487
8488        // writer
8489        synchronized (mPackages) {
8490            mPackages.remove(ps.name);
8491            final PackageParser.Package pkg = ps.pkg;
8492            if (pkg != null) {
8493                cleanPackageDataStructuresLILPw(pkg, chatty);
8494            }
8495        }
8496    }
8497
8498    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8499        if (DEBUG_INSTALL) {
8500            if (chatty)
8501                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8502        }
8503
8504        // writer
8505        synchronized (mPackages) {
8506            mPackages.remove(pkg.applicationInfo.packageName);
8507            cleanPackageDataStructuresLILPw(pkg, chatty);
8508        }
8509    }
8510
8511    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8512        int N = pkg.providers.size();
8513        StringBuilder r = null;
8514        int i;
8515        for (i=0; i<N; i++) {
8516            PackageParser.Provider p = pkg.providers.get(i);
8517            mProviders.removeProvider(p);
8518            if (p.info.authority == null) {
8519
8520                /* There was another ContentProvider with this authority when
8521                 * this app was installed so this authority is null,
8522                 * Ignore it as we don't have to unregister the provider.
8523                 */
8524                continue;
8525            }
8526            String names[] = p.info.authority.split(";");
8527            for (int j = 0; j < names.length; j++) {
8528                if (mProvidersByAuthority.get(names[j]) == p) {
8529                    mProvidersByAuthority.remove(names[j]);
8530                    if (DEBUG_REMOVE) {
8531                        if (chatty)
8532                            Log.d(TAG, "Unregistered content provider: " + names[j]
8533                                    + ", className = " + p.info.name + ", isSyncable = "
8534                                    + p.info.isSyncable);
8535                    }
8536                }
8537            }
8538            if (DEBUG_REMOVE && chatty) {
8539                if (r == null) {
8540                    r = new StringBuilder(256);
8541                } else {
8542                    r.append(' ');
8543                }
8544                r.append(p.info.name);
8545            }
8546        }
8547        if (r != null) {
8548            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8549        }
8550
8551        N = pkg.services.size();
8552        r = null;
8553        for (i=0; i<N; i++) {
8554            PackageParser.Service s = pkg.services.get(i);
8555            mServices.removeService(s);
8556            if (chatty) {
8557                if (r == null) {
8558                    r = new StringBuilder(256);
8559                } else {
8560                    r.append(' ');
8561                }
8562                r.append(s.info.name);
8563            }
8564        }
8565        if (r != null) {
8566            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8567        }
8568
8569        N = pkg.receivers.size();
8570        r = null;
8571        for (i=0; i<N; i++) {
8572            PackageParser.Activity a = pkg.receivers.get(i);
8573            mReceivers.removeActivity(a, "receiver");
8574            if (DEBUG_REMOVE && chatty) {
8575                if (r == null) {
8576                    r = new StringBuilder(256);
8577                } else {
8578                    r.append(' ');
8579                }
8580                r.append(a.info.name);
8581            }
8582        }
8583        if (r != null) {
8584            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8585        }
8586
8587        N = pkg.activities.size();
8588        r = null;
8589        for (i=0; i<N; i++) {
8590            PackageParser.Activity a = pkg.activities.get(i);
8591            mActivities.removeActivity(a, "activity");
8592            if (DEBUG_REMOVE && chatty) {
8593                if (r == null) {
8594                    r = new StringBuilder(256);
8595                } else {
8596                    r.append(' ');
8597                }
8598                r.append(a.info.name);
8599            }
8600        }
8601        if (r != null) {
8602            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8603        }
8604
8605        N = pkg.permissions.size();
8606        r = null;
8607        for (i=0; i<N; i++) {
8608            PackageParser.Permission p = pkg.permissions.get(i);
8609            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8610            if (bp == null) {
8611                bp = mSettings.mPermissionTrees.get(p.info.name);
8612            }
8613            if (bp != null && bp.perm == p) {
8614                bp.perm = null;
8615                if (DEBUG_REMOVE && chatty) {
8616                    if (r == null) {
8617                        r = new StringBuilder(256);
8618                    } else {
8619                        r.append(' ');
8620                    }
8621                    r.append(p.info.name);
8622                }
8623            }
8624            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8625                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8626                if (appOpPkgs != null) {
8627                    appOpPkgs.remove(pkg.packageName);
8628                }
8629            }
8630        }
8631        if (r != null) {
8632            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8633        }
8634
8635        N = pkg.requestedPermissions.size();
8636        r = null;
8637        for (i=0; i<N; i++) {
8638            String perm = pkg.requestedPermissions.get(i);
8639            BasePermission bp = mSettings.mPermissions.get(perm);
8640            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8641                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8642                if (appOpPkgs != null) {
8643                    appOpPkgs.remove(pkg.packageName);
8644                    if (appOpPkgs.isEmpty()) {
8645                        mAppOpPermissionPackages.remove(perm);
8646                    }
8647                }
8648            }
8649        }
8650        if (r != null) {
8651            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8652        }
8653
8654        N = pkg.instrumentation.size();
8655        r = null;
8656        for (i=0; i<N; i++) {
8657            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8658            mInstrumentation.remove(a.getComponentName());
8659            if (DEBUG_REMOVE && chatty) {
8660                if (r == null) {
8661                    r = new StringBuilder(256);
8662                } else {
8663                    r.append(' ');
8664                }
8665                r.append(a.info.name);
8666            }
8667        }
8668        if (r != null) {
8669            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8670        }
8671
8672        r = null;
8673        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8674            // Only system apps can hold shared libraries.
8675            if (pkg.libraryNames != null) {
8676                for (i=0; i<pkg.libraryNames.size(); i++) {
8677                    String name = pkg.libraryNames.get(i);
8678                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8679                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8680                        mSharedLibraries.remove(name);
8681                        if (DEBUG_REMOVE && chatty) {
8682                            if (r == null) {
8683                                r = new StringBuilder(256);
8684                            } else {
8685                                r.append(' ');
8686                            }
8687                            r.append(name);
8688                        }
8689                    }
8690                }
8691            }
8692        }
8693        if (r != null) {
8694            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8695        }
8696    }
8697
8698    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8699        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8700            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8701                return true;
8702            }
8703        }
8704        return false;
8705    }
8706
8707    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8708    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8709    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8710
8711    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8712            int flags) {
8713        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8714        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8715    }
8716
8717    private void updatePermissionsLPw(String changingPkg,
8718            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8719        // Make sure there are no dangling permission trees.
8720        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8721        while (it.hasNext()) {
8722            final BasePermission bp = it.next();
8723            if (bp.packageSetting == null) {
8724                // We may not yet have parsed the package, so just see if
8725                // we still know about its settings.
8726                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8727            }
8728            if (bp.packageSetting == null) {
8729                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8730                        + " from package " + bp.sourcePackage);
8731                it.remove();
8732            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8733                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8734                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8735                            + " from package " + bp.sourcePackage);
8736                    flags |= UPDATE_PERMISSIONS_ALL;
8737                    it.remove();
8738                }
8739            }
8740        }
8741
8742        // Make sure all dynamic permissions have been assigned to a package,
8743        // and make sure there are no dangling permissions.
8744        it = mSettings.mPermissions.values().iterator();
8745        while (it.hasNext()) {
8746            final BasePermission bp = it.next();
8747            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8748                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8749                        + bp.name + " pkg=" + bp.sourcePackage
8750                        + " info=" + bp.pendingInfo);
8751                if (bp.packageSetting == null && bp.pendingInfo != null) {
8752                    final BasePermission tree = findPermissionTreeLP(bp.name);
8753                    if (tree != null && tree.perm != null) {
8754                        bp.packageSetting = tree.packageSetting;
8755                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8756                                new PermissionInfo(bp.pendingInfo));
8757                        bp.perm.info.packageName = tree.perm.info.packageName;
8758                        bp.perm.info.name = bp.name;
8759                        bp.uid = tree.uid;
8760                    }
8761                }
8762            }
8763            if (bp.packageSetting == null) {
8764                // We may not yet have parsed the package, so just see if
8765                // we still know about its settings.
8766                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8767            }
8768            if (bp.packageSetting == null) {
8769                Slog.w(TAG, "Removing dangling permission: " + bp.name
8770                        + " from package " + bp.sourcePackage);
8771                it.remove();
8772            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8773                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8774                    Slog.i(TAG, "Removing old permission: " + bp.name
8775                            + " from package " + bp.sourcePackage);
8776                    flags |= UPDATE_PERMISSIONS_ALL;
8777                    it.remove();
8778                }
8779            }
8780        }
8781
8782        // Now update the permissions for all packages, in particular
8783        // replace the granted permissions of the system packages.
8784        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8785            for (PackageParser.Package pkg : mPackages.values()) {
8786                if (pkg != pkgInfo) {
8787                    // Only replace for packages on requested volume
8788                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8789                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8790                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8791                    grantPermissionsLPw(pkg, replace, changingPkg);
8792                }
8793            }
8794        }
8795
8796        if (pkgInfo != null) {
8797            // Only replace for packages on requested volume
8798            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8799            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8800                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8801            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8802        }
8803    }
8804
8805    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8806            String packageOfInterest) {
8807        // IMPORTANT: There are two types of permissions: install and runtime.
8808        // Install time permissions are granted when the app is installed to
8809        // all device users and users added in the future. Runtime permissions
8810        // are granted at runtime explicitly to specific users. Normal and signature
8811        // protected permissions are install time permissions. Dangerous permissions
8812        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8813        // otherwise they are runtime permissions. This function does not manage
8814        // runtime permissions except for the case an app targeting Lollipop MR1
8815        // being upgraded to target a newer SDK, in which case dangerous permissions
8816        // are transformed from install time to runtime ones.
8817
8818        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8819        if (ps == null) {
8820            return;
8821        }
8822
8823        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8824
8825        PermissionsState permissionsState = ps.getPermissionsState();
8826        PermissionsState origPermissions = permissionsState;
8827
8828        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8829
8830        boolean runtimePermissionsRevoked = false;
8831        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8832
8833        boolean changedInstallPermission = false;
8834
8835        if (replace) {
8836            ps.installPermissionsFixed = false;
8837            if (!ps.isSharedUser()) {
8838                origPermissions = new PermissionsState(permissionsState);
8839                permissionsState.reset();
8840            } else {
8841                // We need to know only about runtime permission changes since the
8842                // calling code always writes the install permissions state but
8843                // the runtime ones are written only if changed. The only cases of
8844                // changed runtime permissions here are promotion of an install to
8845                // runtime and revocation of a runtime from a shared user.
8846                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8847                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8848                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8849                    runtimePermissionsRevoked = true;
8850                }
8851            }
8852        }
8853
8854        permissionsState.setGlobalGids(mGlobalGids);
8855
8856        final int N = pkg.requestedPermissions.size();
8857        for (int i=0; i<N; i++) {
8858            final String name = pkg.requestedPermissions.get(i);
8859            final BasePermission bp = mSettings.mPermissions.get(name);
8860
8861            if (DEBUG_INSTALL) {
8862                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8863            }
8864
8865            if (bp == null || bp.packageSetting == null) {
8866                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8867                    Slog.w(TAG, "Unknown permission " + name
8868                            + " in package " + pkg.packageName);
8869                }
8870                continue;
8871            }
8872
8873            final String perm = bp.name;
8874            boolean allowedSig = false;
8875            int grant = GRANT_DENIED;
8876
8877            // Keep track of app op permissions.
8878            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8879                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8880                if (pkgs == null) {
8881                    pkgs = new ArraySet<>();
8882                    mAppOpPermissionPackages.put(bp.name, pkgs);
8883                }
8884                pkgs.add(pkg.packageName);
8885            }
8886
8887            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8888            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8889                    >= Build.VERSION_CODES.M;
8890            switch (level) {
8891                case PermissionInfo.PROTECTION_NORMAL: {
8892                    // For all apps normal permissions are install time ones.
8893                    grant = GRANT_INSTALL;
8894                } break;
8895
8896                case PermissionInfo.PROTECTION_DANGEROUS: {
8897                    // If a permission review is required for legacy apps we represent
8898                    // their permissions as always granted runtime ones since we need
8899                    // to keep the review required permission flag per user while an
8900                    // install permission's state is shared across all users.
8901                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8902                        // For legacy apps dangerous permissions are install time ones.
8903                        grant = GRANT_INSTALL;
8904                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8905                        // For legacy apps that became modern, install becomes runtime.
8906                        grant = GRANT_UPGRADE;
8907                    } else if (mPromoteSystemApps
8908                            && isSystemApp(ps)
8909                            && mExistingSystemPackages.contains(ps.name)) {
8910                        // For legacy system apps, install becomes runtime.
8911                        // We cannot check hasInstallPermission() for system apps since those
8912                        // permissions were granted implicitly and not persisted pre-M.
8913                        grant = GRANT_UPGRADE;
8914                    } else {
8915                        // For modern apps keep runtime permissions unchanged.
8916                        grant = GRANT_RUNTIME;
8917                    }
8918                } break;
8919
8920                case PermissionInfo.PROTECTION_SIGNATURE: {
8921                    // For all apps signature permissions are install time ones.
8922                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8923                    if (allowedSig) {
8924                        grant = GRANT_INSTALL;
8925                    }
8926                } break;
8927            }
8928
8929            if (DEBUG_INSTALL) {
8930                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8931            }
8932
8933            if (grant != GRANT_DENIED) {
8934                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8935                    // If this is an existing, non-system package, then
8936                    // we can't add any new permissions to it.
8937                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8938                        // Except...  if this is a permission that was added
8939                        // to the platform (note: need to only do this when
8940                        // updating the platform).
8941                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8942                            grant = GRANT_DENIED;
8943                        }
8944                    }
8945                }
8946
8947                switch (grant) {
8948                    case GRANT_INSTALL: {
8949                        // Revoke this as runtime permission to handle the case of
8950                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8951                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8952                            if (origPermissions.getRuntimePermissionState(
8953                                    bp.name, userId) != null) {
8954                                // Revoke the runtime permission and clear the flags.
8955                                origPermissions.revokeRuntimePermission(bp, userId);
8956                                origPermissions.updatePermissionFlags(bp, userId,
8957                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8958                                // If we revoked a permission permission, we have to write.
8959                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8960                                        changedRuntimePermissionUserIds, userId);
8961                            }
8962                        }
8963                        // Grant an install permission.
8964                        if (permissionsState.grantInstallPermission(bp) !=
8965                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8966                            changedInstallPermission = true;
8967                        }
8968                    } break;
8969
8970                    case GRANT_RUNTIME: {
8971                        // Grant previously granted runtime permissions.
8972                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8973                            PermissionState permissionState = origPermissions
8974                                    .getRuntimePermissionState(bp.name, userId);
8975                            int flags = permissionState != null
8976                                    ? permissionState.getFlags() : 0;
8977                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8978                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8979                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8980                                    // If we cannot put the permission as it was, we have to write.
8981                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8982                                            changedRuntimePermissionUserIds, userId);
8983                                }
8984                                // If the app supports runtime permissions no need for a review.
8985                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8986                                        && appSupportsRuntimePermissions
8987                                        && (flags & PackageManager
8988                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8989                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8990                                    // Since we changed the flags, we have to write.
8991                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8992                                            changedRuntimePermissionUserIds, userId);
8993                                }
8994                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8995                                    && !appSupportsRuntimePermissions) {
8996                                // For legacy apps that need a permission review, every new
8997                                // runtime permission is granted but it is pending a review.
8998                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8999                                    permissionsState.grantRuntimePermission(bp, userId);
9000                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9001                                    // We changed the permission and flags, hence have to write.
9002                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9003                                            changedRuntimePermissionUserIds, userId);
9004                                }
9005                            }
9006                            // Propagate the permission flags.
9007                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9008                        }
9009                    } break;
9010
9011                    case GRANT_UPGRADE: {
9012                        // Grant runtime permissions for a previously held install permission.
9013                        PermissionState permissionState = origPermissions
9014                                .getInstallPermissionState(bp.name);
9015                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9016
9017                        if (origPermissions.revokeInstallPermission(bp)
9018                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9019                            // We will be transferring the permission flags, so clear them.
9020                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9021                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9022                            changedInstallPermission = true;
9023                        }
9024
9025                        // If the permission is not to be promoted to runtime we ignore it and
9026                        // also its other flags as they are not applicable to install permissions.
9027                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9028                            for (int userId : currentUserIds) {
9029                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9030                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9031                                    // Transfer the permission flags.
9032                                    permissionsState.updatePermissionFlags(bp, userId,
9033                                            flags, flags);
9034                                    // If we granted the permission, we have to write.
9035                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9036                                            changedRuntimePermissionUserIds, userId);
9037                                }
9038                            }
9039                        }
9040                    } break;
9041
9042                    default: {
9043                        if (packageOfInterest == null
9044                                || packageOfInterest.equals(pkg.packageName)) {
9045                            Slog.w(TAG, "Not granting permission " + perm
9046                                    + " to package " + pkg.packageName
9047                                    + " because it was previously installed without");
9048                        }
9049                    } break;
9050                }
9051            } else {
9052                if (permissionsState.revokeInstallPermission(bp) !=
9053                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9054                    // Also drop the permission flags.
9055                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9056                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9057                    changedInstallPermission = true;
9058                    Slog.i(TAG, "Un-granting permission " + perm
9059                            + " from package " + pkg.packageName
9060                            + " (protectionLevel=" + bp.protectionLevel
9061                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9062                            + ")");
9063                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9064                    // Don't print warning for app op permissions, since it is fine for them
9065                    // not to be granted, there is a UI for the user to decide.
9066                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9067                        Slog.w(TAG, "Not granting permission " + perm
9068                                + " to package " + pkg.packageName
9069                                + " (protectionLevel=" + bp.protectionLevel
9070                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9071                                + ")");
9072                    }
9073                }
9074            }
9075        }
9076
9077        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9078                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9079            // This is the first that we have heard about this package, so the
9080            // permissions we have now selected are fixed until explicitly
9081            // changed.
9082            ps.installPermissionsFixed = true;
9083        }
9084
9085        // Persist the runtime permissions state for users with changes. If permissions
9086        // were revoked because no app in the shared user declares them we have to
9087        // write synchronously to avoid losing runtime permissions state.
9088        for (int userId : changedRuntimePermissionUserIds) {
9089            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9090        }
9091
9092        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9093    }
9094
9095    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9096        boolean allowed = false;
9097        final int NP = PackageParser.NEW_PERMISSIONS.length;
9098        for (int ip=0; ip<NP; ip++) {
9099            final PackageParser.NewPermissionInfo npi
9100                    = PackageParser.NEW_PERMISSIONS[ip];
9101            if (npi.name.equals(perm)
9102                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9103                allowed = true;
9104                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9105                        + pkg.packageName);
9106                break;
9107            }
9108        }
9109        return allowed;
9110    }
9111
9112    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9113            BasePermission bp, PermissionsState origPermissions) {
9114        boolean allowed;
9115        allowed = (compareSignatures(
9116                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9117                        == PackageManager.SIGNATURE_MATCH)
9118                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9119                        == PackageManager.SIGNATURE_MATCH);
9120        if (!allowed && (bp.protectionLevel
9121                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9122            if (isSystemApp(pkg)) {
9123                // For updated system applications, a system permission
9124                // is granted only if it had been defined by the original application.
9125                if (pkg.isUpdatedSystemApp()) {
9126                    final PackageSetting sysPs = mSettings
9127                            .getDisabledSystemPkgLPr(pkg.packageName);
9128                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9129                        // If the original was granted this permission, we take
9130                        // that grant decision as read and propagate it to the
9131                        // update.
9132                        if (sysPs.isPrivileged()) {
9133                            allowed = true;
9134                        }
9135                    } else {
9136                        // The system apk may have been updated with an older
9137                        // version of the one on the data partition, but which
9138                        // granted a new system permission that it didn't have
9139                        // before.  In this case we do want to allow the app to
9140                        // now get the new permission if the ancestral apk is
9141                        // privileged to get it.
9142                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9143                            for (int j=0;
9144                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9145                                if (perm.equals(
9146                                        sysPs.pkg.requestedPermissions.get(j))) {
9147                                    allowed = true;
9148                                    break;
9149                                }
9150                            }
9151                        }
9152                    }
9153                } else {
9154                    allowed = isPrivilegedApp(pkg);
9155                }
9156            }
9157        }
9158        if (!allowed) {
9159            if (!allowed && (bp.protectionLevel
9160                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9161                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9162                // If this was a previously normal/dangerous permission that got moved
9163                // to a system permission as part of the runtime permission redesign, then
9164                // we still want to blindly grant it to old apps.
9165                allowed = true;
9166            }
9167            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9168                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9169                // If this permission is to be granted to the system installer and
9170                // this app is an installer, then it gets the permission.
9171                allowed = true;
9172            }
9173            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9174                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9175                // If this permission is to be granted to the system verifier and
9176                // this app is a verifier, then it gets the permission.
9177                allowed = true;
9178            }
9179            if (!allowed && (bp.protectionLevel
9180                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9181                    && isSystemApp(pkg)) {
9182                // Any pre-installed system app is allowed to get this permission.
9183                allowed = true;
9184            }
9185            if (!allowed && (bp.protectionLevel
9186                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9187                // For development permissions, a development permission
9188                // is granted only if it was already granted.
9189                allowed = origPermissions.hasInstallPermission(perm);
9190            }
9191        }
9192        return allowed;
9193    }
9194
9195    final class ActivityIntentResolver
9196            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9197        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9198                boolean defaultOnly, int userId) {
9199            if (!sUserManager.exists(userId)) return null;
9200            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9201            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9202        }
9203
9204        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9205                int userId) {
9206            if (!sUserManager.exists(userId)) return null;
9207            mFlags = flags;
9208            return super.queryIntent(intent, resolvedType,
9209                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9210        }
9211
9212        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9213                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9214            if (!sUserManager.exists(userId)) return null;
9215            if (packageActivities == null) {
9216                return null;
9217            }
9218            mFlags = flags;
9219            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9220            final int N = packageActivities.size();
9221            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9222                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9223
9224            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9225            for (int i = 0; i < N; ++i) {
9226                intentFilters = packageActivities.get(i).intents;
9227                if (intentFilters != null && intentFilters.size() > 0) {
9228                    PackageParser.ActivityIntentInfo[] array =
9229                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9230                    intentFilters.toArray(array);
9231                    listCut.add(array);
9232                }
9233            }
9234            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9235        }
9236
9237        public final void addActivity(PackageParser.Activity a, String type) {
9238            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9239            mActivities.put(a.getComponentName(), a);
9240            if (DEBUG_SHOW_INFO)
9241                Log.v(
9242                TAG, "  " + type + " " +
9243                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9244            if (DEBUG_SHOW_INFO)
9245                Log.v(TAG, "    Class=" + a.info.name);
9246            final int NI = a.intents.size();
9247            for (int j=0; j<NI; j++) {
9248                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9249                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9250                    intent.setPriority(0);
9251                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9252                            + a.className + " with priority > 0, forcing to 0");
9253                }
9254                if (DEBUG_SHOW_INFO) {
9255                    Log.v(TAG, "    IntentFilter:");
9256                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9257                }
9258                if (!intent.debugCheck()) {
9259                    Log.w(TAG, "==> For Activity " + a.info.name);
9260                }
9261                addFilter(intent);
9262            }
9263        }
9264
9265        public final void removeActivity(PackageParser.Activity a, String type) {
9266            mActivities.remove(a.getComponentName());
9267            if (DEBUG_SHOW_INFO) {
9268                Log.v(TAG, "  " + type + " "
9269                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9270                                : a.info.name) + ":");
9271                Log.v(TAG, "    Class=" + a.info.name);
9272            }
9273            final int NI = a.intents.size();
9274            for (int j=0; j<NI; j++) {
9275                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9276                if (DEBUG_SHOW_INFO) {
9277                    Log.v(TAG, "    IntentFilter:");
9278                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9279                }
9280                removeFilter(intent);
9281            }
9282        }
9283
9284        @Override
9285        protected boolean allowFilterResult(
9286                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9287            ActivityInfo filterAi = filter.activity.info;
9288            for (int i=dest.size()-1; i>=0; i--) {
9289                ActivityInfo destAi = dest.get(i).activityInfo;
9290                if (destAi.name == filterAi.name
9291                        && destAi.packageName == filterAi.packageName) {
9292                    return false;
9293                }
9294            }
9295            return true;
9296        }
9297
9298        @Override
9299        protected ActivityIntentInfo[] newArray(int size) {
9300            return new ActivityIntentInfo[size];
9301        }
9302
9303        @Override
9304        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9305            if (!sUserManager.exists(userId)) return true;
9306            PackageParser.Package p = filter.activity.owner;
9307            if (p != null) {
9308                PackageSetting ps = (PackageSetting)p.mExtras;
9309                if (ps != null) {
9310                    // System apps are never considered stopped for purposes of
9311                    // filtering, because there may be no way for the user to
9312                    // actually re-launch them.
9313                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9314                            && ps.getStopped(userId);
9315                }
9316            }
9317            return false;
9318        }
9319
9320        @Override
9321        protected boolean isPackageForFilter(String packageName,
9322                PackageParser.ActivityIntentInfo info) {
9323            return packageName.equals(info.activity.owner.packageName);
9324        }
9325
9326        @Override
9327        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9328                int match, int userId) {
9329            if (!sUserManager.exists(userId)) return null;
9330            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9331                return null;
9332            }
9333            final PackageParser.Activity activity = info.activity;
9334            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9335            if (ps == null) {
9336                return null;
9337            }
9338            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9339                    ps.readUserState(userId), userId);
9340            if (ai == null) {
9341                return null;
9342            }
9343            final ResolveInfo res = new ResolveInfo();
9344            res.activityInfo = ai;
9345            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9346                res.filter = info;
9347            }
9348            if (info != null) {
9349                res.handleAllWebDataURI = info.handleAllWebDataURI();
9350            }
9351            res.priority = info.getPriority();
9352            res.preferredOrder = activity.owner.mPreferredOrder;
9353            //System.out.println("Result: " + res.activityInfo.className +
9354            //                   " = " + res.priority);
9355            res.match = match;
9356            res.isDefault = info.hasDefault;
9357            res.labelRes = info.labelRes;
9358            res.nonLocalizedLabel = info.nonLocalizedLabel;
9359            if (userNeedsBadging(userId)) {
9360                res.noResourceId = true;
9361            } else {
9362                res.icon = info.icon;
9363            }
9364            res.iconResourceId = info.icon;
9365            res.system = res.activityInfo.applicationInfo.isSystemApp();
9366            return res;
9367        }
9368
9369        @Override
9370        protected void sortResults(List<ResolveInfo> results) {
9371            Collections.sort(results, mResolvePrioritySorter);
9372        }
9373
9374        @Override
9375        protected void dumpFilter(PrintWriter out, String prefix,
9376                PackageParser.ActivityIntentInfo filter) {
9377            out.print(prefix); out.print(
9378                    Integer.toHexString(System.identityHashCode(filter.activity)));
9379                    out.print(' ');
9380                    filter.activity.printComponentShortName(out);
9381                    out.print(" filter ");
9382                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9383        }
9384
9385        @Override
9386        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9387            return filter.activity;
9388        }
9389
9390        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9391            PackageParser.Activity activity = (PackageParser.Activity)label;
9392            out.print(prefix); out.print(
9393                    Integer.toHexString(System.identityHashCode(activity)));
9394                    out.print(' ');
9395                    activity.printComponentShortName(out);
9396            if (count > 1) {
9397                out.print(" ("); out.print(count); out.print(" filters)");
9398            }
9399            out.println();
9400        }
9401
9402//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9403//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9404//            final List<ResolveInfo> retList = Lists.newArrayList();
9405//            while (i.hasNext()) {
9406//                final ResolveInfo resolveInfo = i.next();
9407//                if (isEnabledLP(resolveInfo.activityInfo)) {
9408//                    retList.add(resolveInfo);
9409//                }
9410//            }
9411//            return retList;
9412//        }
9413
9414        // Keys are String (activity class name), values are Activity.
9415        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9416                = new ArrayMap<ComponentName, PackageParser.Activity>();
9417        private int mFlags;
9418    }
9419
9420    private final class ServiceIntentResolver
9421            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9422        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9423                boolean defaultOnly, int userId) {
9424            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9425            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9426        }
9427
9428        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9429                int userId) {
9430            if (!sUserManager.exists(userId)) return null;
9431            mFlags = flags;
9432            return super.queryIntent(intent, resolvedType,
9433                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9434        }
9435
9436        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9437                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9438            if (!sUserManager.exists(userId)) return null;
9439            if (packageServices == null) {
9440                return null;
9441            }
9442            mFlags = flags;
9443            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9444            final int N = packageServices.size();
9445            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9446                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9447
9448            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9449            for (int i = 0; i < N; ++i) {
9450                intentFilters = packageServices.get(i).intents;
9451                if (intentFilters != null && intentFilters.size() > 0) {
9452                    PackageParser.ServiceIntentInfo[] array =
9453                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9454                    intentFilters.toArray(array);
9455                    listCut.add(array);
9456                }
9457            }
9458            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9459        }
9460
9461        public final void addService(PackageParser.Service s) {
9462            mServices.put(s.getComponentName(), s);
9463            if (DEBUG_SHOW_INFO) {
9464                Log.v(TAG, "  "
9465                        + (s.info.nonLocalizedLabel != null
9466                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9467                Log.v(TAG, "    Class=" + s.info.name);
9468            }
9469            final int NI = s.intents.size();
9470            int j;
9471            for (j=0; j<NI; j++) {
9472                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9473                if (DEBUG_SHOW_INFO) {
9474                    Log.v(TAG, "    IntentFilter:");
9475                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9476                }
9477                if (!intent.debugCheck()) {
9478                    Log.w(TAG, "==> For Service " + s.info.name);
9479                }
9480                addFilter(intent);
9481            }
9482        }
9483
9484        public final void removeService(PackageParser.Service s) {
9485            mServices.remove(s.getComponentName());
9486            if (DEBUG_SHOW_INFO) {
9487                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9488                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9489                Log.v(TAG, "    Class=" + s.info.name);
9490            }
9491            final int NI = s.intents.size();
9492            int j;
9493            for (j=0; j<NI; j++) {
9494                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9495                if (DEBUG_SHOW_INFO) {
9496                    Log.v(TAG, "    IntentFilter:");
9497                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9498                }
9499                removeFilter(intent);
9500            }
9501        }
9502
9503        @Override
9504        protected boolean allowFilterResult(
9505                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9506            ServiceInfo filterSi = filter.service.info;
9507            for (int i=dest.size()-1; i>=0; i--) {
9508                ServiceInfo destAi = dest.get(i).serviceInfo;
9509                if (destAi.name == filterSi.name
9510                        && destAi.packageName == filterSi.packageName) {
9511                    return false;
9512                }
9513            }
9514            return true;
9515        }
9516
9517        @Override
9518        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9519            return new PackageParser.ServiceIntentInfo[size];
9520        }
9521
9522        @Override
9523        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9524            if (!sUserManager.exists(userId)) return true;
9525            PackageParser.Package p = filter.service.owner;
9526            if (p != null) {
9527                PackageSetting ps = (PackageSetting)p.mExtras;
9528                if (ps != null) {
9529                    // System apps are never considered stopped for purposes of
9530                    // filtering, because there may be no way for the user to
9531                    // actually re-launch them.
9532                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9533                            && ps.getStopped(userId);
9534                }
9535            }
9536            return false;
9537        }
9538
9539        @Override
9540        protected boolean isPackageForFilter(String packageName,
9541                PackageParser.ServiceIntentInfo info) {
9542            return packageName.equals(info.service.owner.packageName);
9543        }
9544
9545        @Override
9546        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9547                int match, int userId) {
9548            if (!sUserManager.exists(userId)) return null;
9549            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9550            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9551                return null;
9552            }
9553            final PackageParser.Service service = info.service;
9554            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9555            if (ps == null) {
9556                return null;
9557            }
9558            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9559                    ps.readUserState(userId), userId);
9560            if (si == null) {
9561                return null;
9562            }
9563            final ResolveInfo res = new ResolveInfo();
9564            res.serviceInfo = si;
9565            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9566                res.filter = filter;
9567            }
9568            res.priority = info.getPriority();
9569            res.preferredOrder = service.owner.mPreferredOrder;
9570            res.match = match;
9571            res.isDefault = info.hasDefault;
9572            res.labelRes = info.labelRes;
9573            res.nonLocalizedLabel = info.nonLocalizedLabel;
9574            res.icon = info.icon;
9575            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9576            return res;
9577        }
9578
9579        @Override
9580        protected void sortResults(List<ResolveInfo> results) {
9581            Collections.sort(results, mResolvePrioritySorter);
9582        }
9583
9584        @Override
9585        protected void dumpFilter(PrintWriter out, String prefix,
9586                PackageParser.ServiceIntentInfo filter) {
9587            out.print(prefix); out.print(
9588                    Integer.toHexString(System.identityHashCode(filter.service)));
9589                    out.print(' ');
9590                    filter.service.printComponentShortName(out);
9591                    out.print(" filter ");
9592                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9593        }
9594
9595        @Override
9596        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9597            return filter.service;
9598        }
9599
9600        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9601            PackageParser.Service service = (PackageParser.Service)label;
9602            out.print(prefix); out.print(
9603                    Integer.toHexString(System.identityHashCode(service)));
9604                    out.print(' ');
9605                    service.printComponentShortName(out);
9606            if (count > 1) {
9607                out.print(" ("); out.print(count); out.print(" filters)");
9608            }
9609            out.println();
9610        }
9611
9612//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9613//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9614//            final List<ResolveInfo> retList = Lists.newArrayList();
9615//            while (i.hasNext()) {
9616//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9617//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9618//                    retList.add(resolveInfo);
9619//                }
9620//            }
9621//            return retList;
9622//        }
9623
9624        // Keys are String (activity class name), values are Activity.
9625        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9626                = new ArrayMap<ComponentName, PackageParser.Service>();
9627        private int mFlags;
9628    };
9629
9630    private final class ProviderIntentResolver
9631            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9632        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9633                boolean defaultOnly, int userId) {
9634            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9635            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9636        }
9637
9638        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9639                int userId) {
9640            if (!sUserManager.exists(userId))
9641                return null;
9642            mFlags = flags;
9643            return super.queryIntent(intent, resolvedType,
9644                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9645        }
9646
9647        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9648                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9649            if (!sUserManager.exists(userId))
9650                return null;
9651            if (packageProviders == null) {
9652                return null;
9653            }
9654            mFlags = flags;
9655            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9656            final int N = packageProviders.size();
9657            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9658                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9659
9660            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9661            for (int i = 0; i < N; ++i) {
9662                intentFilters = packageProviders.get(i).intents;
9663                if (intentFilters != null && intentFilters.size() > 0) {
9664                    PackageParser.ProviderIntentInfo[] array =
9665                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9666                    intentFilters.toArray(array);
9667                    listCut.add(array);
9668                }
9669            }
9670            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9671        }
9672
9673        public final void addProvider(PackageParser.Provider p) {
9674            if (mProviders.containsKey(p.getComponentName())) {
9675                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9676                return;
9677            }
9678
9679            mProviders.put(p.getComponentName(), p);
9680            if (DEBUG_SHOW_INFO) {
9681                Log.v(TAG, "  "
9682                        + (p.info.nonLocalizedLabel != null
9683                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9684                Log.v(TAG, "    Class=" + p.info.name);
9685            }
9686            final int NI = p.intents.size();
9687            int j;
9688            for (j = 0; j < NI; j++) {
9689                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9690                if (DEBUG_SHOW_INFO) {
9691                    Log.v(TAG, "    IntentFilter:");
9692                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9693                }
9694                if (!intent.debugCheck()) {
9695                    Log.w(TAG, "==> For Provider " + p.info.name);
9696                }
9697                addFilter(intent);
9698            }
9699        }
9700
9701        public final void removeProvider(PackageParser.Provider p) {
9702            mProviders.remove(p.getComponentName());
9703            if (DEBUG_SHOW_INFO) {
9704                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9705                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9706                Log.v(TAG, "    Class=" + p.info.name);
9707            }
9708            final int NI = p.intents.size();
9709            int j;
9710            for (j = 0; j < NI; j++) {
9711                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9712                if (DEBUG_SHOW_INFO) {
9713                    Log.v(TAG, "    IntentFilter:");
9714                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9715                }
9716                removeFilter(intent);
9717            }
9718        }
9719
9720        @Override
9721        protected boolean allowFilterResult(
9722                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9723            ProviderInfo filterPi = filter.provider.info;
9724            for (int i = dest.size() - 1; i >= 0; i--) {
9725                ProviderInfo destPi = dest.get(i).providerInfo;
9726                if (destPi.name == filterPi.name
9727                        && destPi.packageName == filterPi.packageName) {
9728                    return false;
9729                }
9730            }
9731            return true;
9732        }
9733
9734        @Override
9735        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9736            return new PackageParser.ProviderIntentInfo[size];
9737        }
9738
9739        @Override
9740        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9741            if (!sUserManager.exists(userId))
9742                return true;
9743            PackageParser.Package p = filter.provider.owner;
9744            if (p != null) {
9745                PackageSetting ps = (PackageSetting) p.mExtras;
9746                if (ps != null) {
9747                    // System apps are never considered stopped for purposes of
9748                    // filtering, because there may be no way for the user to
9749                    // actually re-launch them.
9750                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9751                            && ps.getStopped(userId);
9752                }
9753            }
9754            return false;
9755        }
9756
9757        @Override
9758        protected boolean isPackageForFilter(String packageName,
9759                PackageParser.ProviderIntentInfo info) {
9760            return packageName.equals(info.provider.owner.packageName);
9761        }
9762
9763        @Override
9764        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9765                int match, int userId) {
9766            if (!sUserManager.exists(userId))
9767                return null;
9768            final PackageParser.ProviderIntentInfo info = filter;
9769            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9770                return null;
9771            }
9772            final PackageParser.Provider provider = info.provider;
9773            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9774            if (ps == null) {
9775                return null;
9776            }
9777            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9778                    ps.readUserState(userId), userId);
9779            if (pi == null) {
9780                return null;
9781            }
9782            final ResolveInfo res = new ResolveInfo();
9783            res.providerInfo = pi;
9784            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9785                res.filter = filter;
9786            }
9787            res.priority = info.getPriority();
9788            res.preferredOrder = provider.owner.mPreferredOrder;
9789            res.match = match;
9790            res.isDefault = info.hasDefault;
9791            res.labelRes = info.labelRes;
9792            res.nonLocalizedLabel = info.nonLocalizedLabel;
9793            res.icon = info.icon;
9794            res.system = res.providerInfo.applicationInfo.isSystemApp();
9795            return res;
9796        }
9797
9798        @Override
9799        protected void sortResults(List<ResolveInfo> results) {
9800            Collections.sort(results, mResolvePrioritySorter);
9801        }
9802
9803        @Override
9804        protected void dumpFilter(PrintWriter out, String prefix,
9805                PackageParser.ProviderIntentInfo filter) {
9806            out.print(prefix);
9807            out.print(
9808                    Integer.toHexString(System.identityHashCode(filter.provider)));
9809            out.print(' ');
9810            filter.provider.printComponentShortName(out);
9811            out.print(" filter ");
9812            out.println(Integer.toHexString(System.identityHashCode(filter)));
9813        }
9814
9815        @Override
9816        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9817            return filter.provider;
9818        }
9819
9820        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9821            PackageParser.Provider provider = (PackageParser.Provider)label;
9822            out.print(prefix); out.print(
9823                    Integer.toHexString(System.identityHashCode(provider)));
9824                    out.print(' ');
9825                    provider.printComponentShortName(out);
9826            if (count > 1) {
9827                out.print(" ("); out.print(count); out.print(" filters)");
9828            }
9829            out.println();
9830        }
9831
9832        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9833                = new ArrayMap<ComponentName, PackageParser.Provider>();
9834        private int mFlags;
9835    }
9836
9837    private static final class EphemeralIntentResolver
9838            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9839        @Override
9840        protected EphemeralResolveIntentInfo[] newArray(int size) {
9841            return new EphemeralResolveIntentInfo[size];
9842        }
9843
9844        @Override
9845        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9846            return true;
9847        }
9848
9849        @Override
9850        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9851                int userId) {
9852            if (!sUserManager.exists(userId)) {
9853                return null;
9854            }
9855            return info.getEphemeralResolveInfo();
9856        }
9857    }
9858
9859    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9860            new Comparator<ResolveInfo>() {
9861        public int compare(ResolveInfo r1, ResolveInfo r2) {
9862            int v1 = r1.priority;
9863            int v2 = r2.priority;
9864            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9865            if (v1 != v2) {
9866                return (v1 > v2) ? -1 : 1;
9867            }
9868            v1 = r1.preferredOrder;
9869            v2 = r2.preferredOrder;
9870            if (v1 != v2) {
9871                return (v1 > v2) ? -1 : 1;
9872            }
9873            if (r1.isDefault != r2.isDefault) {
9874                return r1.isDefault ? -1 : 1;
9875            }
9876            v1 = r1.match;
9877            v2 = r2.match;
9878            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9879            if (v1 != v2) {
9880                return (v1 > v2) ? -1 : 1;
9881            }
9882            if (r1.system != r2.system) {
9883                return r1.system ? -1 : 1;
9884            }
9885            if (r1.activityInfo != null) {
9886                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9887            }
9888            if (r1.serviceInfo != null) {
9889                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9890            }
9891            if (r1.providerInfo != null) {
9892                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9893            }
9894            return 0;
9895        }
9896    };
9897
9898    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9899            new Comparator<ProviderInfo>() {
9900        public int compare(ProviderInfo p1, ProviderInfo p2) {
9901            final int v1 = p1.initOrder;
9902            final int v2 = p2.initOrder;
9903            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9904        }
9905    };
9906
9907    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9908            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9909            final int[] userIds) {
9910        mHandler.post(new Runnable() {
9911            @Override
9912            public void run() {
9913                try {
9914                    final IActivityManager am = ActivityManagerNative.getDefault();
9915                    if (am == null) return;
9916                    final int[] resolvedUserIds;
9917                    if (userIds == null) {
9918                        resolvedUserIds = am.getRunningUserIds();
9919                    } else {
9920                        resolvedUserIds = userIds;
9921                    }
9922                    for (int id : resolvedUserIds) {
9923                        final Intent intent = new Intent(action,
9924                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9925                        if (extras != null) {
9926                            intent.putExtras(extras);
9927                        }
9928                        if (targetPkg != null) {
9929                            intent.setPackage(targetPkg);
9930                        }
9931                        // Modify the UID when posting to other users
9932                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9933                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9934                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9935                            intent.putExtra(Intent.EXTRA_UID, uid);
9936                        }
9937                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9938                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9939                        if (DEBUG_BROADCASTS) {
9940                            RuntimeException here = new RuntimeException("here");
9941                            here.fillInStackTrace();
9942                            Slog.d(TAG, "Sending to user " + id + ": "
9943                                    + intent.toShortString(false, true, false, false)
9944                                    + " " + intent.getExtras(), here);
9945                        }
9946                        am.broadcastIntent(null, intent, null, finishedReceiver,
9947                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9948                                null, finishedReceiver != null, false, id);
9949                    }
9950                } catch (RemoteException ex) {
9951                }
9952            }
9953        });
9954    }
9955
9956    /**
9957     * Check if the external storage media is available. This is true if there
9958     * is a mounted external storage medium or if the external storage is
9959     * emulated.
9960     */
9961    private boolean isExternalMediaAvailable() {
9962        return mMediaMounted || Environment.isExternalStorageEmulated();
9963    }
9964
9965    @Override
9966    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9967        // writer
9968        synchronized (mPackages) {
9969            if (!isExternalMediaAvailable()) {
9970                // If the external storage is no longer mounted at this point,
9971                // the caller may not have been able to delete all of this
9972                // packages files and can not delete any more.  Bail.
9973                return null;
9974            }
9975            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9976            if (lastPackage != null) {
9977                pkgs.remove(lastPackage);
9978            }
9979            if (pkgs.size() > 0) {
9980                return pkgs.get(0);
9981            }
9982        }
9983        return null;
9984    }
9985
9986    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9987        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9988                userId, andCode ? 1 : 0, packageName);
9989        if (mSystemReady) {
9990            msg.sendToTarget();
9991        } else {
9992            if (mPostSystemReadyMessages == null) {
9993                mPostSystemReadyMessages = new ArrayList<>();
9994            }
9995            mPostSystemReadyMessages.add(msg);
9996        }
9997    }
9998
9999    void startCleaningPackages() {
10000        // reader
10001        synchronized (mPackages) {
10002            if (!isExternalMediaAvailable()) {
10003                return;
10004            }
10005            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10006                return;
10007            }
10008        }
10009        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10010        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10011        IActivityManager am = ActivityManagerNative.getDefault();
10012        if (am != null) {
10013            try {
10014                am.startService(null, intent, null, mContext.getOpPackageName(),
10015                        UserHandle.USER_SYSTEM);
10016            } catch (RemoteException e) {
10017            }
10018        }
10019    }
10020
10021    @Override
10022    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10023            int installFlags, String installerPackageName, VerificationParams verificationParams,
10024            String packageAbiOverride) {
10025        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10026                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10027    }
10028
10029    @Override
10030    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10031            int installFlags, String installerPackageName, VerificationParams verificationParams,
10032            String packageAbiOverride, int userId) {
10033        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10034
10035        final int callingUid = Binder.getCallingUid();
10036        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10037
10038        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10039            try {
10040                if (observer != null) {
10041                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10042                }
10043            } catch (RemoteException re) {
10044            }
10045            return;
10046        }
10047
10048        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10049            installFlags |= PackageManager.INSTALL_FROM_ADB;
10050
10051        } else {
10052            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10053            // about installerPackageName.
10054
10055            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10056            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10057        }
10058
10059        UserHandle user;
10060        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10061            user = UserHandle.ALL;
10062        } else {
10063            user = new UserHandle(userId);
10064        }
10065
10066        // Only system components can circumvent runtime permissions when installing.
10067        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10068                && mContext.checkCallingOrSelfPermission(Manifest.permission
10069                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10070            throw new SecurityException("You need the "
10071                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10072                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10073        }
10074
10075        verificationParams.setInstallerUid(callingUid);
10076
10077        final File originFile = new File(originPath);
10078        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10079
10080        final Message msg = mHandler.obtainMessage(INIT_COPY);
10081        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10082                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10083        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10084        msg.obj = params;
10085
10086        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10087                System.identityHashCode(msg.obj));
10088        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10089                System.identityHashCode(msg.obj));
10090
10091        mHandler.sendMessage(msg);
10092    }
10093
10094    void installStage(String packageName, File stagedDir, String stagedCid,
10095            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10096            String installerPackageName, int installerUid, UserHandle user) {
10097        if (DEBUG_EPHEMERAL) {
10098            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10099                Slog.d(TAG, "Ephemeral install of " + packageName);
10100            }
10101        }
10102        final VerificationParams verifParams = new VerificationParams(
10103                null, sessionParams.originatingUri, sessionParams.referrerUri,
10104                sessionParams.originatingUid);
10105        verifParams.setInstallerUid(installerUid);
10106
10107        final OriginInfo origin;
10108        if (stagedDir != null) {
10109            origin = OriginInfo.fromStagedFile(stagedDir);
10110        } else {
10111            origin = OriginInfo.fromStagedContainer(stagedCid);
10112        }
10113
10114        final Message msg = mHandler.obtainMessage(INIT_COPY);
10115        final InstallParams params = new InstallParams(origin, null, observer,
10116                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10117                verifParams, user, sessionParams.abiOverride,
10118                sessionParams.grantedRuntimePermissions);
10119        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10120        msg.obj = params;
10121
10122        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10123                System.identityHashCode(msg.obj));
10124        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10125                System.identityHashCode(msg.obj));
10126
10127        mHandler.sendMessage(msg);
10128    }
10129
10130    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10131        Bundle extras = new Bundle(1);
10132        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10133
10134        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10135                packageName, extras, 0, null, null, new int[] {userId});
10136        try {
10137            IActivityManager am = ActivityManagerNative.getDefault();
10138            final boolean isSystem =
10139                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10140            if (isSystem && am.isUserRunning(userId, 0)) {
10141                // The just-installed/enabled app is bundled on the system, so presumed
10142                // to be able to run automatically without needing an explicit launch.
10143                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10144                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10145                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10146                        .setPackage(packageName);
10147                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10148                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10149            }
10150        } catch (RemoteException e) {
10151            // shouldn't happen
10152            Slog.w(TAG, "Unable to bootstrap installed package", e);
10153        }
10154    }
10155
10156    @Override
10157    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10158            int userId) {
10159        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10160        PackageSetting pkgSetting;
10161        final int uid = Binder.getCallingUid();
10162        enforceCrossUserPermission(uid, userId, true, true,
10163                "setApplicationHiddenSetting for user " + userId);
10164
10165        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10166            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10167            return false;
10168        }
10169
10170        long callingId = Binder.clearCallingIdentity();
10171        try {
10172            boolean sendAdded = false;
10173            boolean sendRemoved = false;
10174            // writer
10175            synchronized (mPackages) {
10176                pkgSetting = mSettings.mPackages.get(packageName);
10177                if (pkgSetting == null) {
10178                    return false;
10179                }
10180                if (pkgSetting.getHidden(userId) != hidden) {
10181                    pkgSetting.setHidden(hidden, userId);
10182                    mSettings.writePackageRestrictionsLPr(userId);
10183                    if (hidden) {
10184                        sendRemoved = true;
10185                    } else {
10186                        sendAdded = true;
10187                    }
10188                }
10189            }
10190            if (sendAdded) {
10191                sendPackageAddedForUser(packageName, pkgSetting, userId);
10192                return true;
10193            }
10194            if (sendRemoved) {
10195                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10196                        "hiding pkg");
10197                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10198                return true;
10199            }
10200        } finally {
10201            Binder.restoreCallingIdentity(callingId);
10202        }
10203        return false;
10204    }
10205
10206    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10207            int userId) {
10208        final PackageRemovedInfo info = new PackageRemovedInfo();
10209        info.removedPackage = packageName;
10210        info.removedUsers = new int[] {userId};
10211        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10212        info.sendBroadcast(false, false, false);
10213    }
10214
10215    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10216        if (pkgList.length > 0) {
10217            Bundle extras = new Bundle(1);
10218            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10219
10220            sendPackageBroadcast(
10221                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10222                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10223                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10224                    new int[] {userId});
10225        }
10226    }
10227
10228    /**
10229     * Returns true if application is not found or there was an error. Otherwise it returns
10230     * the hidden state of the package for the given user.
10231     */
10232    @Override
10233    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10234        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10235        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10236                false, "getApplicationHidden for user " + userId);
10237        PackageSetting pkgSetting;
10238        long callingId = Binder.clearCallingIdentity();
10239        try {
10240            // writer
10241            synchronized (mPackages) {
10242                pkgSetting = mSettings.mPackages.get(packageName);
10243                if (pkgSetting == null) {
10244                    return true;
10245                }
10246                return pkgSetting.getHidden(userId);
10247            }
10248        } finally {
10249            Binder.restoreCallingIdentity(callingId);
10250        }
10251    }
10252
10253    /**
10254     * @hide
10255     */
10256    @Override
10257    public int installExistingPackageAsUser(String packageName, int userId) {
10258        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10259                null);
10260        PackageSetting pkgSetting;
10261        final int uid = Binder.getCallingUid();
10262        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10263                + userId);
10264        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10265            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10266        }
10267
10268        long callingId = Binder.clearCallingIdentity();
10269        try {
10270            boolean installed = false;
10271
10272            // writer
10273            synchronized (mPackages) {
10274                pkgSetting = mSettings.mPackages.get(packageName);
10275                if (pkgSetting == null) {
10276                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10277                }
10278                if (!pkgSetting.getInstalled(userId)) {
10279                    pkgSetting.setInstalled(true, userId);
10280                    pkgSetting.setHidden(false, userId);
10281                    mSettings.writePackageRestrictionsLPr(userId);
10282                    if (pkgSetting.pkg != null) {
10283                        prepareAppDataAfterInstall(pkgSetting.pkg);
10284                    }
10285                    installed = true;
10286                }
10287            }
10288
10289            if (installed) {
10290                sendPackageAddedForUser(packageName, pkgSetting, userId);
10291            }
10292        } finally {
10293            Binder.restoreCallingIdentity(callingId);
10294        }
10295
10296        return PackageManager.INSTALL_SUCCEEDED;
10297    }
10298
10299    boolean isUserRestricted(int userId, String restrictionKey) {
10300        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10301        if (restrictions.getBoolean(restrictionKey, false)) {
10302            Log.w(TAG, "User is restricted: " + restrictionKey);
10303            return true;
10304        }
10305        return false;
10306    }
10307
10308    @Override
10309    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10310        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10311        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10312                "setPackageSuspended for user " + userId);
10313
10314        // TODO: investigate and add more restrictions for suspending crucial packages.
10315        if (isPackageDeviceAdmin(packageName, userId)) {
10316            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10317                    + "\": has active device admin");
10318            return false;
10319        }
10320
10321        long callingId = Binder.clearCallingIdentity();
10322        try {
10323            boolean changed = false;
10324            boolean success = false;
10325            int appId = -1;
10326            synchronized (mPackages) {
10327                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10328                if (pkgSetting != null) {
10329                    if (pkgSetting.getSuspended(userId) != suspended) {
10330                        pkgSetting.setSuspended(suspended, userId);
10331                        mSettings.writePackageRestrictionsLPr(userId);
10332                        appId = pkgSetting.appId;
10333                        changed = true;
10334                    }
10335                    success = true;
10336                }
10337            }
10338
10339            if (changed) {
10340                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10341                if (suspended) {
10342                    killApplication(packageName, UserHandle.getUid(userId, appId),
10343                            "suspending package");
10344                }
10345            }
10346            return success;
10347        } finally {
10348            Binder.restoreCallingIdentity(callingId);
10349        }
10350    }
10351
10352    @Override
10353    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10354        mContext.enforceCallingOrSelfPermission(
10355                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10356                "Only package verification agents can verify applications");
10357
10358        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10359        final PackageVerificationResponse response = new PackageVerificationResponse(
10360                verificationCode, Binder.getCallingUid());
10361        msg.arg1 = id;
10362        msg.obj = response;
10363        mHandler.sendMessage(msg);
10364    }
10365
10366    @Override
10367    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10368            long millisecondsToDelay) {
10369        mContext.enforceCallingOrSelfPermission(
10370                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10371                "Only package verification agents can extend verification timeouts");
10372
10373        final PackageVerificationState state = mPendingVerification.get(id);
10374        final PackageVerificationResponse response = new PackageVerificationResponse(
10375                verificationCodeAtTimeout, Binder.getCallingUid());
10376
10377        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10378            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10379        }
10380        if (millisecondsToDelay < 0) {
10381            millisecondsToDelay = 0;
10382        }
10383        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10384                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10385            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10386        }
10387
10388        if ((state != null) && !state.timeoutExtended()) {
10389            state.extendTimeout();
10390
10391            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10392            msg.arg1 = id;
10393            msg.obj = response;
10394            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10395        }
10396    }
10397
10398    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10399            int verificationCode, UserHandle user) {
10400        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10401        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10402        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10403        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10404        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10405
10406        mContext.sendBroadcastAsUser(intent, user,
10407                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10408    }
10409
10410    private ComponentName matchComponentForVerifier(String packageName,
10411            List<ResolveInfo> receivers) {
10412        ActivityInfo targetReceiver = null;
10413
10414        final int NR = receivers.size();
10415        for (int i = 0; i < NR; i++) {
10416            final ResolveInfo info = receivers.get(i);
10417            if (info.activityInfo == null) {
10418                continue;
10419            }
10420
10421            if (packageName.equals(info.activityInfo.packageName)) {
10422                targetReceiver = info.activityInfo;
10423                break;
10424            }
10425        }
10426
10427        if (targetReceiver == null) {
10428            return null;
10429        }
10430
10431        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10432    }
10433
10434    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10435            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10436        if (pkgInfo.verifiers.length == 0) {
10437            return null;
10438        }
10439
10440        final int N = pkgInfo.verifiers.length;
10441        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10442        for (int i = 0; i < N; i++) {
10443            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10444
10445            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10446                    receivers);
10447            if (comp == null) {
10448                continue;
10449            }
10450
10451            final int verifierUid = getUidForVerifier(verifierInfo);
10452            if (verifierUid == -1) {
10453                continue;
10454            }
10455
10456            if (DEBUG_VERIFY) {
10457                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10458                        + " with the correct signature");
10459            }
10460            sufficientVerifiers.add(comp);
10461            verificationState.addSufficientVerifier(verifierUid);
10462        }
10463
10464        return sufficientVerifiers;
10465    }
10466
10467    private int getUidForVerifier(VerifierInfo verifierInfo) {
10468        synchronized (mPackages) {
10469            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10470            if (pkg == null) {
10471                return -1;
10472            } else if (pkg.mSignatures.length != 1) {
10473                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10474                        + " has more than one signature; ignoring");
10475                return -1;
10476            }
10477
10478            /*
10479             * If the public key of the package's signature does not match
10480             * our expected public key, then this is a different package and
10481             * we should skip.
10482             */
10483
10484            final byte[] expectedPublicKey;
10485            try {
10486                final Signature verifierSig = pkg.mSignatures[0];
10487                final PublicKey publicKey = verifierSig.getPublicKey();
10488                expectedPublicKey = publicKey.getEncoded();
10489            } catch (CertificateException e) {
10490                return -1;
10491            }
10492
10493            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10494
10495            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10496                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10497                        + " does not have the expected public key; ignoring");
10498                return -1;
10499            }
10500
10501            return pkg.applicationInfo.uid;
10502        }
10503    }
10504
10505    @Override
10506    public void finishPackageInstall(int token) {
10507        enforceSystemOrRoot("Only the system is allowed to finish installs");
10508
10509        if (DEBUG_INSTALL) {
10510            Slog.v(TAG, "BM finishing package install for " + token);
10511        }
10512        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10513
10514        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10515        mHandler.sendMessage(msg);
10516    }
10517
10518    /**
10519     * Get the verification agent timeout.
10520     *
10521     * @return verification timeout in milliseconds
10522     */
10523    private long getVerificationTimeout() {
10524        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10525                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10526                DEFAULT_VERIFICATION_TIMEOUT);
10527    }
10528
10529    /**
10530     * Get the default verification agent response code.
10531     *
10532     * @return default verification response code
10533     */
10534    private int getDefaultVerificationResponse() {
10535        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10536                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10537                DEFAULT_VERIFICATION_RESPONSE);
10538    }
10539
10540    /**
10541     * Check whether or not package verification has been enabled.
10542     *
10543     * @return true if verification should be performed
10544     */
10545    private boolean isVerificationEnabled(int userId, int installFlags) {
10546        if (!DEFAULT_VERIFY_ENABLE) {
10547            return false;
10548        }
10549        // Ephemeral apps don't get the full verification treatment
10550        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10551            if (DEBUG_EPHEMERAL) {
10552                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10553            }
10554            return false;
10555        }
10556
10557        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10558
10559        // Check if installing from ADB
10560        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10561            // Do not run verification in a test harness environment
10562            if (ActivityManager.isRunningInTestHarness()) {
10563                return false;
10564            }
10565            if (ensureVerifyAppsEnabled) {
10566                return true;
10567            }
10568            // Check if the developer does not want package verification for ADB installs
10569            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10570                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10571                return false;
10572            }
10573        }
10574
10575        if (ensureVerifyAppsEnabled) {
10576            return true;
10577        }
10578
10579        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10580                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10581    }
10582
10583    @Override
10584    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10585            throws RemoteException {
10586        mContext.enforceCallingOrSelfPermission(
10587                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10588                "Only intentfilter verification agents can verify applications");
10589
10590        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10591        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10592                Binder.getCallingUid(), verificationCode, failedDomains);
10593        msg.arg1 = id;
10594        msg.obj = response;
10595        mHandler.sendMessage(msg);
10596    }
10597
10598    @Override
10599    public int getIntentVerificationStatus(String packageName, int userId) {
10600        synchronized (mPackages) {
10601            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10602        }
10603    }
10604
10605    @Override
10606    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10607        mContext.enforceCallingOrSelfPermission(
10608                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10609
10610        boolean result = false;
10611        synchronized (mPackages) {
10612            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10613        }
10614        if (result) {
10615            scheduleWritePackageRestrictionsLocked(userId);
10616        }
10617        return result;
10618    }
10619
10620    @Override
10621    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10622        synchronized (mPackages) {
10623            return mSettings.getIntentFilterVerificationsLPr(packageName);
10624        }
10625    }
10626
10627    @Override
10628    public List<IntentFilter> getAllIntentFilters(String packageName) {
10629        if (TextUtils.isEmpty(packageName)) {
10630            return Collections.<IntentFilter>emptyList();
10631        }
10632        synchronized (mPackages) {
10633            PackageParser.Package pkg = mPackages.get(packageName);
10634            if (pkg == null || pkg.activities == null) {
10635                return Collections.<IntentFilter>emptyList();
10636            }
10637            final int count = pkg.activities.size();
10638            ArrayList<IntentFilter> result = new ArrayList<>();
10639            for (int n=0; n<count; n++) {
10640                PackageParser.Activity activity = pkg.activities.get(n);
10641                if (activity.intents != null && activity.intents.size() > 0) {
10642                    result.addAll(activity.intents);
10643                }
10644            }
10645            return result;
10646        }
10647    }
10648
10649    @Override
10650    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10651        mContext.enforceCallingOrSelfPermission(
10652                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10653
10654        synchronized (mPackages) {
10655            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10656            if (packageName != null) {
10657                result |= updateIntentVerificationStatus(packageName,
10658                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10659                        userId);
10660                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10661                        packageName, userId);
10662            }
10663            return result;
10664        }
10665    }
10666
10667    @Override
10668    public String getDefaultBrowserPackageName(int userId) {
10669        synchronized (mPackages) {
10670            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10671        }
10672    }
10673
10674    /**
10675     * Get the "allow unknown sources" setting.
10676     *
10677     * @return the current "allow unknown sources" setting
10678     */
10679    private int getUnknownSourcesSettings() {
10680        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10681                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10682                -1);
10683    }
10684
10685    @Override
10686    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10687        final int uid = Binder.getCallingUid();
10688        // writer
10689        synchronized (mPackages) {
10690            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10691            if (targetPackageSetting == null) {
10692                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10693            }
10694
10695            PackageSetting installerPackageSetting;
10696            if (installerPackageName != null) {
10697                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10698                if (installerPackageSetting == null) {
10699                    throw new IllegalArgumentException("Unknown installer package: "
10700                            + installerPackageName);
10701                }
10702            } else {
10703                installerPackageSetting = null;
10704            }
10705
10706            Signature[] callerSignature;
10707            Object obj = mSettings.getUserIdLPr(uid);
10708            if (obj != null) {
10709                if (obj instanceof SharedUserSetting) {
10710                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10711                } else if (obj instanceof PackageSetting) {
10712                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10713                } else {
10714                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10715                }
10716            } else {
10717                throw new SecurityException("Unknown calling UID: " + uid);
10718            }
10719
10720            // Verify: can't set installerPackageName to a package that is
10721            // not signed with the same cert as the caller.
10722            if (installerPackageSetting != null) {
10723                if (compareSignatures(callerSignature,
10724                        installerPackageSetting.signatures.mSignatures)
10725                        != PackageManager.SIGNATURE_MATCH) {
10726                    throw new SecurityException(
10727                            "Caller does not have same cert as new installer package "
10728                            + installerPackageName);
10729                }
10730            }
10731
10732            // Verify: if target already has an installer package, it must
10733            // be signed with the same cert as the caller.
10734            if (targetPackageSetting.installerPackageName != null) {
10735                PackageSetting setting = mSettings.mPackages.get(
10736                        targetPackageSetting.installerPackageName);
10737                // If the currently set package isn't valid, then it's always
10738                // okay to change it.
10739                if (setting != null) {
10740                    if (compareSignatures(callerSignature,
10741                            setting.signatures.mSignatures)
10742                            != PackageManager.SIGNATURE_MATCH) {
10743                        throw new SecurityException(
10744                                "Caller does not have same cert as old installer package "
10745                                + targetPackageSetting.installerPackageName);
10746                    }
10747                }
10748            }
10749
10750            // Okay!
10751            targetPackageSetting.installerPackageName = installerPackageName;
10752            scheduleWriteSettingsLocked();
10753        }
10754    }
10755
10756    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10757        // Queue up an async operation since the package installation may take a little while.
10758        mHandler.post(new Runnable() {
10759            public void run() {
10760                mHandler.removeCallbacks(this);
10761                 // Result object to be returned
10762                PackageInstalledInfo res = new PackageInstalledInfo();
10763                res.returnCode = currentStatus;
10764                res.uid = -1;
10765                res.pkg = null;
10766                res.removedInfo = new PackageRemovedInfo();
10767                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10768                    args.doPreInstall(res.returnCode);
10769                    synchronized (mInstallLock) {
10770                        installPackageTracedLI(args, res);
10771                    }
10772                    args.doPostInstall(res.returnCode, res.uid);
10773                }
10774
10775                // A restore should be performed at this point if (a) the install
10776                // succeeded, (b) the operation is not an update, and (c) the new
10777                // package has not opted out of backup participation.
10778                final boolean update = res.removedInfo.removedPackage != null;
10779                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10780                boolean doRestore = !update
10781                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10782
10783                // Set up the post-install work request bookkeeping.  This will be used
10784                // and cleaned up by the post-install event handling regardless of whether
10785                // there's a restore pass performed.  Token values are >= 1.
10786                int token;
10787                if (mNextInstallToken < 0) mNextInstallToken = 1;
10788                token = mNextInstallToken++;
10789
10790                PostInstallData data = new PostInstallData(args, res);
10791                mRunningInstalls.put(token, data);
10792                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10793
10794                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10795                    // Pass responsibility to the Backup Manager.  It will perform a
10796                    // restore if appropriate, then pass responsibility back to the
10797                    // Package Manager to run the post-install observer callbacks
10798                    // and broadcasts.
10799                    IBackupManager bm = IBackupManager.Stub.asInterface(
10800                            ServiceManager.getService(Context.BACKUP_SERVICE));
10801                    if (bm != null) {
10802                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10803                                + " to BM for possible restore");
10804                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10805                        try {
10806                            // TODO: http://b/22388012
10807                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10808                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10809                            } else {
10810                                doRestore = false;
10811                            }
10812                        } catch (RemoteException e) {
10813                            // can't happen; the backup manager is local
10814                        } catch (Exception e) {
10815                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10816                            doRestore = false;
10817                        }
10818                    } else {
10819                        Slog.e(TAG, "Backup Manager not found!");
10820                        doRestore = false;
10821                    }
10822                }
10823
10824                if (!doRestore) {
10825                    // No restore possible, or the Backup Manager was mysteriously not
10826                    // available -- just fire the post-install work request directly.
10827                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10828
10829                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10830
10831                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10832                    mHandler.sendMessage(msg);
10833                }
10834            }
10835        });
10836    }
10837
10838    private abstract class HandlerParams {
10839        private static final int MAX_RETRIES = 4;
10840
10841        /**
10842         * Number of times startCopy() has been attempted and had a non-fatal
10843         * error.
10844         */
10845        private int mRetries = 0;
10846
10847        /** User handle for the user requesting the information or installation. */
10848        private final UserHandle mUser;
10849        String traceMethod;
10850        int traceCookie;
10851
10852        HandlerParams(UserHandle user) {
10853            mUser = user;
10854        }
10855
10856        UserHandle getUser() {
10857            return mUser;
10858        }
10859
10860        HandlerParams setTraceMethod(String traceMethod) {
10861            this.traceMethod = traceMethod;
10862            return this;
10863        }
10864
10865        HandlerParams setTraceCookie(int traceCookie) {
10866            this.traceCookie = traceCookie;
10867            return this;
10868        }
10869
10870        final boolean startCopy() {
10871            boolean res;
10872            try {
10873                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10874
10875                if (++mRetries > MAX_RETRIES) {
10876                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10877                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10878                    handleServiceError();
10879                    return false;
10880                } else {
10881                    handleStartCopy();
10882                    res = true;
10883                }
10884            } catch (RemoteException e) {
10885                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10886                mHandler.sendEmptyMessage(MCS_RECONNECT);
10887                res = false;
10888            }
10889            handleReturnCode();
10890            return res;
10891        }
10892
10893        final void serviceError() {
10894            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10895            handleServiceError();
10896            handleReturnCode();
10897        }
10898
10899        abstract void handleStartCopy() throws RemoteException;
10900        abstract void handleServiceError();
10901        abstract void handleReturnCode();
10902    }
10903
10904    class MeasureParams extends HandlerParams {
10905        private final PackageStats mStats;
10906        private boolean mSuccess;
10907
10908        private final IPackageStatsObserver mObserver;
10909
10910        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10911            super(new UserHandle(stats.userHandle));
10912            mObserver = observer;
10913            mStats = stats;
10914        }
10915
10916        @Override
10917        public String toString() {
10918            return "MeasureParams{"
10919                + Integer.toHexString(System.identityHashCode(this))
10920                + " " + mStats.packageName + "}";
10921        }
10922
10923        @Override
10924        void handleStartCopy() throws RemoteException {
10925            synchronized (mInstallLock) {
10926                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10927            }
10928
10929            if (mSuccess) {
10930                final boolean mounted;
10931                if (Environment.isExternalStorageEmulated()) {
10932                    mounted = true;
10933                } else {
10934                    final String status = Environment.getExternalStorageState();
10935                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10936                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10937                }
10938
10939                if (mounted) {
10940                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10941
10942                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10943                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10944
10945                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10946                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10947
10948                    // Always subtract cache size, since it's a subdirectory
10949                    mStats.externalDataSize -= mStats.externalCacheSize;
10950
10951                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10952                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10953
10954                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10955                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10956                }
10957            }
10958        }
10959
10960        @Override
10961        void handleReturnCode() {
10962            if (mObserver != null) {
10963                try {
10964                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10965                } catch (RemoteException e) {
10966                    Slog.i(TAG, "Observer no longer exists.");
10967                }
10968            }
10969        }
10970
10971        @Override
10972        void handleServiceError() {
10973            Slog.e(TAG, "Could not measure application " + mStats.packageName
10974                            + " external storage");
10975        }
10976    }
10977
10978    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10979            throws RemoteException {
10980        long result = 0;
10981        for (File path : paths) {
10982            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10983        }
10984        return result;
10985    }
10986
10987    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10988        for (File path : paths) {
10989            try {
10990                mcs.clearDirectory(path.getAbsolutePath());
10991            } catch (RemoteException e) {
10992            }
10993        }
10994    }
10995
10996    static class OriginInfo {
10997        /**
10998         * Location where install is coming from, before it has been
10999         * copied/renamed into place. This could be a single monolithic APK
11000         * file, or a cluster directory. This location may be untrusted.
11001         */
11002        final File file;
11003        final String cid;
11004
11005        /**
11006         * Flag indicating that {@link #file} or {@link #cid} has already been
11007         * staged, meaning downstream users don't need to defensively copy the
11008         * contents.
11009         */
11010        final boolean staged;
11011
11012        /**
11013         * Flag indicating that {@link #file} or {@link #cid} is an already
11014         * installed app that is being moved.
11015         */
11016        final boolean existing;
11017
11018        final String resolvedPath;
11019        final File resolvedFile;
11020
11021        static OriginInfo fromNothing() {
11022            return new OriginInfo(null, null, false, false);
11023        }
11024
11025        static OriginInfo fromUntrustedFile(File file) {
11026            return new OriginInfo(file, null, false, false);
11027        }
11028
11029        static OriginInfo fromExistingFile(File file) {
11030            return new OriginInfo(file, null, false, true);
11031        }
11032
11033        static OriginInfo fromStagedFile(File file) {
11034            return new OriginInfo(file, null, true, false);
11035        }
11036
11037        static OriginInfo fromStagedContainer(String cid) {
11038            return new OriginInfo(null, cid, true, false);
11039        }
11040
11041        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11042            this.file = file;
11043            this.cid = cid;
11044            this.staged = staged;
11045            this.existing = existing;
11046
11047            if (cid != null) {
11048                resolvedPath = PackageHelper.getSdDir(cid);
11049                resolvedFile = new File(resolvedPath);
11050            } else if (file != null) {
11051                resolvedPath = file.getAbsolutePath();
11052                resolvedFile = file;
11053            } else {
11054                resolvedPath = null;
11055                resolvedFile = null;
11056            }
11057        }
11058    }
11059
11060    static class MoveInfo {
11061        final int moveId;
11062        final String fromUuid;
11063        final String toUuid;
11064        final String packageName;
11065        final String dataAppName;
11066        final int appId;
11067        final String seinfo;
11068        final int targetSdkVersion;
11069
11070        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11071                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11072            this.moveId = moveId;
11073            this.fromUuid = fromUuid;
11074            this.toUuid = toUuid;
11075            this.packageName = packageName;
11076            this.dataAppName = dataAppName;
11077            this.appId = appId;
11078            this.seinfo = seinfo;
11079            this.targetSdkVersion = targetSdkVersion;
11080        }
11081    }
11082
11083    class InstallParams extends HandlerParams {
11084        final OriginInfo origin;
11085        final MoveInfo move;
11086        final IPackageInstallObserver2 observer;
11087        int installFlags;
11088        final String installerPackageName;
11089        final String volumeUuid;
11090        final VerificationParams verificationParams;
11091        private InstallArgs mArgs;
11092        private int mRet;
11093        final String packageAbiOverride;
11094        final String[] grantedRuntimePermissions;
11095
11096        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11097                int installFlags, String installerPackageName, String volumeUuid,
11098                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11099                String[] grantedPermissions) {
11100            super(user);
11101            this.origin = origin;
11102            this.move = move;
11103            this.observer = observer;
11104            this.installFlags = installFlags;
11105            this.installerPackageName = installerPackageName;
11106            this.volumeUuid = volumeUuid;
11107            this.verificationParams = verificationParams;
11108            this.packageAbiOverride = packageAbiOverride;
11109            this.grantedRuntimePermissions = grantedPermissions;
11110        }
11111
11112        @Override
11113        public String toString() {
11114            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11115                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11116        }
11117
11118        private int installLocationPolicy(PackageInfoLite pkgLite) {
11119            String packageName = pkgLite.packageName;
11120            int installLocation = pkgLite.installLocation;
11121            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11122            // reader
11123            synchronized (mPackages) {
11124                PackageParser.Package pkg = mPackages.get(packageName);
11125                if (pkg != null) {
11126                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11127                        // Check for downgrading.
11128                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11129                            try {
11130                                checkDowngrade(pkg, pkgLite);
11131                            } catch (PackageManagerException e) {
11132                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11133                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11134                            }
11135                        }
11136                        // Check for updated system application.
11137                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11138                            if (onSd) {
11139                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11140                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11141                            }
11142                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11143                        } else {
11144                            if (onSd) {
11145                                // Install flag overrides everything.
11146                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11147                            }
11148                            // If current upgrade specifies particular preference
11149                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11150                                // Application explicitly specified internal.
11151                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11152                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11153                                // App explictly prefers external. Let policy decide
11154                            } else {
11155                                // Prefer previous location
11156                                if (isExternal(pkg)) {
11157                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11158                                }
11159                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11160                            }
11161                        }
11162                    } else {
11163                        // Invalid install. Return error code
11164                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11165                    }
11166                }
11167            }
11168            // All the special cases have been taken care of.
11169            // Return result based on recommended install location.
11170            if (onSd) {
11171                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11172            }
11173            return pkgLite.recommendedInstallLocation;
11174        }
11175
11176        /*
11177         * Invoke remote method to get package information and install
11178         * location values. Override install location based on default
11179         * policy if needed and then create install arguments based
11180         * on the install location.
11181         */
11182        public void handleStartCopy() throws RemoteException {
11183            int ret = PackageManager.INSTALL_SUCCEEDED;
11184
11185            // If we're already staged, we've firmly committed to an install location
11186            if (origin.staged) {
11187                if (origin.file != null) {
11188                    installFlags |= PackageManager.INSTALL_INTERNAL;
11189                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11190                } else if (origin.cid != null) {
11191                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11192                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11193                } else {
11194                    throw new IllegalStateException("Invalid stage location");
11195                }
11196            }
11197
11198            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11199            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11200            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11201            PackageInfoLite pkgLite = null;
11202
11203            if (onInt && onSd) {
11204                // Check if both bits are set.
11205                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11206                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11207            } else if (onSd && ephemeral) {
11208                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11209                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11210            } else {
11211                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11212                        packageAbiOverride);
11213
11214                if (DEBUG_EPHEMERAL && ephemeral) {
11215                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11216                }
11217
11218                /*
11219                 * If we have too little free space, try to free cache
11220                 * before giving up.
11221                 */
11222                if (!origin.staged && pkgLite.recommendedInstallLocation
11223                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11224                    // TODO: focus freeing disk space on the target device
11225                    final StorageManager storage = StorageManager.from(mContext);
11226                    final long lowThreshold = storage.getStorageLowBytes(
11227                            Environment.getDataDirectory());
11228
11229                    final long sizeBytes = mContainerService.calculateInstalledSize(
11230                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11231
11232                    try {
11233                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11234                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11235                                installFlags, packageAbiOverride);
11236                    } catch (InstallerException e) {
11237                        Slog.w(TAG, "Failed to free cache", e);
11238                    }
11239
11240                    /*
11241                     * The cache free must have deleted the file we
11242                     * downloaded to install.
11243                     *
11244                     * TODO: fix the "freeCache" call to not delete
11245                     *       the file we care about.
11246                     */
11247                    if (pkgLite.recommendedInstallLocation
11248                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11249                        pkgLite.recommendedInstallLocation
11250                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11251                    }
11252                }
11253            }
11254
11255            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11256                int loc = pkgLite.recommendedInstallLocation;
11257                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11258                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11259                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11260                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11261                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11262                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11263                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11264                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11265                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11266                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11267                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11268                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11269                } else {
11270                    // Override with defaults if needed.
11271                    loc = installLocationPolicy(pkgLite);
11272                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11273                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11274                    } else if (!onSd && !onInt) {
11275                        // Override install location with flags
11276                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11277                            // Set the flag to install on external media.
11278                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11279                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11280                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11281                            if (DEBUG_EPHEMERAL) {
11282                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11283                            }
11284                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11285                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11286                                    |PackageManager.INSTALL_INTERNAL);
11287                        } else {
11288                            // Make sure the flag for installing on external
11289                            // media is unset
11290                            installFlags |= PackageManager.INSTALL_INTERNAL;
11291                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11292                        }
11293                    }
11294                }
11295            }
11296
11297            final InstallArgs args = createInstallArgs(this);
11298            mArgs = args;
11299
11300            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11301                // TODO: http://b/22976637
11302                // Apps installed for "all" users use the device owner to verify the app
11303                UserHandle verifierUser = getUser();
11304                if (verifierUser == UserHandle.ALL) {
11305                    verifierUser = UserHandle.SYSTEM;
11306                }
11307
11308                /*
11309                 * Determine if we have any installed package verifiers. If we
11310                 * do, then we'll defer to them to verify the packages.
11311                 */
11312                final int requiredUid = mRequiredVerifierPackage == null ? -1
11313                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11314                                verifierUser.getIdentifier());
11315                if (!origin.existing && requiredUid != -1
11316                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11317                    final Intent verification = new Intent(
11318                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11319                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11320                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11321                            PACKAGE_MIME_TYPE);
11322                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11323
11324                    // Query all live verifiers based on current user state
11325                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11326                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11327
11328                    if (DEBUG_VERIFY) {
11329                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11330                                + verification.toString() + " with " + pkgLite.verifiers.length
11331                                + " optional verifiers");
11332                    }
11333
11334                    final int verificationId = mPendingVerificationToken++;
11335
11336                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11337
11338                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11339                            installerPackageName);
11340
11341                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11342                            installFlags);
11343
11344                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11345                            pkgLite.packageName);
11346
11347                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11348                            pkgLite.versionCode);
11349
11350                    if (verificationParams != null) {
11351                        if (verificationParams.getVerificationURI() != null) {
11352                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11353                                 verificationParams.getVerificationURI());
11354                        }
11355                        if (verificationParams.getOriginatingURI() != null) {
11356                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11357                                  verificationParams.getOriginatingURI());
11358                        }
11359                        if (verificationParams.getReferrer() != null) {
11360                            verification.putExtra(Intent.EXTRA_REFERRER,
11361                                  verificationParams.getReferrer());
11362                        }
11363                        if (verificationParams.getOriginatingUid() >= 0) {
11364                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11365                                  verificationParams.getOriginatingUid());
11366                        }
11367                        if (verificationParams.getInstallerUid() >= 0) {
11368                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11369                                  verificationParams.getInstallerUid());
11370                        }
11371                    }
11372
11373                    final PackageVerificationState verificationState = new PackageVerificationState(
11374                            requiredUid, args);
11375
11376                    mPendingVerification.append(verificationId, verificationState);
11377
11378                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11379                            receivers, verificationState);
11380
11381                    /*
11382                     * If any sufficient verifiers were listed in the package
11383                     * manifest, attempt to ask them.
11384                     */
11385                    if (sufficientVerifiers != null) {
11386                        final int N = sufficientVerifiers.size();
11387                        if (N == 0) {
11388                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11389                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11390                        } else {
11391                            for (int i = 0; i < N; i++) {
11392                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11393
11394                                final Intent sufficientIntent = new Intent(verification);
11395                                sufficientIntent.setComponent(verifierComponent);
11396                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11397                            }
11398                        }
11399                    }
11400
11401                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11402                            mRequiredVerifierPackage, receivers);
11403                    if (ret == PackageManager.INSTALL_SUCCEEDED
11404                            && mRequiredVerifierPackage != null) {
11405                        Trace.asyncTraceBegin(
11406                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11407                        /*
11408                         * Send the intent to the required verification agent,
11409                         * but only start the verification timeout after the
11410                         * target BroadcastReceivers have run.
11411                         */
11412                        verification.setComponent(requiredVerifierComponent);
11413                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11414                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11415                                new BroadcastReceiver() {
11416                                    @Override
11417                                    public void onReceive(Context context, Intent intent) {
11418                                        final Message msg = mHandler
11419                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11420                                        msg.arg1 = verificationId;
11421                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11422                                    }
11423                                }, null, 0, null, null);
11424
11425                        /*
11426                         * We don't want the copy to proceed until verification
11427                         * succeeds, so null out this field.
11428                         */
11429                        mArgs = null;
11430                    }
11431                } else {
11432                    /*
11433                     * No package verification is enabled, so immediately start
11434                     * the remote call to initiate copy using temporary file.
11435                     */
11436                    ret = args.copyApk(mContainerService, true);
11437                }
11438            }
11439
11440            mRet = ret;
11441        }
11442
11443        @Override
11444        void handleReturnCode() {
11445            // If mArgs is null, then MCS couldn't be reached. When it
11446            // reconnects, it will try again to install. At that point, this
11447            // will succeed.
11448            if (mArgs != null) {
11449                processPendingInstall(mArgs, mRet);
11450            }
11451        }
11452
11453        @Override
11454        void handleServiceError() {
11455            mArgs = createInstallArgs(this);
11456            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11457        }
11458
11459        public boolean isForwardLocked() {
11460            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11461        }
11462    }
11463
11464    /**
11465     * Used during creation of InstallArgs
11466     *
11467     * @param installFlags package installation flags
11468     * @return true if should be installed on external storage
11469     */
11470    private static boolean installOnExternalAsec(int installFlags) {
11471        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11472            return false;
11473        }
11474        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11475            return true;
11476        }
11477        return false;
11478    }
11479
11480    /**
11481     * Used during creation of InstallArgs
11482     *
11483     * @param installFlags package installation flags
11484     * @return true if should be installed as forward locked
11485     */
11486    private static boolean installForwardLocked(int installFlags) {
11487        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11488    }
11489
11490    private InstallArgs createInstallArgs(InstallParams params) {
11491        if (params.move != null) {
11492            return new MoveInstallArgs(params);
11493        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11494            return new AsecInstallArgs(params);
11495        } else {
11496            return new FileInstallArgs(params);
11497        }
11498    }
11499
11500    /**
11501     * Create args that describe an existing installed package. Typically used
11502     * when cleaning up old installs, or used as a move source.
11503     */
11504    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11505            String resourcePath, String[] instructionSets) {
11506        final boolean isInAsec;
11507        if (installOnExternalAsec(installFlags)) {
11508            /* Apps on SD card are always in ASEC containers. */
11509            isInAsec = true;
11510        } else if (installForwardLocked(installFlags)
11511                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11512            /*
11513             * Forward-locked apps are only in ASEC containers if they're the
11514             * new style
11515             */
11516            isInAsec = true;
11517        } else {
11518            isInAsec = false;
11519        }
11520
11521        if (isInAsec) {
11522            return new AsecInstallArgs(codePath, instructionSets,
11523                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11524        } else {
11525            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11526        }
11527    }
11528
11529    static abstract class InstallArgs {
11530        /** @see InstallParams#origin */
11531        final OriginInfo origin;
11532        /** @see InstallParams#move */
11533        final MoveInfo move;
11534
11535        final IPackageInstallObserver2 observer;
11536        // Always refers to PackageManager flags only
11537        final int installFlags;
11538        final String installerPackageName;
11539        final String volumeUuid;
11540        final UserHandle user;
11541        final String abiOverride;
11542        final String[] installGrantPermissions;
11543        /** If non-null, drop an async trace when the install completes */
11544        final String traceMethod;
11545        final int traceCookie;
11546
11547        // The list of instruction sets supported by this app. This is currently
11548        // only used during the rmdex() phase to clean up resources. We can get rid of this
11549        // if we move dex files under the common app path.
11550        /* nullable */ String[] instructionSets;
11551
11552        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11553                int installFlags, String installerPackageName, String volumeUuid,
11554                UserHandle user, String[] instructionSets,
11555                String abiOverride, String[] installGrantPermissions,
11556                String traceMethod, int traceCookie) {
11557            this.origin = origin;
11558            this.move = move;
11559            this.installFlags = installFlags;
11560            this.observer = observer;
11561            this.installerPackageName = installerPackageName;
11562            this.volumeUuid = volumeUuid;
11563            this.user = user;
11564            this.instructionSets = instructionSets;
11565            this.abiOverride = abiOverride;
11566            this.installGrantPermissions = installGrantPermissions;
11567            this.traceMethod = traceMethod;
11568            this.traceCookie = traceCookie;
11569        }
11570
11571        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11572        abstract int doPreInstall(int status);
11573
11574        /**
11575         * Rename package into final resting place. All paths on the given
11576         * scanned package should be updated to reflect the rename.
11577         */
11578        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11579        abstract int doPostInstall(int status, int uid);
11580
11581        /** @see PackageSettingBase#codePathString */
11582        abstract String getCodePath();
11583        /** @see PackageSettingBase#resourcePathString */
11584        abstract String getResourcePath();
11585
11586        // Need installer lock especially for dex file removal.
11587        abstract void cleanUpResourcesLI();
11588        abstract boolean doPostDeleteLI(boolean delete);
11589
11590        /**
11591         * Called before the source arguments are copied. This is used mostly
11592         * for MoveParams when it needs to read the source file to put it in the
11593         * destination.
11594         */
11595        int doPreCopy() {
11596            return PackageManager.INSTALL_SUCCEEDED;
11597        }
11598
11599        /**
11600         * Called after the source arguments are copied. This is used mostly for
11601         * MoveParams when it needs to read the source file to put it in the
11602         * destination.
11603         *
11604         * @return
11605         */
11606        int doPostCopy(int uid) {
11607            return PackageManager.INSTALL_SUCCEEDED;
11608        }
11609
11610        protected boolean isFwdLocked() {
11611            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11612        }
11613
11614        protected boolean isExternalAsec() {
11615            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11616        }
11617
11618        protected boolean isEphemeral() {
11619            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11620        }
11621
11622        UserHandle getUser() {
11623            return user;
11624        }
11625    }
11626
11627    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11628        if (!allCodePaths.isEmpty()) {
11629            if (instructionSets == null) {
11630                throw new IllegalStateException("instructionSet == null");
11631            }
11632            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11633            for (String codePath : allCodePaths) {
11634                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11635                    try {
11636                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11637                    } catch (InstallerException ignored) {
11638                    }
11639                }
11640            }
11641        }
11642    }
11643
11644    /**
11645     * Logic to handle installation of non-ASEC applications, including copying
11646     * and renaming logic.
11647     */
11648    class FileInstallArgs extends InstallArgs {
11649        private File codeFile;
11650        private File resourceFile;
11651
11652        // Example topology:
11653        // /data/app/com.example/base.apk
11654        // /data/app/com.example/split_foo.apk
11655        // /data/app/com.example/lib/arm/libfoo.so
11656        // /data/app/com.example/lib/arm64/libfoo.so
11657        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11658
11659        /** New install */
11660        FileInstallArgs(InstallParams params) {
11661            super(params.origin, params.move, params.observer, params.installFlags,
11662                    params.installerPackageName, params.volumeUuid,
11663                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11664                    params.grantedRuntimePermissions,
11665                    params.traceMethod, params.traceCookie);
11666            if (isFwdLocked()) {
11667                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11668            }
11669        }
11670
11671        /** Existing install */
11672        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11673            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11674                    null, null, null, 0);
11675            this.codeFile = (codePath != null) ? new File(codePath) : null;
11676            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11677        }
11678
11679        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11680            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11681            try {
11682                return doCopyApk(imcs, temp);
11683            } finally {
11684                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11685            }
11686        }
11687
11688        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11689            if (origin.staged) {
11690                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11691                codeFile = origin.file;
11692                resourceFile = origin.file;
11693                return PackageManager.INSTALL_SUCCEEDED;
11694            }
11695
11696            try {
11697                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11698                final File tempDir =
11699                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11700                codeFile = tempDir;
11701                resourceFile = tempDir;
11702            } catch (IOException e) {
11703                Slog.w(TAG, "Failed to create copy file: " + e);
11704                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11705            }
11706
11707            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11708                @Override
11709                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11710                    if (!FileUtils.isValidExtFilename(name)) {
11711                        throw new IllegalArgumentException("Invalid filename: " + name);
11712                    }
11713                    try {
11714                        final File file = new File(codeFile, name);
11715                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11716                                O_RDWR | O_CREAT, 0644);
11717                        Os.chmod(file.getAbsolutePath(), 0644);
11718                        return new ParcelFileDescriptor(fd);
11719                    } catch (ErrnoException e) {
11720                        throw new RemoteException("Failed to open: " + e.getMessage());
11721                    }
11722                }
11723            };
11724
11725            int ret = PackageManager.INSTALL_SUCCEEDED;
11726            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11727            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11728                Slog.e(TAG, "Failed to copy package");
11729                return ret;
11730            }
11731
11732            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11733            NativeLibraryHelper.Handle handle = null;
11734            try {
11735                handle = NativeLibraryHelper.Handle.create(codeFile);
11736                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11737                        abiOverride);
11738            } catch (IOException e) {
11739                Slog.e(TAG, "Copying native libraries failed", e);
11740                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11741            } finally {
11742                IoUtils.closeQuietly(handle);
11743            }
11744
11745            return ret;
11746        }
11747
11748        int doPreInstall(int status) {
11749            if (status != PackageManager.INSTALL_SUCCEEDED) {
11750                cleanUp();
11751            }
11752            return status;
11753        }
11754
11755        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11756            if (status != PackageManager.INSTALL_SUCCEEDED) {
11757                cleanUp();
11758                return false;
11759            }
11760
11761            final File targetDir = codeFile.getParentFile();
11762            final File beforeCodeFile = codeFile;
11763            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11764
11765            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11766            try {
11767                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11768            } catch (ErrnoException e) {
11769                Slog.w(TAG, "Failed to rename", e);
11770                return false;
11771            }
11772
11773            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11774                Slog.w(TAG, "Failed to restorecon");
11775                return false;
11776            }
11777
11778            // Reflect the rename internally
11779            codeFile = afterCodeFile;
11780            resourceFile = afterCodeFile;
11781
11782            // Reflect the rename in scanned details
11783            pkg.codePath = afterCodeFile.getAbsolutePath();
11784            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11785                    pkg.baseCodePath);
11786            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11787                    pkg.splitCodePaths);
11788
11789            // Reflect the rename in app info
11790            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11791            pkg.applicationInfo.setCodePath(pkg.codePath);
11792            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11793            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11794            pkg.applicationInfo.setResourcePath(pkg.codePath);
11795            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11796            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11797
11798            return true;
11799        }
11800
11801        int doPostInstall(int status, int uid) {
11802            if (status != PackageManager.INSTALL_SUCCEEDED) {
11803                cleanUp();
11804            }
11805            return status;
11806        }
11807
11808        @Override
11809        String getCodePath() {
11810            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11811        }
11812
11813        @Override
11814        String getResourcePath() {
11815            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11816        }
11817
11818        private boolean cleanUp() {
11819            if (codeFile == null || !codeFile.exists()) {
11820                return false;
11821            }
11822
11823            removeCodePathLI(codeFile);
11824
11825            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11826                resourceFile.delete();
11827            }
11828
11829            return true;
11830        }
11831
11832        void cleanUpResourcesLI() {
11833            // Try enumerating all code paths before deleting
11834            List<String> allCodePaths = Collections.EMPTY_LIST;
11835            if (codeFile != null && codeFile.exists()) {
11836                try {
11837                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11838                    allCodePaths = pkg.getAllCodePaths();
11839                } catch (PackageParserException e) {
11840                    // Ignored; we tried our best
11841                }
11842            }
11843
11844            cleanUp();
11845            removeDexFiles(allCodePaths, instructionSets);
11846        }
11847
11848        boolean doPostDeleteLI(boolean delete) {
11849            // XXX err, shouldn't we respect the delete flag?
11850            cleanUpResourcesLI();
11851            return true;
11852        }
11853    }
11854
11855    private boolean isAsecExternal(String cid) {
11856        final String asecPath = PackageHelper.getSdFilesystem(cid);
11857        return !asecPath.startsWith(mAsecInternalPath);
11858    }
11859
11860    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11861            PackageManagerException {
11862        if (copyRet < 0) {
11863            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11864                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11865                throw new PackageManagerException(copyRet, message);
11866            }
11867        }
11868    }
11869
11870    /**
11871     * Extract the MountService "container ID" from the full code path of an
11872     * .apk.
11873     */
11874    static String cidFromCodePath(String fullCodePath) {
11875        int eidx = fullCodePath.lastIndexOf("/");
11876        String subStr1 = fullCodePath.substring(0, eidx);
11877        int sidx = subStr1.lastIndexOf("/");
11878        return subStr1.substring(sidx+1, eidx);
11879    }
11880
11881    /**
11882     * Logic to handle installation of ASEC applications, including copying and
11883     * renaming logic.
11884     */
11885    class AsecInstallArgs extends InstallArgs {
11886        static final String RES_FILE_NAME = "pkg.apk";
11887        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11888
11889        String cid;
11890        String packagePath;
11891        String resourcePath;
11892
11893        /** New install */
11894        AsecInstallArgs(InstallParams params) {
11895            super(params.origin, params.move, params.observer, params.installFlags,
11896                    params.installerPackageName, params.volumeUuid,
11897                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11898                    params.grantedRuntimePermissions,
11899                    params.traceMethod, params.traceCookie);
11900        }
11901
11902        /** Existing install */
11903        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11904                        boolean isExternal, boolean isForwardLocked) {
11905            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11906                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11907                    instructionSets, null, null, null, 0);
11908            // Hackily pretend we're still looking at a full code path
11909            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11910                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11911            }
11912
11913            // Extract cid from fullCodePath
11914            int eidx = fullCodePath.lastIndexOf("/");
11915            String subStr1 = fullCodePath.substring(0, eidx);
11916            int sidx = subStr1.lastIndexOf("/");
11917            cid = subStr1.substring(sidx+1, eidx);
11918            setMountPath(subStr1);
11919        }
11920
11921        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11922            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11923                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11924                    instructionSets, null, null, null, 0);
11925            this.cid = cid;
11926            setMountPath(PackageHelper.getSdDir(cid));
11927        }
11928
11929        void createCopyFile() {
11930            cid = mInstallerService.allocateExternalStageCidLegacy();
11931        }
11932
11933        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11934            if (origin.staged && origin.cid != null) {
11935                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11936                cid = origin.cid;
11937                setMountPath(PackageHelper.getSdDir(cid));
11938                return PackageManager.INSTALL_SUCCEEDED;
11939            }
11940
11941            if (temp) {
11942                createCopyFile();
11943            } else {
11944                /*
11945                 * Pre-emptively destroy the container since it's destroyed if
11946                 * copying fails due to it existing anyway.
11947                 */
11948                PackageHelper.destroySdDir(cid);
11949            }
11950
11951            final String newMountPath = imcs.copyPackageToContainer(
11952                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11953                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11954
11955            if (newMountPath != null) {
11956                setMountPath(newMountPath);
11957                return PackageManager.INSTALL_SUCCEEDED;
11958            } else {
11959                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11960            }
11961        }
11962
11963        @Override
11964        String getCodePath() {
11965            return packagePath;
11966        }
11967
11968        @Override
11969        String getResourcePath() {
11970            return resourcePath;
11971        }
11972
11973        int doPreInstall(int status) {
11974            if (status != PackageManager.INSTALL_SUCCEEDED) {
11975                // Destroy container
11976                PackageHelper.destroySdDir(cid);
11977            } else {
11978                boolean mounted = PackageHelper.isContainerMounted(cid);
11979                if (!mounted) {
11980                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11981                            Process.SYSTEM_UID);
11982                    if (newMountPath != null) {
11983                        setMountPath(newMountPath);
11984                    } else {
11985                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11986                    }
11987                }
11988            }
11989            return status;
11990        }
11991
11992        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11993            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11994            String newMountPath = null;
11995            if (PackageHelper.isContainerMounted(cid)) {
11996                // Unmount the container
11997                if (!PackageHelper.unMountSdDir(cid)) {
11998                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11999                    return false;
12000                }
12001            }
12002            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12003                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12004                        " which might be stale. Will try to clean up.");
12005                // Clean up the stale container and proceed to recreate.
12006                if (!PackageHelper.destroySdDir(newCacheId)) {
12007                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12008                    return false;
12009                }
12010                // Successfully cleaned up stale container. Try to rename again.
12011                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12012                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12013                            + " inspite of cleaning it up.");
12014                    return false;
12015                }
12016            }
12017            if (!PackageHelper.isContainerMounted(newCacheId)) {
12018                Slog.w(TAG, "Mounting container " + newCacheId);
12019                newMountPath = PackageHelper.mountSdDir(newCacheId,
12020                        getEncryptKey(), Process.SYSTEM_UID);
12021            } else {
12022                newMountPath = PackageHelper.getSdDir(newCacheId);
12023            }
12024            if (newMountPath == null) {
12025                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12026                return false;
12027            }
12028            Log.i(TAG, "Succesfully renamed " + cid +
12029                    " to " + newCacheId +
12030                    " at new path: " + newMountPath);
12031            cid = newCacheId;
12032
12033            final File beforeCodeFile = new File(packagePath);
12034            setMountPath(newMountPath);
12035            final File afterCodeFile = new File(packagePath);
12036
12037            // Reflect the rename in scanned details
12038            pkg.codePath = afterCodeFile.getAbsolutePath();
12039            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12040                    pkg.baseCodePath);
12041            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12042                    pkg.splitCodePaths);
12043
12044            // Reflect the rename in app info
12045            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12046            pkg.applicationInfo.setCodePath(pkg.codePath);
12047            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12048            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12049            pkg.applicationInfo.setResourcePath(pkg.codePath);
12050            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12051            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12052
12053            return true;
12054        }
12055
12056        private void setMountPath(String mountPath) {
12057            final File mountFile = new File(mountPath);
12058
12059            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12060            if (monolithicFile.exists()) {
12061                packagePath = monolithicFile.getAbsolutePath();
12062                if (isFwdLocked()) {
12063                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12064                } else {
12065                    resourcePath = packagePath;
12066                }
12067            } else {
12068                packagePath = mountFile.getAbsolutePath();
12069                resourcePath = packagePath;
12070            }
12071        }
12072
12073        int doPostInstall(int status, int uid) {
12074            if (status != PackageManager.INSTALL_SUCCEEDED) {
12075                cleanUp();
12076            } else {
12077                final int groupOwner;
12078                final String protectedFile;
12079                if (isFwdLocked()) {
12080                    groupOwner = UserHandle.getSharedAppGid(uid);
12081                    protectedFile = RES_FILE_NAME;
12082                } else {
12083                    groupOwner = -1;
12084                    protectedFile = null;
12085                }
12086
12087                if (uid < Process.FIRST_APPLICATION_UID
12088                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12089                    Slog.e(TAG, "Failed to finalize " + cid);
12090                    PackageHelper.destroySdDir(cid);
12091                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12092                }
12093
12094                boolean mounted = PackageHelper.isContainerMounted(cid);
12095                if (!mounted) {
12096                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12097                }
12098            }
12099            return status;
12100        }
12101
12102        private void cleanUp() {
12103            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12104
12105            // Destroy secure container
12106            PackageHelper.destroySdDir(cid);
12107        }
12108
12109        private List<String> getAllCodePaths() {
12110            final File codeFile = new File(getCodePath());
12111            if (codeFile != null && codeFile.exists()) {
12112                try {
12113                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12114                    return pkg.getAllCodePaths();
12115                } catch (PackageParserException e) {
12116                    // Ignored; we tried our best
12117                }
12118            }
12119            return Collections.EMPTY_LIST;
12120        }
12121
12122        void cleanUpResourcesLI() {
12123            // Enumerate all code paths before deleting
12124            cleanUpResourcesLI(getAllCodePaths());
12125        }
12126
12127        private void cleanUpResourcesLI(List<String> allCodePaths) {
12128            cleanUp();
12129            removeDexFiles(allCodePaths, instructionSets);
12130        }
12131
12132        String getPackageName() {
12133            return getAsecPackageName(cid);
12134        }
12135
12136        boolean doPostDeleteLI(boolean delete) {
12137            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12138            final List<String> allCodePaths = getAllCodePaths();
12139            boolean mounted = PackageHelper.isContainerMounted(cid);
12140            if (mounted) {
12141                // Unmount first
12142                if (PackageHelper.unMountSdDir(cid)) {
12143                    mounted = false;
12144                }
12145            }
12146            if (!mounted && delete) {
12147                cleanUpResourcesLI(allCodePaths);
12148            }
12149            return !mounted;
12150        }
12151
12152        @Override
12153        int doPreCopy() {
12154            if (isFwdLocked()) {
12155                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12156                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12157                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12158                }
12159            }
12160
12161            return PackageManager.INSTALL_SUCCEEDED;
12162        }
12163
12164        @Override
12165        int doPostCopy(int uid) {
12166            if (isFwdLocked()) {
12167                if (uid < Process.FIRST_APPLICATION_UID
12168                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12169                                RES_FILE_NAME)) {
12170                    Slog.e(TAG, "Failed to finalize " + cid);
12171                    PackageHelper.destroySdDir(cid);
12172                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12173                }
12174            }
12175
12176            return PackageManager.INSTALL_SUCCEEDED;
12177        }
12178    }
12179
12180    /**
12181     * Logic to handle movement of existing installed applications.
12182     */
12183    class MoveInstallArgs extends InstallArgs {
12184        private File codeFile;
12185        private File resourceFile;
12186
12187        /** New install */
12188        MoveInstallArgs(InstallParams params) {
12189            super(params.origin, params.move, params.observer, params.installFlags,
12190                    params.installerPackageName, params.volumeUuid,
12191                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12192                    params.grantedRuntimePermissions,
12193                    params.traceMethod, params.traceCookie);
12194        }
12195
12196        int copyApk(IMediaContainerService imcs, boolean temp) {
12197            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12198                    + move.fromUuid + " to " + move.toUuid);
12199            synchronized (mInstaller) {
12200                try {
12201                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12202                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12203                } catch (InstallerException e) {
12204                    Slog.w(TAG, "Failed to move app", e);
12205                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12206                }
12207            }
12208
12209            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12210            resourceFile = codeFile;
12211            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12212
12213            return PackageManager.INSTALL_SUCCEEDED;
12214        }
12215
12216        int doPreInstall(int status) {
12217            if (status != PackageManager.INSTALL_SUCCEEDED) {
12218                cleanUp(move.toUuid);
12219            }
12220            return status;
12221        }
12222
12223        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12224            if (status != PackageManager.INSTALL_SUCCEEDED) {
12225                cleanUp(move.toUuid);
12226                return false;
12227            }
12228
12229            // Reflect the move in app info
12230            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12231            pkg.applicationInfo.setCodePath(pkg.codePath);
12232            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12233            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12234            pkg.applicationInfo.setResourcePath(pkg.codePath);
12235            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12236            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12237
12238            return true;
12239        }
12240
12241        int doPostInstall(int status, int uid) {
12242            if (status == PackageManager.INSTALL_SUCCEEDED) {
12243                cleanUp(move.fromUuid);
12244            } else {
12245                cleanUp(move.toUuid);
12246            }
12247            return status;
12248        }
12249
12250        @Override
12251        String getCodePath() {
12252            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12253        }
12254
12255        @Override
12256        String getResourcePath() {
12257            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12258        }
12259
12260        private boolean cleanUp(String volumeUuid) {
12261            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12262                    move.dataAppName);
12263            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12264            synchronized (mInstallLock) {
12265                // Clean up both app data and code
12266                removeDataDirsLI(volumeUuid, move.packageName);
12267                removeCodePathLI(codeFile);
12268            }
12269            return true;
12270        }
12271
12272        void cleanUpResourcesLI() {
12273            throw new UnsupportedOperationException();
12274        }
12275
12276        boolean doPostDeleteLI(boolean delete) {
12277            throw new UnsupportedOperationException();
12278        }
12279    }
12280
12281    static String getAsecPackageName(String packageCid) {
12282        int idx = packageCid.lastIndexOf("-");
12283        if (idx == -1) {
12284            return packageCid;
12285        }
12286        return packageCid.substring(0, idx);
12287    }
12288
12289    // Utility method used to create code paths based on package name and available index.
12290    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12291        String idxStr = "";
12292        int idx = 1;
12293        // Fall back to default value of idx=1 if prefix is not
12294        // part of oldCodePath
12295        if (oldCodePath != null) {
12296            String subStr = oldCodePath;
12297            // Drop the suffix right away
12298            if (suffix != null && subStr.endsWith(suffix)) {
12299                subStr = subStr.substring(0, subStr.length() - suffix.length());
12300            }
12301            // If oldCodePath already contains prefix find out the
12302            // ending index to either increment or decrement.
12303            int sidx = subStr.lastIndexOf(prefix);
12304            if (sidx != -1) {
12305                subStr = subStr.substring(sidx + prefix.length());
12306                if (subStr != null) {
12307                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12308                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12309                    }
12310                    try {
12311                        idx = Integer.parseInt(subStr);
12312                        if (idx <= 1) {
12313                            idx++;
12314                        } else {
12315                            idx--;
12316                        }
12317                    } catch(NumberFormatException e) {
12318                    }
12319                }
12320            }
12321        }
12322        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12323        return prefix + idxStr;
12324    }
12325
12326    private File getNextCodePath(File targetDir, String packageName) {
12327        int suffix = 1;
12328        File result;
12329        do {
12330            result = new File(targetDir, packageName + "-" + suffix);
12331            suffix++;
12332        } while (result.exists());
12333        return result;
12334    }
12335
12336    // Utility method that returns the relative package path with respect
12337    // to the installation directory. Like say for /data/data/com.test-1.apk
12338    // string com.test-1 is returned.
12339    static String deriveCodePathName(String codePath) {
12340        if (codePath == null) {
12341            return null;
12342        }
12343        final File codeFile = new File(codePath);
12344        final String name = codeFile.getName();
12345        if (codeFile.isDirectory()) {
12346            return name;
12347        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12348            final int lastDot = name.lastIndexOf('.');
12349            return name.substring(0, lastDot);
12350        } else {
12351            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12352            return null;
12353        }
12354    }
12355
12356    static class PackageInstalledInfo {
12357        String name;
12358        int uid;
12359        // The set of users that originally had this package installed.
12360        int[] origUsers;
12361        // The set of users that now have this package installed.
12362        int[] newUsers;
12363        PackageParser.Package pkg;
12364        int returnCode;
12365        String returnMsg;
12366        PackageRemovedInfo removedInfo;
12367
12368        public void setError(int code, String msg) {
12369            returnCode = code;
12370            returnMsg = msg;
12371            Slog.w(TAG, msg);
12372        }
12373
12374        public void setError(String msg, PackageParserException e) {
12375            returnCode = e.error;
12376            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12377            Slog.w(TAG, msg, e);
12378        }
12379
12380        public void setError(String msg, PackageManagerException e) {
12381            returnCode = e.error;
12382            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12383            Slog.w(TAG, msg, e);
12384        }
12385
12386        // In some error cases we want to convey more info back to the observer
12387        String origPackage;
12388        String origPermission;
12389    }
12390
12391    /*
12392     * Install a non-existing package.
12393     */
12394    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12395            UserHandle user, String installerPackageName, String volumeUuid,
12396            PackageInstalledInfo res) {
12397        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12398
12399        // Remember this for later, in case we need to rollback this install
12400        String pkgName = pkg.packageName;
12401
12402        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12403        // TODO: b/23350563
12404        final boolean dataDirExists = Environment
12405                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12406
12407        synchronized(mPackages) {
12408            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12409                // A package with the same name is already installed, though
12410                // it has been renamed to an older name.  The package we
12411                // are trying to install should be installed as an update to
12412                // the existing one, but that has not been requested, so bail.
12413                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12414                        + " without first uninstalling package running as "
12415                        + mSettings.mRenamedPackages.get(pkgName));
12416                return;
12417            }
12418            if (mPackages.containsKey(pkgName)) {
12419                // Don't allow installation over an existing package with the same name.
12420                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12421                        + " without first uninstalling.");
12422                return;
12423            }
12424        }
12425
12426        try {
12427            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12428                    System.currentTimeMillis(), user);
12429
12430            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12431            prepareAppDataAfterInstall(newPackage);
12432
12433            // delete the partially installed application. the data directory will have to be
12434            // restored if it was already existing
12435            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12436                // remove package from internal structures.  Note that we want deletePackageX to
12437                // delete the package data and cache directories that it created in
12438                // scanPackageLocked, unless those directories existed before we even tried to
12439                // install.
12440                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12441                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12442                                res.removedInfo, true);
12443            }
12444
12445        } catch (PackageManagerException e) {
12446            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12447        }
12448
12449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12450    }
12451
12452    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12453        // Can't rotate keys during boot or if sharedUser.
12454        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12455                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12456            return false;
12457        }
12458        // app is using upgradeKeySets; make sure all are valid
12459        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12460        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12461        for (int i = 0; i < upgradeKeySets.length; i++) {
12462            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12463                Slog.wtf(TAG, "Package "
12464                         + (oldPs.name != null ? oldPs.name : "<null>")
12465                         + " contains upgrade-key-set reference to unknown key-set: "
12466                         + upgradeKeySets[i]
12467                         + " reverting to signatures check.");
12468                return false;
12469            }
12470        }
12471        return true;
12472    }
12473
12474    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12475        // Upgrade keysets are being used.  Determine if new package has a superset of the
12476        // required keys.
12477        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12478        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12479        for (int i = 0; i < upgradeKeySets.length; i++) {
12480            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12481            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12482                return true;
12483            }
12484        }
12485        return false;
12486    }
12487
12488    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12489            UserHandle user, String installerPackageName, String volumeUuid,
12490            PackageInstalledInfo res) {
12491        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12492
12493        final PackageParser.Package oldPackage;
12494        final String pkgName = pkg.packageName;
12495        final int[] allUsers;
12496        final boolean[] perUserInstalled;
12497
12498        // First find the old package info and check signatures
12499        synchronized(mPackages) {
12500            oldPackage = mPackages.get(pkgName);
12501            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12502            if (isEphemeral && !oldIsEphemeral) {
12503                // can't downgrade from full to ephemeral
12504                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12505                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12506                return;
12507            }
12508            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12509            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12510            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12511                if(!checkUpgradeKeySetLP(ps, pkg)) {
12512                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12513                            "New package not signed by keys specified by upgrade-keysets: "
12514                            + pkgName);
12515                    return;
12516                }
12517            } else {
12518                // default to original signature matching
12519                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12520                    != PackageManager.SIGNATURE_MATCH) {
12521                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12522                            "New package has a different signature: " + pkgName);
12523                    return;
12524                }
12525            }
12526
12527            // In case of rollback, remember per-user/profile install state
12528            allUsers = sUserManager.getUserIds();
12529            perUserInstalled = new boolean[allUsers.length];
12530            for (int i = 0; i < allUsers.length; i++) {
12531                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12532            }
12533        }
12534
12535        boolean sysPkg = (isSystemApp(oldPackage));
12536        if (sysPkg) {
12537            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12538                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12539        } else {
12540            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12541                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12542        }
12543    }
12544
12545    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12546            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12547            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12548            String volumeUuid, PackageInstalledInfo res) {
12549        String pkgName = deletedPackage.packageName;
12550        boolean deletedPkg = true;
12551        boolean updatedSettings = false;
12552
12553        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12554                + deletedPackage);
12555        long origUpdateTime;
12556        if (pkg.mExtras != null) {
12557            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12558        } else {
12559            origUpdateTime = 0;
12560        }
12561
12562        // First delete the existing package while retaining the data directory
12563        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12564                res.removedInfo, true)) {
12565            // If the existing package wasn't successfully deleted
12566            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12567            deletedPkg = false;
12568        } else {
12569            // Successfully deleted the old package; proceed with replace.
12570
12571            // If deleted package lived in a container, give users a chance to
12572            // relinquish resources before killing.
12573            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12574                if (DEBUG_INSTALL) {
12575                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12576                }
12577                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12578                final ArrayList<String> pkgList = new ArrayList<String>(1);
12579                pkgList.add(deletedPackage.applicationInfo.packageName);
12580                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12581            }
12582
12583            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12584            try {
12585                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12586                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12587                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12588                        perUserInstalled, res, user);
12589                prepareAppDataAfterInstall(newPackage);
12590                updatedSettings = true;
12591            } catch (PackageManagerException e) {
12592                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12593            }
12594        }
12595
12596        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12597            // remove package from internal structures.  Note that we want deletePackageX to
12598            // delete the package data and cache directories that it created in
12599            // scanPackageLocked, unless those directories existed before we even tried to
12600            // install.
12601            if(updatedSettings) {
12602                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12603                deletePackageLI(
12604                        pkgName, null, true, allUsers, perUserInstalled,
12605                        PackageManager.DELETE_KEEP_DATA,
12606                                res.removedInfo, true);
12607            }
12608            // Since we failed to install the new package we need to restore the old
12609            // package that we deleted.
12610            if (deletedPkg) {
12611                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12612                File restoreFile = new File(deletedPackage.codePath);
12613                // Parse old package
12614                boolean oldExternal = isExternal(deletedPackage);
12615                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12616                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12617                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12618                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12619                try {
12620                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12621                            null);
12622                } catch (PackageManagerException e) {
12623                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12624                            + e.getMessage());
12625                    return;
12626                }
12627                // Restore of old package succeeded. Update permissions.
12628                // writer
12629                synchronized (mPackages) {
12630                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12631                            UPDATE_PERMISSIONS_ALL);
12632                    // can downgrade to reader
12633                    mSettings.writeLPr();
12634                }
12635                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12636            }
12637        }
12638    }
12639
12640    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12641            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12642            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12643            String volumeUuid, PackageInstalledInfo res) {
12644        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12645                + ", old=" + deletedPackage);
12646        boolean disabledSystem = false;
12647        boolean updatedSettings = false;
12648        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12649        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12650                != 0) {
12651            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12652        }
12653        String packageName = deletedPackage.packageName;
12654        if (packageName == null) {
12655            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12656                    "Attempt to delete null packageName.");
12657            return;
12658        }
12659        PackageParser.Package oldPkg;
12660        PackageSetting oldPkgSetting;
12661        // reader
12662        synchronized (mPackages) {
12663            oldPkg = mPackages.get(packageName);
12664            oldPkgSetting = mSettings.mPackages.get(packageName);
12665            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12666                    (oldPkgSetting == null)) {
12667                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12668                        "Couldn't find package " + packageName + " information");
12669                return;
12670            }
12671        }
12672
12673        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12674
12675        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12676        res.removedInfo.removedPackage = packageName;
12677        // Remove existing system package
12678        removePackageLI(oldPkgSetting, true);
12679        // writer
12680        synchronized (mPackages) {
12681            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12682            if (!disabledSystem && deletedPackage != null) {
12683                // We didn't need to disable the .apk as a current system package,
12684                // which means we are replacing another update that is already
12685                // installed.  We need to make sure to delete the older one's .apk.
12686                res.removedInfo.args = createInstallArgsForExisting(0,
12687                        deletedPackage.applicationInfo.getCodePath(),
12688                        deletedPackage.applicationInfo.getResourcePath(),
12689                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12690            } else {
12691                res.removedInfo.args = null;
12692            }
12693        }
12694
12695        // Successfully disabled the old package. Now proceed with re-installation
12696        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12697
12698        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12699        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12700
12701        PackageParser.Package newPackage = null;
12702        try {
12703            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12704            if (newPackage.mExtras != null) {
12705                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12706                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12707                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12708
12709                // is the update attempting to change shared user? that isn't going to work...
12710                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12711                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12712                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12713                            + " to " + newPkgSetting.sharedUser);
12714                    updatedSettings = true;
12715                }
12716            }
12717
12718            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12719                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12720                        perUserInstalled, res, user);
12721                prepareAppDataAfterInstall(newPackage);
12722                updatedSettings = true;
12723            }
12724
12725        } catch (PackageManagerException e) {
12726            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12727        }
12728
12729        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12730            // Re installation failed. Restore old information
12731            // Remove new pkg information
12732            if (newPackage != null) {
12733                removeInstalledPackageLI(newPackage, true);
12734            }
12735            // Add back the old system package
12736            try {
12737                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12738            } catch (PackageManagerException e) {
12739                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12740            }
12741            // Restore the old system information in Settings
12742            synchronized (mPackages) {
12743                if (disabledSystem) {
12744                    mSettings.enableSystemPackageLPw(packageName);
12745                }
12746                if (updatedSettings) {
12747                    mSettings.setInstallerPackageName(packageName,
12748                            oldPkgSetting.installerPackageName);
12749                }
12750                mSettings.writeLPr();
12751            }
12752        }
12753    }
12754
12755    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12756        // Collect all used permissions in the UID
12757        ArraySet<String> usedPermissions = new ArraySet<>();
12758        final int packageCount = su.packages.size();
12759        for (int i = 0; i < packageCount; i++) {
12760            PackageSetting ps = su.packages.valueAt(i);
12761            if (ps.pkg == null) {
12762                continue;
12763            }
12764            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12765            for (int j = 0; j < requestedPermCount; j++) {
12766                String permission = ps.pkg.requestedPermissions.get(j);
12767                BasePermission bp = mSettings.mPermissions.get(permission);
12768                if (bp != null) {
12769                    usedPermissions.add(permission);
12770                }
12771            }
12772        }
12773
12774        PermissionsState permissionsState = su.getPermissionsState();
12775        // Prune install permissions
12776        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12777        final int installPermCount = installPermStates.size();
12778        for (int i = installPermCount - 1; i >= 0;  i--) {
12779            PermissionState permissionState = installPermStates.get(i);
12780            if (!usedPermissions.contains(permissionState.getName())) {
12781                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12782                if (bp != null) {
12783                    permissionsState.revokeInstallPermission(bp);
12784                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12785                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12786                }
12787            }
12788        }
12789
12790        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12791
12792        // Prune runtime permissions
12793        for (int userId : allUserIds) {
12794            List<PermissionState> runtimePermStates = permissionsState
12795                    .getRuntimePermissionStates(userId);
12796            final int runtimePermCount = runtimePermStates.size();
12797            for (int i = runtimePermCount - 1; i >= 0; i--) {
12798                PermissionState permissionState = runtimePermStates.get(i);
12799                if (!usedPermissions.contains(permissionState.getName())) {
12800                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12801                    if (bp != null) {
12802                        permissionsState.revokeRuntimePermission(bp, userId);
12803                        permissionsState.updatePermissionFlags(bp, userId,
12804                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12805                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12806                                runtimePermissionChangedUserIds, userId);
12807                    }
12808                }
12809            }
12810        }
12811
12812        return runtimePermissionChangedUserIds;
12813    }
12814
12815    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12816            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12817            UserHandle user) {
12818        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12819
12820        String pkgName = newPackage.packageName;
12821        synchronized (mPackages) {
12822            //write settings. the installStatus will be incomplete at this stage.
12823            //note that the new package setting would have already been
12824            //added to mPackages. It hasn't been persisted yet.
12825            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12827            mSettings.writeLPr();
12828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12829        }
12830
12831        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12832        synchronized (mPackages) {
12833            updatePermissionsLPw(newPackage.packageName, newPackage,
12834                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12835                            ? UPDATE_PERMISSIONS_ALL : 0));
12836            // For system-bundled packages, we assume that installing an upgraded version
12837            // of the package implies that the user actually wants to run that new code,
12838            // so we enable the package.
12839            PackageSetting ps = mSettings.mPackages.get(pkgName);
12840            if (ps != null) {
12841                if (isSystemApp(newPackage)) {
12842                    // NB: implicit assumption that system package upgrades apply to all users
12843                    if (DEBUG_INSTALL) {
12844                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12845                    }
12846                    if (res.origUsers != null) {
12847                        for (int userHandle : res.origUsers) {
12848                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12849                                    userHandle, installerPackageName);
12850                        }
12851                    }
12852                    // Also convey the prior install/uninstall state
12853                    if (allUsers != null && perUserInstalled != null) {
12854                        for (int i = 0; i < allUsers.length; i++) {
12855                            if (DEBUG_INSTALL) {
12856                                Slog.d(TAG, "    user " + allUsers[i]
12857                                        + " => " + perUserInstalled[i]);
12858                            }
12859                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12860                        }
12861                        // these install state changes will be persisted in the
12862                        // upcoming call to mSettings.writeLPr().
12863                    }
12864                }
12865                // It's implied that when a user requests installation, they want the app to be
12866                // installed and enabled.
12867                int userId = user.getIdentifier();
12868                if (userId != UserHandle.USER_ALL) {
12869                    ps.setInstalled(true, userId);
12870                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12871                }
12872            }
12873            res.name = pkgName;
12874            res.uid = newPackage.applicationInfo.uid;
12875            res.pkg = newPackage;
12876            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12877            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12878            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12879            //to update install status
12880            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12881            mSettings.writeLPr();
12882            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12883        }
12884
12885        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12886    }
12887
12888    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12889        try {
12890            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12891            installPackageLI(args, res);
12892        } finally {
12893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12894        }
12895    }
12896
12897    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12898        final int installFlags = args.installFlags;
12899        final String installerPackageName = args.installerPackageName;
12900        final String volumeUuid = args.volumeUuid;
12901        final File tmpPackageFile = new File(args.getCodePath());
12902        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12903        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12904                || (args.volumeUuid != null));
12905        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12906        boolean replace = false;
12907        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12908        if (args.move != null) {
12909            // moving a complete application; perfom an initial scan on the new install location
12910            scanFlags |= SCAN_INITIAL;
12911        }
12912        // Result object to be returned
12913        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12914
12915        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12916
12917        // Sanity check
12918        if (ephemeral && (forwardLocked || onExternal)) {
12919            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12920                    + " external=" + onExternal);
12921            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12922            return;
12923        }
12924
12925        // Retrieve PackageSettings and parse package
12926        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12927                | PackageParser.PARSE_ENFORCE_CODE
12928                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12929                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12930                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12931        PackageParser pp = new PackageParser();
12932        pp.setSeparateProcesses(mSeparateProcesses);
12933        pp.setDisplayMetrics(mMetrics);
12934
12935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12936        final PackageParser.Package pkg;
12937        try {
12938            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12939        } catch (PackageParserException e) {
12940            res.setError("Failed parse during installPackageLI", e);
12941            return;
12942        } finally {
12943            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12944        }
12945
12946        // If package doesn't declare API override, mark that we have an install
12947        // time CPU ABI override.
12948        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
12949            pkg.cpuAbiOverride = args.abiOverride;
12950        }
12951
12952        String pkgName = res.name = pkg.packageName;
12953        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12954            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12955                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12956                return;
12957            }
12958        }
12959
12960        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12961        try {
12962            pp.collectCertificates(pkg, parseFlags);
12963        } catch (PackageParserException e) {
12964            res.setError("Failed collect during installPackageLI", e);
12965            return;
12966        } finally {
12967            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12968        }
12969
12970        // Get rid of all references to package scan path via parser.
12971        pp = null;
12972        String oldCodePath = null;
12973        boolean systemApp = false;
12974        synchronized (mPackages) {
12975            // Check if installing already existing package
12976            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12977                String oldName = mSettings.mRenamedPackages.get(pkgName);
12978                if (pkg.mOriginalPackages != null
12979                        && pkg.mOriginalPackages.contains(oldName)
12980                        && mPackages.containsKey(oldName)) {
12981                    // This package is derived from an original package,
12982                    // and this device has been updating from that original
12983                    // name.  We must continue using the original name, so
12984                    // rename the new package here.
12985                    pkg.setPackageName(oldName);
12986                    pkgName = pkg.packageName;
12987                    replace = true;
12988                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12989                            + oldName + " pkgName=" + pkgName);
12990                } else if (mPackages.containsKey(pkgName)) {
12991                    // This package, under its official name, already exists
12992                    // on the device; we should replace it.
12993                    replace = true;
12994                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12995                }
12996
12997                // Prevent apps opting out from runtime permissions
12998                if (replace) {
12999                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13000                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13001                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13002                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13003                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13004                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13005                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13006                                        + " doesn't support runtime permissions but the old"
13007                                        + " target SDK " + oldTargetSdk + " does.");
13008                        return;
13009                    }
13010                }
13011            }
13012
13013            PackageSetting ps = mSettings.mPackages.get(pkgName);
13014            if (ps != null) {
13015                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13016
13017                // Quick sanity check that we're signed correctly if updating;
13018                // we'll check this again later when scanning, but we want to
13019                // bail early here before tripping over redefined permissions.
13020                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13021                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13022                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13023                                + pkg.packageName + " upgrade keys do not match the "
13024                                + "previously installed version");
13025                        return;
13026                    }
13027                } else {
13028                    try {
13029                        verifySignaturesLP(ps, pkg);
13030                    } catch (PackageManagerException e) {
13031                        res.setError(e.error, e.getMessage());
13032                        return;
13033                    }
13034                }
13035
13036                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13037                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13038                    systemApp = (ps.pkg.applicationInfo.flags &
13039                            ApplicationInfo.FLAG_SYSTEM) != 0;
13040                }
13041                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13042            }
13043
13044            // Check whether the newly-scanned package wants to define an already-defined perm
13045            int N = pkg.permissions.size();
13046            for (int i = N-1; i >= 0; i--) {
13047                PackageParser.Permission perm = pkg.permissions.get(i);
13048                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13049                if (bp != null) {
13050                    // If the defining package is signed with our cert, it's okay.  This
13051                    // also includes the "updating the same package" case, of course.
13052                    // "updating same package" could also involve key-rotation.
13053                    final boolean sigsOk;
13054                    if (bp.sourcePackage.equals(pkg.packageName)
13055                            && (bp.packageSetting instanceof PackageSetting)
13056                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13057                                    scanFlags))) {
13058                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13059                    } else {
13060                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13061                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13062                    }
13063                    if (!sigsOk) {
13064                        // If the owning package is the system itself, we log but allow
13065                        // install to proceed; we fail the install on all other permission
13066                        // redefinitions.
13067                        if (!bp.sourcePackage.equals("android")) {
13068                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13069                                    + pkg.packageName + " attempting to redeclare permission "
13070                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13071                            res.origPermission = perm.info.name;
13072                            res.origPackage = bp.sourcePackage;
13073                            return;
13074                        } else {
13075                            Slog.w(TAG, "Package " + pkg.packageName
13076                                    + " attempting to redeclare system permission "
13077                                    + perm.info.name + "; ignoring new declaration");
13078                            pkg.permissions.remove(i);
13079                        }
13080                    }
13081                }
13082            }
13083
13084        }
13085
13086        if (systemApp) {
13087            if (onExternal) {
13088                // Abort update; system app can't be replaced with app on sdcard
13089                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13090                        "Cannot install updates to system apps on sdcard");
13091                return;
13092            } else if (ephemeral) {
13093                // Abort update; system app can't be replaced with an ephemeral app
13094                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13095                        "Cannot update a system app with an ephemeral app");
13096                return;
13097            }
13098        }
13099
13100        if (args.move != null) {
13101            // We did an in-place move, so dex is ready to roll
13102            scanFlags |= SCAN_NO_DEX;
13103            scanFlags |= SCAN_MOVE;
13104
13105            synchronized (mPackages) {
13106                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13107                if (ps == null) {
13108                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13109                            "Missing settings for moved package " + pkgName);
13110                }
13111
13112                // We moved the entire application as-is, so bring over the
13113                // previously derived ABI information.
13114                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13115                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13116            }
13117
13118        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13119            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13120            scanFlags |= SCAN_NO_DEX;
13121
13122            try {
13123                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13124                    args.abiOverride : pkg.cpuAbiOverride);
13125                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13126                        true /* extract libs */);
13127            } catch (PackageManagerException pme) {
13128                Slog.e(TAG, "Error deriving application ABI", pme);
13129                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13130                return;
13131            }
13132
13133            // Extract package to save the VM unzipping the APK in memory during
13134            // launch. Only do this if profile-guided compilation is enabled because
13135            // otherwise BackgroundDexOptService will not dexopt the package later.
13136            if (mUseJitProfiles) {
13137                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13138                // Do not run PackageDexOptimizer through the local performDexOpt
13139                // method because `pkg` is not in `mPackages` yet.
13140                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13141                        false /* useProfiles */, true /* extractOnly */);
13142                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13143                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13144                    String msg = "Extracking package failed for " + pkgName;
13145                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13146                    return;
13147                }
13148            }
13149        }
13150
13151        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13152            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13153            return;
13154        }
13155
13156        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13157
13158        if (replace) {
13159            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13160                    installerPackageName, volumeUuid, res);
13161        } else {
13162            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13163                    args.user, installerPackageName, volumeUuid, res);
13164        }
13165        synchronized (mPackages) {
13166            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13167            if (ps != null) {
13168                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13169            }
13170        }
13171    }
13172
13173    private void startIntentFilterVerifications(int userId, boolean replacing,
13174            PackageParser.Package pkg) {
13175        if (mIntentFilterVerifierComponent == null) {
13176            Slog.w(TAG, "No IntentFilter verification will not be done as "
13177                    + "there is no IntentFilterVerifier available!");
13178            return;
13179        }
13180
13181        final int verifierUid = getPackageUid(
13182                mIntentFilterVerifierComponent.getPackageName(),
13183                MATCH_DEBUG_TRIAGED_MISSING,
13184                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13185
13186        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13187        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13188        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13189        mHandler.sendMessage(msg);
13190    }
13191
13192    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13193            PackageParser.Package pkg) {
13194        int size = pkg.activities.size();
13195        if (size == 0) {
13196            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13197                    "No activity, so no need to verify any IntentFilter!");
13198            return;
13199        }
13200
13201        final boolean hasDomainURLs = hasDomainURLs(pkg);
13202        if (!hasDomainURLs) {
13203            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13204                    "No domain URLs, so no need to verify any IntentFilter!");
13205            return;
13206        }
13207
13208        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13209                + " if any IntentFilter from the " + size
13210                + " Activities needs verification ...");
13211
13212        int count = 0;
13213        final String packageName = pkg.packageName;
13214
13215        synchronized (mPackages) {
13216            // If this is a new install and we see that we've already run verification for this
13217            // package, we have nothing to do: it means the state was restored from backup.
13218            if (!replacing) {
13219                IntentFilterVerificationInfo ivi =
13220                        mSettings.getIntentFilterVerificationLPr(packageName);
13221                if (ivi != null) {
13222                    if (DEBUG_DOMAIN_VERIFICATION) {
13223                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13224                                + ivi.getStatusString());
13225                    }
13226                    return;
13227                }
13228            }
13229
13230            // If any filters need to be verified, then all need to be.
13231            boolean needToVerify = false;
13232            for (PackageParser.Activity a : pkg.activities) {
13233                for (ActivityIntentInfo filter : a.intents) {
13234                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13235                        if (DEBUG_DOMAIN_VERIFICATION) {
13236                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13237                        }
13238                        needToVerify = true;
13239                        break;
13240                    }
13241                }
13242            }
13243
13244            if (needToVerify) {
13245                final int verificationId = mIntentFilterVerificationToken++;
13246                for (PackageParser.Activity a : pkg.activities) {
13247                    for (ActivityIntentInfo filter : a.intents) {
13248                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13249                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13250                                    "Verification needed for IntentFilter:" + filter.toString());
13251                            mIntentFilterVerifier.addOneIntentFilterVerification(
13252                                    verifierUid, userId, verificationId, filter, packageName);
13253                            count++;
13254                        }
13255                    }
13256                }
13257            }
13258        }
13259
13260        if (count > 0) {
13261            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13262                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13263                    +  " for userId:" + userId);
13264            mIntentFilterVerifier.startVerifications(userId);
13265        } else {
13266            if (DEBUG_DOMAIN_VERIFICATION) {
13267                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13268            }
13269        }
13270    }
13271
13272    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13273        final ComponentName cn  = filter.activity.getComponentName();
13274        final String packageName = cn.getPackageName();
13275
13276        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13277                packageName);
13278        if (ivi == null) {
13279            return true;
13280        }
13281        int status = ivi.getStatus();
13282        switch (status) {
13283            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13284            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13285                return true;
13286
13287            default:
13288                // Nothing to do
13289                return false;
13290        }
13291    }
13292
13293    private static boolean isMultiArch(ApplicationInfo info) {
13294        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13295    }
13296
13297    private static boolean isExternal(PackageParser.Package pkg) {
13298        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13299    }
13300
13301    private static boolean isExternal(PackageSetting ps) {
13302        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13303    }
13304
13305    private static boolean isEphemeral(PackageParser.Package pkg) {
13306        return pkg.applicationInfo.isEphemeralApp();
13307    }
13308
13309    private static boolean isEphemeral(PackageSetting ps) {
13310        return ps.pkg != null && isEphemeral(ps.pkg);
13311    }
13312
13313    private static boolean isSystemApp(PackageParser.Package pkg) {
13314        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13315    }
13316
13317    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13318        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13319    }
13320
13321    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13322        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13323    }
13324
13325    private static boolean isSystemApp(PackageSetting ps) {
13326        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13327    }
13328
13329    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13330        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13331    }
13332
13333    private int packageFlagsToInstallFlags(PackageSetting ps) {
13334        int installFlags = 0;
13335        if (isEphemeral(ps)) {
13336            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13337        }
13338        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13339            // This existing package was an external ASEC install when we have
13340            // the external flag without a UUID
13341            installFlags |= PackageManager.INSTALL_EXTERNAL;
13342        }
13343        if (ps.isForwardLocked()) {
13344            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13345        }
13346        return installFlags;
13347    }
13348
13349    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13350        if (isExternal(pkg)) {
13351            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13352                return StorageManager.UUID_PRIMARY_PHYSICAL;
13353            } else {
13354                return pkg.volumeUuid;
13355            }
13356        } else {
13357            return StorageManager.UUID_PRIVATE_INTERNAL;
13358        }
13359    }
13360
13361    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13362        if (isExternal(pkg)) {
13363            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13364                return mSettings.getExternalVersion();
13365            } else {
13366                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13367            }
13368        } else {
13369            return mSettings.getInternalVersion();
13370        }
13371    }
13372
13373    private void deleteTempPackageFiles() {
13374        final FilenameFilter filter = new FilenameFilter() {
13375            public boolean accept(File dir, String name) {
13376                return name.startsWith("vmdl") && name.endsWith(".tmp");
13377            }
13378        };
13379        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13380            file.delete();
13381        }
13382    }
13383
13384    @Override
13385    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13386            int flags) {
13387        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13388                flags);
13389    }
13390
13391    @Override
13392    public void deletePackage(final String packageName,
13393            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13394        mContext.enforceCallingOrSelfPermission(
13395                android.Manifest.permission.DELETE_PACKAGES, null);
13396        Preconditions.checkNotNull(packageName);
13397        Preconditions.checkNotNull(observer);
13398        final int uid = Binder.getCallingUid();
13399        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13400        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13401        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13402            mContext.enforceCallingOrSelfPermission(
13403                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13404                    "deletePackage for user " + userId);
13405        }
13406
13407        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13408            try {
13409                observer.onPackageDeleted(packageName,
13410                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13411            } catch (RemoteException re) {
13412            }
13413            return;
13414        }
13415
13416        for (int currentUserId : users) {
13417            if (getBlockUninstallForUser(packageName, currentUserId)) {
13418                try {
13419                    observer.onPackageDeleted(packageName,
13420                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13421                } catch (RemoteException re) {
13422                }
13423                return;
13424            }
13425        }
13426
13427        if (DEBUG_REMOVE) {
13428            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13429        }
13430        // Queue up an async operation since the package deletion may take a little while.
13431        mHandler.post(new Runnable() {
13432            public void run() {
13433                mHandler.removeCallbacks(this);
13434                final int returnCode = deletePackageX(packageName, userId, flags);
13435                try {
13436                    observer.onPackageDeleted(packageName, returnCode, null);
13437                } catch (RemoteException e) {
13438                    Log.i(TAG, "Observer no longer exists.");
13439                } //end catch
13440            } //end run
13441        });
13442    }
13443
13444    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13445        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13446                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13447        try {
13448            if (dpm != null) {
13449                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13450                        /* callingUserOnly =*/ false);
13451                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13452                        : deviceOwnerComponentName.getPackageName();
13453                // Does the package contains the device owner?
13454                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13455                // this check is probably not needed, since DO should be registered as a device
13456                // admin on some user too. (Original bug for this: b/17657954)
13457                if (packageName.equals(deviceOwnerPackageName)) {
13458                    return true;
13459                }
13460                // Does it contain a device admin for any user?
13461                int[] users;
13462                if (userId == UserHandle.USER_ALL) {
13463                    users = sUserManager.getUserIds();
13464                } else {
13465                    users = new int[]{userId};
13466                }
13467                for (int i = 0; i < users.length; ++i) {
13468                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13469                        return true;
13470                    }
13471                }
13472            }
13473        } catch (RemoteException e) {
13474        }
13475        return false;
13476    }
13477
13478    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13479        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13480    }
13481
13482    /**
13483     *  This method is an internal method that could be get invoked either
13484     *  to delete an installed package or to clean up a failed installation.
13485     *  After deleting an installed package, a broadcast is sent to notify any
13486     *  listeners that the package has been installed. For cleaning up a failed
13487     *  installation, the broadcast is not necessary since the package's
13488     *  installation wouldn't have sent the initial broadcast either
13489     *  The key steps in deleting a package are
13490     *  deleting the package information in internal structures like mPackages,
13491     *  deleting the packages base directories through installd
13492     *  updating mSettings to reflect current status
13493     *  persisting settings for later use
13494     *  sending a broadcast if necessary
13495     */
13496    private int deletePackageX(String packageName, int userId, int flags) {
13497        final PackageRemovedInfo info = new PackageRemovedInfo();
13498        final boolean res;
13499
13500        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13501                ? UserHandle.ALL : new UserHandle(userId);
13502
13503        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13504            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13505            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13506        }
13507
13508        boolean removedForAllUsers = false;
13509        boolean systemUpdate = false;
13510
13511        PackageParser.Package uninstalledPkg;
13512
13513        // for the uninstall-updates case and restricted profiles, remember the per-
13514        // userhandle installed state
13515        int[] allUsers;
13516        boolean[] perUserInstalled;
13517        synchronized (mPackages) {
13518            uninstalledPkg = mPackages.get(packageName);
13519            PackageSetting ps = mSettings.mPackages.get(packageName);
13520            allUsers = sUserManager.getUserIds();
13521            perUserInstalled = new boolean[allUsers.length];
13522            for (int i = 0; i < allUsers.length; i++) {
13523                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13524            }
13525        }
13526
13527        synchronized (mInstallLock) {
13528            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13529            res = deletePackageLI(packageName, removeForUser,
13530                    true, allUsers, perUserInstalled,
13531                    flags | REMOVE_CHATTY, info, true);
13532            systemUpdate = info.isRemovedPackageSystemUpdate;
13533            synchronized (mPackages) {
13534                if (res) {
13535                    if (!systemUpdate && mPackages.get(packageName) == null) {
13536                        removedForAllUsers = true;
13537                    }
13538                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13539                }
13540            }
13541            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13542                    + " removedForAllUsers=" + removedForAllUsers);
13543        }
13544
13545        if (res) {
13546            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13547
13548            // If the removed package was a system update, the old system package
13549            // was re-enabled; we need to broadcast this information
13550            if (systemUpdate) {
13551                Bundle extras = new Bundle(1);
13552                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13553                        ? info.removedAppId : info.uid);
13554                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13555
13556                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13557                        extras, 0, null, null, null);
13558                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13559                        extras, 0, null, null, null);
13560                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13561                        null, 0, packageName, null, null);
13562            }
13563        }
13564        // Force a gc here.
13565        Runtime.getRuntime().gc();
13566        // Delete the resources here after sending the broadcast to let
13567        // other processes clean up before deleting resources.
13568        if (info.args != null) {
13569            synchronized (mInstallLock) {
13570                info.args.doPostDeleteLI(true);
13571            }
13572        }
13573
13574        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13575    }
13576
13577    class PackageRemovedInfo {
13578        String removedPackage;
13579        int uid = -1;
13580        int removedAppId = -1;
13581        int[] removedUsers = null;
13582        boolean isRemovedPackageSystemUpdate = false;
13583        // Clean up resources deleted packages.
13584        InstallArgs args = null;
13585
13586        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13587            Bundle extras = new Bundle(1);
13588            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13589            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13590            if (replacing) {
13591                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13592            }
13593            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13594            if (removedPackage != null) {
13595                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13596                        extras, 0, null, null, removedUsers);
13597                if (fullRemove && !replacing) {
13598                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13599                            extras, 0, null, null, removedUsers);
13600                }
13601            }
13602            if (removedAppId >= 0) {
13603                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13604                        removedUsers);
13605            }
13606        }
13607    }
13608
13609    /*
13610     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13611     * flag is not set, the data directory is removed as well.
13612     * make sure this flag is set for partially installed apps. If not its meaningless to
13613     * delete a partially installed application.
13614     */
13615    private void removePackageDataLI(PackageSetting ps,
13616            int[] allUserHandles, boolean[] perUserInstalled,
13617            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13618        String packageName = ps.name;
13619        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13620        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13621        // Retrieve object to delete permissions for shared user later on
13622        final PackageSetting deletedPs;
13623        // reader
13624        synchronized (mPackages) {
13625            deletedPs = mSettings.mPackages.get(packageName);
13626            if (outInfo != null) {
13627                outInfo.removedPackage = packageName;
13628                outInfo.removedUsers = deletedPs != null
13629                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13630                        : null;
13631            }
13632        }
13633        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13634            removeDataDirsLI(ps.volumeUuid, packageName);
13635            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13636        }
13637        // writer
13638        synchronized (mPackages) {
13639            if (deletedPs != null) {
13640                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13641                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13642                    clearDefaultBrowserIfNeeded(packageName);
13643                    if (outInfo != null) {
13644                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13645                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13646                    }
13647                    updatePermissionsLPw(deletedPs.name, null, 0);
13648                    if (deletedPs.sharedUser != null) {
13649                        // Remove permissions associated with package. Since runtime
13650                        // permissions are per user we have to kill the removed package
13651                        // or packages running under the shared user of the removed
13652                        // package if revoking the permissions requested only by the removed
13653                        // package is successful and this causes a change in gids.
13654                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13655                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13656                                    userId);
13657                            if (userIdToKill == UserHandle.USER_ALL
13658                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13659                                // If gids changed for this user, kill all affected packages.
13660                                mHandler.post(new Runnable() {
13661                                    @Override
13662                                    public void run() {
13663                                        // This has to happen with no lock held.
13664                                        killApplication(deletedPs.name, deletedPs.appId,
13665                                                KILL_APP_REASON_GIDS_CHANGED);
13666                                    }
13667                                });
13668                                break;
13669                            }
13670                        }
13671                    }
13672                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13673                }
13674                // make sure to preserve per-user disabled state if this removal was just
13675                // a downgrade of a system app to the factory package
13676                if (allUserHandles != null && perUserInstalled != null) {
13677                    if (DEBUG_REMOVE) {
13678                        Slog.d(TAG, "Propagating install state across downgrade");
13679                    }
13680                    for (int i = 0; i < allUserHandles.length; i++) {
13681                        if (DEBUG_REMOVE) {
13682                            Slog.d(TAG, "    user " + allUserHandles[i]
13683                                    + " => " + perUserInstalled[i]);
13684                        }
13685                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13686                    }
13687                }
13688            }
13689            // can downgrade to reader
13690            if (writeSettings) {
13691                // Save settings now
13692                mSettings.writeLPr();
13693            }
13694        }
13695        if (outInfo != null) {
13696            // A user ID was deleted here. Go through all users and remove it
13697            // from KeyStore.
13698            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13699        }
13700    }
13701
13702    static boolean locationIsPrivileged(File path) {
13703        try {
13704            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13705                    .getCanonicalPath();
13706            return path.getCanonicalPath().startsWith(privilegedAppDir);
13707        } catch (IOException e) {
13708            Slog.e(TAG, "Unable to access code path " + path);
13709        }
13710        return false;
13711    }
13712
13713    /*
13714     * Tries to delete system package.
13715     */
13716    private boolean deleteSystemPackageLI(PackageSetting newPs,
13717            int[] allUserHandles, boolean[] perUserInstalled,
13718            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13719        final boolean applyUserRestrictions
13720                = (allUserHandles != null) && (perUserInstalled != null);
13721        PackageSetting disabledPs = null;
13722        // Confirm if the system package has been updated
13723        // An updated system app can be deleted. This will also have to restore
13724        // the system pkg from system partition
13725        // reader
13726        synchronized (mPackages) {
13727            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13728        }
13729        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13730                + " disabledPs=" + disabledPs);
13731        if (disabledPs == null) {
13732            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13733            return false;
13734        } else if (DEBUG_REMOVE) {
13735            Slog.d(TAG, "Deleting system pkg from data partition");
13736        }
13737        if (DEBUG_REMOVE) {
13738            if (applyUserRestrictions) {
13739                Slog.d(TAG, "Remembering install states:");
13740                for (int i = 0; i < allUserHandles.length; i++) {
13741                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13742                }
13743            }
13744        }
13745        // Delete the updated package
13746        outInfo.isRemovedPackageSystemUpdate = true;
13747        if (disabledPs.versionCode < newPs.versionCode) {
13748            // Delete data for downgrades
13749            flags &= ~PackageManager.DELETE_KEEP_DATA;
13750        } else {
13751            // Preserve data by setting flag
13752            flags |= PackageManager.DELETE_KEEP_DATA;
13753        }
13754        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13755                allUserHandles, perUserInstalled, outInfo, writeSettings);
13756        if (!ret) {
13757            return false;
13758        }
13759        // writer
13760        synchronized (mPackages) {
13761            // Reinstate the old system package
13762            mSettings.enableSystemPackageLPw(newPs.name);
13763            // Remove any native libraries from the upgraded package.
13764            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13765        }
13766        // Install the system package
13767        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13768        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13769        if (locationIsPrivileged(disabledPs.codePath)) {
13770            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13771        }
13772
13773        final PackageParser.Package newPkg;
13774        try {
13775            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13776        } catch (PackageManagerException e) {
13777            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13778            return false;
13779        }
13780
13781        prepareAppDataAfterInstall(newPkg);
13782
13783        // writer
13784        synchronized (mPackages) {
13785            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13786
13787            // Propagate the permissions state as we do not want to drop on the floor
13788            // runtime permissions. The update permissions method below will take
13789            // care of removing obsolete permissions and grant install permissions.
13790            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13791            updatePermissionsLPw(newPkg.packageName, newPkg,
13792                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13793
13794            if (applyUserRestrictions) {
13795                if (DEBUG_REMOVE) {
13796                    Slog.d(TAG, "Propagating install state across reinstall");
13797                }
13798                for (int i = 0; i < allUserHandles.length; i++) {
13799                    if (DEBUG_REMOVE) {
13800                        Slog.d(TAG, "    user " + allUserHandles[i]
13801                                + " => " + perUserInstalled[i]);
13802                    }
13803                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13804
13805                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13806                }
13807                // Regardless of writeSettings we need to ensure that this restriction
13808                // state propagation is persisted
13809                mSettings.writeAllUsersPackageRestrictionsLPr();
13810            }
13811            // can downgrade to reader here
13812            if (writeSettings) {
13813                mSettings.writeLPr();
13814            }
13815        }
13816        return true;
13817    }
13818
13819    private boolean deleteInstalledPackageLI(PackageSetting ps,
13820            boolean deleteCodeAndResources, int flags,
13821            int[] allUserHandles, boolean[] perUserInstalled,
13822            PackageRemovedInfo outInfo, boolean writeSettings) {
13823        if (outInfo != null) {
13824            outInfo.uid = ps.appId;
13825        }
13826
13827        // Delete package data from internal structures and also remove data if flag is set
13828        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13829
13830        // Delete application code and resources
13831        if (deleteCodeAndResources && (outInfo != null)) {
13832            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13833                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13834            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13835        }
13836        return true;
13837    }
13838
13839    @Override
13840    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13841            int userId) {
13842        mContext.enforceCallingOrSelfPermission(
13843                android.Manifest.permission.DELETE_PACKAGES, null);
13844        synchronized (mPackages) {
13845            PackageSetting ps = mSettings.mPackages.get(packageName);
13846            if (ps == null) {
13847                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13848                return false;
13849            }
13850            if (!ps.getInstalled(userId)) {
13851                // Can't block uninstall for an app that is not installed or enabled.
13852                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13853                return false;
13854            }
13855            ps.setBlockUninstall(blockUninstall, userId);
13856            mSettings.writePackageRestrictionsLPr(userId);
13857        }
13858        return true;
13859    }
13860
13861    @Override
13862    public boolean getBlockUninstallForUser(String packageName, int userId) {
13863        synchronized (mPackages) {
13864            PackageSetting ps = mSettings.mPackages.get(packageName);
13865            if (ps == null) {
13866                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13867                return false;
13868            }
13869            return ps.getBlockUninstall(userId);
13870        }
13871    }
13872
13873    @Override
13874    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13875        int callingUid = Binder.getCallingUid();
13876        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13877            throw new SecurityException(
13878                    "setRequiredForSystemUser can only be run by the system or root");
13879        }
13880        synchronized (mPackages) {
13881            PackageSetting ps = mSettings.mPackages.get(packageName);
13882            if (ps == null) {
13883                Log.w(TAG, "Package doesn't exist: " + packageName);
13884                return false;
13885            }
13886            if (systemUserApp) {
13887                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13888            } else {
13889                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13890            }
13891            mSettings.writeLPr();
13892        }
13893        return true;
13894    }
13895
13896    /*
13897     * This method handles package deletion in general
13898     */
13899    private boolean deletePackageLI(String packageName, UserHandle user,
13900            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13901            int flags, PackageRemovedInfo outInfo,
13902            boolean writeSettings) {
13903        if (packageName == null) {
13904            Slog.w(TAG, "Attempt to delete null packageName.");
13905            return false;
13906        }
13907        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13908        PackageSetting ps;
13909        boolean dataOnly = false;
13910        int removeUser = -1;
13911        int appId = -1;
13912        synchronized (mPackages) {
13913            ps = mSettings.mPackages.get(packageName);
13914            if (ps == null) {
13915                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13916                return false;
13917            }
13918            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13919                    && user.getIdentifier() != UserHandle.USER_ALL) {
13920                // The caller is asking that the package only be deleted for a single
13921                // user.  To do this, we just mark its uninstalled state and delete
13922                // its data.  If this is a system app, we only allow this to happen if
13923                // they have set the special DELETE_SYSTEM_APP which requests different
13924                // semantics than normal for uninstalling system apps.
13925                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13926                final int userId = user.getIdentifier();
13927                ps.setUserState(userId,
13928                        COMPONENT_ENABLED_STATE_DEFAULT,
13929                        false, //installed
13930                        true,  //stopped
13931                        true,  //notLaunched
13932                        false, //hidden
13933                        false, //suspended
13934                        null, null, null,
13935                        false, // blockUninstall
13936                        ps.readUserState(userId).domainVerificationStatus, 0);
13937                if (!isSystemApp(ps)) {
13938                    // Do not uninstall the APK if an app should be cached
13939                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13940                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13941                        // Other user still have this package installed, so all
13942                        // we need to do is clear this user's data and save that
13943                        // it is uninstalled.
13944                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13945                        removeUser = user.getIdentifier();
13946                        appId = ps.appId;
13947                        scheduleWritePackageRestrictionsLocked(removeUser);
13948                    } else {
13949                        // We need to set it back to 'installed' so the uninstall
13950                        // broadcasts will be sent correctly.
13951                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13952                        ps.setInstalled(true, user.getIdentifier());
13953                    }
13954                } else {
13955                    // This is a system app, so we assume that the
13956                    // other users still have this package installed, so all
13957                    // we need to do is clear this user's data and save that
13958                    // it is uninstalled.
13959                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13960                    removeUser = user.getIdentifier();
13961                    appId = ps.appId;
13962                    scheduleWritePackageRestrictionsLocked(removeUser);
13963                }
13964            }
13965        }
13966
13967        if (removeUser >= 0) {
13968            // From above, we determined that we are deleting this only
13969            // for a single user.  Continue the work here.
13970            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13971            if (outInfo != null) {
13972                outInfo.removedPackage = packageName;
13973                outInfo.removedAppId = appId;
13974                outInfo.removedUsers = new int[] {removeUser};
13975            }
13976            // TODO: triage flags as part of 26466827
13977            final int installerFlags = StorageManager.FLAG_STORAGE_CE
13978                    | StorageManager.FLAG_STORAGE_DE;
13979            try {
13980                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13981            } catch (InstallerException e) {
13982                Slog.w(TAG, "Failed to delete app data", e);
13983            }
13984            removeKeystoreDataIfNeeded(removeUser, appId);
13985            schedulePackageCleaning(packageName, removeUser, false);
13986            synchronized (mPackages) {
13987                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13988                    scheduleWritePackageRestrictionsLocked(removeUser);
13989                }
13990                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13991            }
13992            return true;
13993        }
13994
13995        if (dataOnly) {
13996            // Delete application data first
13997            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13998            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13999            return true;
14000        }
14001
14002        boolean ret = false;
14003        if (isSystemApp(ps)) {
14004            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14005            // When an updated system application is deleted we delete the existing resources as well and
14006            // fall back to existing code in system partition
14007            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
14008                    flags, outInfo, writeSettings);
14009        } else {
14010            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14011            // Kill application pre-emptively especially for apps on sd.
14012            killApplication(packageName, ps.appId, "uninstall pkg");
14013            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
14014                    allUserHandles, perUserInstalled,
14015                    outInfo, writeSettings);
14016        }
14017
14018        return ret;
14019    }
14020
14021    private final static class ClearStorageConnection implements ServiceConnection {
14022        IMediaContainerService mContainerService;
14023
14024        @Override
14025        public void onServiceConnected(ComponentName name, IBinder service) {
14026            synchronized (this) {
14027                mContainerService = IMediaContainerService.Stub.asInterface(service);
14028                notifyAll();
14029            }
14030        }
14031
14032        @Override
14033        public void onServiceDisconnected(ComponentName name) {
14034        }
14035    }
14036
14037    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14038        final boolean mounted;
14039        if (Environment.isExternalStorageEmulated()) {
14040            mounted = true;
14041        } else {
14042            final String status = Environment.getExternalStorageState();
14043
14044            mounted = status.equals(Environment.MEDIA_MOUNTED)
14045                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14046        }
14047
14048        if (!mounted) {
14049            return;
14050        }
14051
14052        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14053        int[] users;
14054        if (userId == UserHandle.USER_ALL) {
14055            users = sUserManager.getUserIds();
14056        } else {
14057            users = new int[] { userId };
14058        }
14059        final ClearStorageConnection conn = new ClearStorageConnection();
14060        if (mContext.bindServiceAsUser(
14061                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14062            try {
14063                for (int curUser : users) {
14064                    long timeout = SystemClock.uptimeMillis() + 5000;
14065                    synchronized (conn) {
14066                        long now = SystemClock.uptimeMillis();
14067                        while (conn.mContainerService == null && now < timeout) {
14068                            try {
14069                                conn.wait(timeout - now);
14070                            } catch (InterruptedException e) {
14071                            }
14072                        }
14073                    }
14074                    if (conn.mContainerService == null) {
14075                        return;
14076                    }
14077
14078                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14079                    clearDirectory(conn.mContainerService,
14080                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14081                    if (allData) {
14082                        clearDirectory(conn.mContainerService,
14083                                userEnv.buildExternalStorageAppDataDirs(packageName));
14084                        clearDirectory(conn.mContainerService,
14085                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14086                    }
14087                }
14088            } finally {
14089                mContext.unbindService(conn);
14090            }
14091        }
14092    }
14093
14094    @Override
14095    public void clearApplicationUserData(final String packageName,
14096            final IPackageDataObserver observer, final int userId) {
14097        mContext.enforceCallingOrSelfPermission(
14098                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14099        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14100        // Queue up an async operation since the package deletion may take a little while.
14101        mHandler.post(new Runnable() {
14102            public void run() {
14103                mHandler.removeCallbacks(this);
14104                final boolean succeeded;
14105                synchronized (mInstallLock) {
14106                    succeeded = clearApplicationUserDataLI(packageName, userId);
14107                }
14108                clearExternalStorageDataSync(packageName, userId, true);
14109                if (succeeded) {
14110                    // invoke DeviceStorageMonitor's update method to clear any notifications
14111                    DeviceStorageMonitorInternal
14112                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14113                    if (dsm != null) {
14114                        dsm.checkMemory();
14115                    }
14116                }
14117                if(observer != null) {
14118                    try {
14119                        observer.onRemoveCompleted(packageName, succeeded);
14120                    } catch (RemoteException e) {
14121                        Log.i(TAG, "Observer no longer exists.");
14122                    }
14123                } //end if observer
14124            } //end run
14125        });
14126    }
14127
14128    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14129        if (packageName == null) {
14130            Slog.w(TAG, "Attempt to delete null packageName.");
14131            return false;
14132        }
14133
14134        // Try finding details about the requested package
14135        PackageParser.Package pkg;
14136        synchronized (mPackages) {
14137            pkg = mPackages.get(packageName);
14138            if (pkg == null) {
14139                final PackageSetting ps = mSettings.mPackages.get(packageName);
14140                if (ps != null) {
14141                    pkg = ps.pkg;
14142                }
14143            }
14144
14145            if (pkg == null) {
14146                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14147                return false;
14148            }
14149
14150            PackageSetting ps = (PackageSetting) pkg.mExtras;
14151            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14152        }
14153
14154        // Always delete data directories for package, even if we found no other
14155        // record of app. This helps users recover from UID mismatches without
14156        // resorting to a full data wipe.
14157        // TODO: triage flags as part of 26466827
14158        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14159        try {
14160            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14161        } catch (InstallerException e) {
14162            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14163            return false;
14164        }
14165
14166        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14167        removeKeystoreDataIfNeeded(userId, appId);
14168
14169        // Create a native library symlink only if we have native libraries
14170        // and if the native libraries are 32 bit libraries. We do not provide
14171        // this symlink for 64 bit libraries.
14172        if (pkg.applicationInfo.primaryCpuAbi != null &&
14173                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14174            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14175            try {
14176                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14177                        nativeLibPath, userId);
14178            } catch (InstallerException e) {
14179                Slog.w(TAG, "Failed linking native library dir", e);
14180                return false;
14181            }
14182        }
14183
14184        return true;
14185    }
14186
14187    /**
14188     * Reverts user permission state changes (permissions and flags) in
14189     * all packages for a given user.
14190     *
14191     * @param userId The device user for which to do a reset.
14192     */
14193    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14194        final int packageCount = mPackages.size();
14195        for (int i = 0; i < packageCount; i++) {
14196            PackageParser.Package pkg = mPackages.valueAt(i);
14197            PackageSetting ps = (PackageSetting) pkg.mExtras;
14198            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14199        }
14200    }
14201
14202    /**
14203     * Reverts user permission state changes (permissions and flags).
14204     *
14205     * @param ps The package for which to reset.
14206     * @param userId The device user for which to do a reset.
14207     */
14208    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14209            final PackageSetting ps, final int userId) {
14210        if (ps.pkg == null) {
14211            return;
14212        }
14213
14214        // These are flags that can change base on user actions.
14215        final int userSettableMask = FLAG_PERMISSION_USER_SET
14216                | FLAG_PERMISSION_USER_FIXED
14217                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14218                | FLAG_PERMISSION_REVIEW_REQUIRED;
14219
14220        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14221                | FLAG_PERMISSION_POLICY_FIXED;
14222
14223        boolean writeInstallPermissions = false;
14224        boolean writeRuntimePermissions = false;
14225
14226        final int permissionCount = ps.pkg.requestedPermissions.size();
14227        for (int i = 0; i < permissionCount; i++) {
14228            String permission = ps.pkg.requestedPermissions.get(i);
14229
14230            BasePermission bp = mSettings.mPermissions.get(permission);
14231            if (bp == null) {
14232                continue;
14233            }
14234
14235            // If shared user we just reset the state to which only this app contributed.
14236            if (ps.sharedUser != null) {
14237                boolean used = false;
14238                final int packageCount = ps.sharedUser.packages.size();
14239                for (int j = 0; j < packageCount; j++) {
14240                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14241                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14242                            && pkg.pkg.requestedPermissions.contains(permission)) {
14243                        used = true;
14244                        break;
14245                    }
14246                }
14247                if (used) {
14248                    continue;
14249                }
14250            }
14251
14252            PermissionsState permissionsState = ps.getPermissionsState();
14253
14254            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14255
14256            // Always clear the user settable flags.
14257            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14258                    bp.name) != null;
14259            // If permission review is enabled and this is a legacy app, mark the
14260            // permission as requiring a review as this is the initial state.
14261            int flags = 0;
14262            if (Build.PERMISSIONS_REVIEW_REQUIRED
14263                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14264                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14265            }
14266            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14267                if (hasInstallState) {
14268                    writeInstallPermissions = true;
14269                } else {
14270                    writeRuntimePermissions = true;
14271                }
14272            }
14273
14274            // Below is only runtime permission handling.
14275            if (!bp.isRuntime()) {
14276                continue;
14277            }
14278
14279            // Never clobber system or policy.
14280            if ((oldFlags & policyOrSystemFlags) != 0) {
14281                continue;
14282            }
14283
14284            // If this permission was granted by default, make sure it is.
14285            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14286                if (permissionsState.grantRuntimePermission(bp, userId)
14287                        != PERMISSION_OPERATION_FAILURE) {
14288                    writeRuntimePermissions = true;
14289                }
14290            // If permission review is enabled the permissions for a legacy apps
14291            // are represented as constantly granted runtime ones, so don't revoke.
14292            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14293                // Otherwise, reset the permission.
14294                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14295                switch (revokeResult) {
14296                    case PERMISSION_OPERATION_SUCCESS: {
14297                        writeRuntimePermissions = true;
14298                    } break;
14299
14300                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14301                        writeRuntimePermissions = true;
14302                        final int appId = ps.appId;
14303                        mHandler.post(new Runnable() {
14304                            @Override
14305                            public void run() {
14306                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14307                            }
14308                        });
14309                    } break;
14310                }
14311            }
14312        }
14313
14314        // Synchronously write as we are taking permissions away.
14315        if (writeRuntimePermissions) {
14316            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14317        }
14318
14319        // Synchronously write as we are taking permissions away.
14320        if (writeInstallPermissions) {
14321            mSettings.writeLPr();
14322        }
14323    }
14324
14325    /**
14326     * Remove entries from the keystore daemon. Will only remove it if the
14327     * {@code appId} is valid.
14328     */
14329    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14330        if (appId < 0) {
14331            return;
14332        }
14333
14334        final KeyStore keyStore = KeyStore.getInstance();
14335        if (keyStore != null) {
14336            if (userId == UserHandle.USER_ALL) {
14337                for (final int individual : sUserManager.getUserIds()) {
14338                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14339                }
14340            } else {
14341                keyStore.clearUid(UserHandle.getUid(userId, appId));
14342            }
14343        } else {
14344            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14345        }
14346    }
14347
14348    @Override
14349    public void deleteApplicationCacheFiles(final String packageName,
14350            final IPackageDataObserver observer) {
14351        mContext.enforceCallingOrSelfPermission(
14352                android.Manifest.permission.DELETE_CACHE_FILES, null);
14353        // Queue up an async operation since the package deletion may take a little while.
14354        final int userId = UserHandle.getCallingUserId();
14355        mHandler.post(new Runnable() {
14356            public void run() {
14357                mHandler.removeCallbacks(this);
14358                final boolean succeded;
14359                synchronized (mInstallLock) {
14360                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14361                }
14362                clearExternalStorageDataSync(packageName, userId, false);
14363                if (observer != null) {
14364                    try {
14365                        observer.onRemoveCompleted(packageName, succeded);
14366                    } catch (RemoteException e) {
14367                        Log.i(TAG, "Observer no longer exists.");
14368                    }
14369                } //end if observer
14370            } //end run
14371        });
14372    }
14373
14374    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14375        if (packageName == null) {
14376            Slog.w(TAG, "Attempt to delete null packageName.");
14377            return false;
14378        }
14379        PackageParser.Package p;
14380        synchronized (mPackages) {
14381            p = mPackages.get(packageName);
14382        }
14383        if (p == null) {
14384            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14385            return false;
14386        }
14387        final ApplicationInfo applicationInfo = p.applicationInfo;
14388        if (applicationInfo == null) {
14389            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14390            return false;
14391        }
14392        // TODO: triage flags as part of 26466827
14393        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14394        try {
14395            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14396                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14397        } catch (InstallerException e) {
14398            Slog.w(TAG, "Couldn't remove cache files for package "
14399                    + packageName + " u" + userId, e);
14400            return false;
14401        }
14402        return true;
14403    }
14404
14405    @Override
14406    public void getPackageSizeInfo(final String packageName, int userHandle,
14407            final IPackageStatsObserver observer) {
14408        mContext.enforceCallingOrSelfPermission(
14409                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14410        if (packageName == null) {
14411            throw new IllegalArgumentException("Attempt to get size of null packageName");
14412        }
14413
14414        PackageStats stats = new PackageStats(packageName, userHandle);
14415
14416        /*
14417         * Queue up an async operation since the package measurement may take a
14418         * little while.
14419         */
14420        Message msg = mHandler.obtainMessage(INIT_COPY);
14421        msg.obj = new MeasureParams(stats, observer);
14422        mHandler.sendMessage(msg);
14423    }
14424
14425    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14426            PackageStats pStats) {
14427        if (packageName == null) {
14428            Slog.w(TAG, "Attempt to get size of null packageName.");
14429            return false;
14430        }
14431        PackageParser.Package p;
14432        boolean dataOnly = false;
14433        String libDirRoot = null;
14434        String asecPath = null;
14435        PackageSetting ps = null;
14436        synchronized (mPackages) {
14437            p = mPackages.get(packageName);
14438            ps = mSettings.mPackages.get(packageName);
14439            if(p == null) {
14440                dataOnly = true;
14441                if((ps == null) || (ps.pkg == null)) {
14442                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14443                    return false;
14444                }
14445                p = ps.pkg;
14446            }
14447            if (ps != null) {
14448                libDirRoot = ps.legacyNativeLibraryPathString;
14449            }
14450            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14451                final long token = Binder.clearCallingIdentity();
14452                try {
14453                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14454                    if (secureContainerId != null) {
14455                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14456                    }
14457                } finally {
14458                    Binder.restoreCallingIdentity(token);
14459                }
14460            }
14461        }
14462        String publicSrcDir = null;
14463        if(!dataOnly) {
14464            final ApplicationInfo applicationInfo = p.applicationInfo;
14465            if (applicationInfo == null) {
14466                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14467                return false;
14468            }
14469            if (p.isForwardLocked()) {
14470                publicSrcDir = applicationInfo.getBaseResourcePath();
14471            }
14472        }
14473        // TODO: extend to measure size of split APKs
14474        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14475        // not just the first level.
14476        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14477        // just the primary.
14478        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14479
14480        String apkPath;
14481        File packageDir = new File(p.codePath);
14482
14483        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14484            apkPath = packageDir.getAbsolutePath();
14485            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14486            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14487                libDirRoot = null;
14488            }
14489        } else {
14490            apkPath = p.baseCodePath;
14491        }
14492
14493        // TODO: triage flags as part of 26466827
14494        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14495        try {
14496            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14497                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14498        } catch (InstallerException e) {
14499            return false;
14500        }
14501
14502        // Fix-up for forward-locked applications in ASEC containers.
14503        if (!isExternal(p)) {
14504            pStats.codeSize += pStats.externalCodeSize;
14505            pStats.externalCodeSize = 0L;
14506        }
14507
14508        return true;
14509    }
14510
14511
14512    @Override
14513    public void addPackageToPreferred(String packageName) {
14514        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14515    }
14516
14517    @Override
14518    public void removePackageFromPreferred(String packageName) {
14519        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14520    }
14521
14522    @Override
14523    public List<PackageInfo> getPreferredPackages(int flags) {
14524        return new ArrayList<PackageInfo>();
14525    }
14526
14527    private int getUidTargetSdkVersionLockedLPr(int uid) {
14528        Object obj = mSettings.getUserIdLPr(uid);
14529        if (obj instanceof SharedUserSetting) {
14530            final SharedUserSetting sus = (SharedUserSetting) obj;
14531            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14532            final Iterator<PackageSetting> it = sus.packages.iterator();
14533            while (it.hasNext()) {
14534                final PackageSetting ps = it.next();
14535                if (ps.pkg != null) {
14536                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14537                    if (v < vers) vers = v;
14538                }
14539            }
14540            return vers;
14541        } else if (obj instanceof PackageSetting) {
14542            final PackageSetting ps = (PackageSetting) obj;
14543            if (ps.pkg != null) {
14544                return ps.pkg.applicationInfo.targetSdkVersion;
14545            }
14546        }
14547        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14548    }
14549
14550    @Override
14551    public void addPreferredActivity(IntentFilter filter, int match,
14552            ComponentName[] set, ComponentName activity, int userId) {
14553        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14554                "Adding preferred");
14555    }
14556
14557    private void addPreferredActivityInternal(IntentFilter filter, int match,
14558            ComponentName[] set, ComponentName activity, boolean always, int userId,
14559            String opname) {
14560        // writer
14561        int callingUid = Binder.getCallingUid();
14562        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14563        if (filter.countActions() == 0) {
14564            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14565            return;
14566        }
14567        synchronized (mPackages) {
14568            if (mContext.checkCallingOrSelfPermission(
14569                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14570                    != PackageManager.PERMISSION_GRANTED) {
14571                if (getUidTargetSdkVersionLockedLPr(callingUid)
14572                        < Build.VERSION_CODES.FROYO) {
14573                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14574                            + callingUid);
14575                    return;
14576                }
14577                mContext.enforceCallingOrSelfPermission(
14578                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14579            }
14580
14581            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14582            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14583                    + userId + ":");
14584            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14585            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14586            scheduleWritePackageRestrictionsLocked(userId);
14587        }
14588    }
14589
14590    @Override
14591    public void replacePreferredActivity(IntentFilter filter, int match,
14592            ComponentName[] set, ComponentName activity, int userId) {
14593        if (filter.countActions() != 1) {
14594            throw new IllegalArgumentException(
14595                    "replacePreferredActivity expects filter to have only 1 action.");
14596        }
14597        if (filter.countDataAuthorities() != 0
14598                || filter.countDataPaths() != 0
14599                || filter.countDataSchemes() > 1
14600                || filter.countDataTypes() != 0) {
14601            throw new IllegalArgumentException(
14602                    "replacePreferredActivity expects filter to have no data authorities, " +
14603                    "paths, or types; and at most one scheme.");
14604        }
14605
14606        final int callingUid = Binder.getCallingUid();
14607        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14608        synchronized (mPackages) {
14609            if (mContext.checkCallingOrSelfPermission(
14610                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14611                    != PackageManager.PERMISSION_GRANTED) {
14612                if (getUidTargetSdkVersionLockedLPr(callingUid)
14613                        < Build.VERSION_CODES.FROYO) {
14614                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14615                            + Binder.getCallingUid());
14616                    return;
14617                }
14618                mContext.enforceCallingOrSelfPermission(
14619                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14620            }
14621
14622            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14623            if (pir != null) {
14624                // Get all of the existing entries that exactly match this filter.
14625                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14626                if (existing != null && existing.size() == 1) {
14627                    PreferredActivity cur = existing.get(0);
14628                    if (DEBUG_PREFERRED) {
14629                        Slog.i(TAG, "Checking replace of preferred:");
14630                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14631                        if (!cur.mPref.mAlways) {
14632                            Slog.i(TAG, "  -- CUR; not mAlways!");
14633                        } else {
14634                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14635                            Slog.i(TAG, "  -- CUR: mSet="
14636                                    + Arrays.toString(cur.mPref.mSetComponents));
14637                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14638                            Slog.i(TAG, "  -- NEW: mMatch="
14639                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14640                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14641                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14642                        }
14643                    }
14644                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14645                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14646                            && cur.mPref.sameSet(set)) {
14647                        // Setting the preferred activity to what it happens to be already
14648                        if (DEBUG_PREFERRED) {
14649                            Slog.i(TAG, "Replacing with same preferred activity "
14650                                    + cur.mPref.mShortComponent + " for user "
14651                                    + userId + ":");
14652                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14653                        }
14654                        return;
14655                    }
14656                }
14657
14658                if (existing != null) {
14659                    if (DEBUG_PREFERRED) {
14660                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14661                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14662                    }
14663                    for (int i = 0; i < existing.size(); i++) {
14664                        PreferredActivity pa = existing.get(i);
14665                        if (DEBUG_PREFERRED) {
14666                            Slog.i(TAG, "Removing existing preferred activity "
14667                                    + pa.mPref.mComponent + ":");
14668                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14669                        }
14670                        pir.removeFilter(pa);
14671                    }
14672                }
14673            }
14674            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14675                    "Replacing preferred");
14676        }
14677    }
14678
14679    @Override
14680    public void clearPackagePreferredActivities(String packageName) {
14681        final int uid = Binder.getCallingUid();
14682        // writer
14683        synchronized (mPackages) {
14684            PackageParser.Package pkg = mPackages.get(packageName);
14685            if (pkg == null || pkg.applicationInfo.uid != uid) {
14686                if (mContext.checkCallingOrSelfPermission(
14687                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14688                        != PackageManager.PERMISSION_GRANTED) {
14689                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14690                            < Build.VERSION_CODES.FROYO) {
14691                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14692                                + Binder.getCallingUid());
14693                        return;
14694                    }
14695                    mContext.enforceCallingOrSelfPermission(
14696                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14697                }
14698            }
14699
14700            int user = UserHandle.getCallingUserId();
14701            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14702                scheduleWritePackageRestrictionsLocked(user);
14703            }
14704        }
14705    }
14706
14707    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14708    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14709        ArrayList<PreferredActivity> removed = null;
14710        boolean changed = false;
14711        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14712            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14713            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14714            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14715                continue;
14716            }
14717            Iterator<PreferredActivity> it = pir.filterIterator();
14718            while (it.hasNext()) {
14719                PreferredActivity pa = it.next();
14720                // Mark entry for removal only if it matches the package name
14721                // and the entry is of type "always".
14722                if (packageName == null ||
14723                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14724                                && pa.mPref.mAlways)) {
14725                    if (removed == null) {
14726                        removed = new ArrayList<PreferredActivity>();
14727                    }
14728                    removed.add(pa);
14729                }
14730            }
14731            if (removed != null) {
14732                for (int j=0; j<removed.size(); j++) {
14733                    PreferredActivity pa = removed.get(j);
14734                    pir.removeFilter(pa);
14735                }
14736                changed = true;
14737            }
14738        }
14739        return changed;
14740    }
14741
14742    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14743    private void clearIntentFilterVerificationsLPw(int userId) {
14744        final int packageCount = mPackages.size();
14745        for (int i = 0; i < packageCount; i++) {
14746            PackageParser.Package pkg = mPackages.valueAt(i);
14747            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14748        }
14749    }
14750
14751    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14752    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14753        if (userId == UserHandle.USER_ALL) {
14754            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14755                    sUserManager.getUserIds())) {
14756                for (int oneUserId : sUserManager.getUserIds()) {
14757                    scheduleWritePackageRestrictionsLocked(oneUserId);
14758                }
14759            }
14760        } else {
14761            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14762                scheduleWritePackageRestrictionsLocked(userId);
14763            }
14764        }
14765    }
14766
14767    void clearDefaultBrowserIfNeeded(String packageName) {
14768        for (int oneUserId : sUserManager.getUserIds()) {
14769            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14770            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14771            if (packageName.equals(defaultBrowserPackageName)) {
14772                setDefaultBrowserPackageName(null, oneUserId);
14773            }
14774        }
14775    }
14776
14777    @Override
14778    public void resetApplicationPreferences(int userId) {
14779        mContext.enforceCallingOrSelfPermission(
14780                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14781        // writer
14782        synchronized (mPackages) {
14783            final long identity = Binder.clearCallingIdentity();
14784            try {
14785                clearPackagePreferredActivitiesLPw(null, userId);
14786                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14787                // TODO: We have to reset the default SMS and Phone. This requires
14788                // significant refactoring to keep all default apps in the package
14789                // manager (cleaner but more work) or have the services provide
14790                // callbacks to the package manager to request a default app reset.
14791                applyFactoryDefaultBrowserLPw(userId);
14792                clearIntentFilterVerificationsLPw(userId);
14793                primeDomainVerificationsLPw(userId);
14794                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14795                scheduleWritePackageRestrictionsLocked(userId);
14796            } finally {
14797                Binder.restoreCallingIdentity(identity);
14798            }
14799        }
14800    }
14801
14802    @Override
14803    public int getPreferredActivities(List<IntentFilter> outFilters,
14804            List<ComponentName> outActivities, String packageName) {
14805
14806        int num = 0;
14807        final int userId = UserHandle.getCallingUserId();
14808        // reader
14809        synchronized (mPackages) {
14810            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14811            if (pir != null) {
14812                final Iterator<PreferredActivity> it = pir.filterIterator();
14813                while (it.hasNext()) {
14814                    final PreferredActivity pa = it.next();
14815                    if (packageName == null
14816                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14817                                    && pa.mPref.mAlways)) {
14818                        if (outFilters != null) {
14819                            outFilters.add(new IntentFilter(pa));
14820                        }
14821                        if (outActivities != null) {
14822                            outActivities.add(pa.mPref.mComponent);
14823                        }
14824                    }
14825                }
14826            }
14827        }
14828
14829        return num;
14830    }
14831
14832    @Override
14833    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14834            int userId) {
14835        int callingUid = Binder.getCallingUid();
14836        if (callingUid != Process.SYSTEM_UID) {
14837            throw new SecurityException(
14838                    "addPersistentPreferredActivity can only be run by the system");
14839        }
14840        if (filter.countActions() == 0) {
14841            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14842            return;
14843        }
14844        synchronized (mPackages) {
14845            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14846                    ":");
14847            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14848            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14849                    new PersistentPreferredActivity(filter, activity));
14850            scheduleWritePackageRestrictionsLocked(userId);
14851        }
14852    }
14853
14854    @Override
14855    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14856        int callingUid = Binder.getCallingUid();
14857        if (callingUid != Process.SYSTEM_UID) {
14858            throw new SecurityException(
14859                    "clearPackagePersistentPreferredActivities can only be run by the system");
14860        }
14861        ArrayList<PersistentPreferredActivity> removed = null;
14862        boolean changed = false;
14863        synchronized (mPackages) {
14864            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14865                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14866                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14867                        .valueAt(i);
14868                if (userId != thisUserId) {
14869                    continue;
14870                }
14871                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14872                while (it.hasNext()) {
14873                    PersistentPreferredActivity ppa = it.next();
14874                    // Mark entry for removal only if it matches the package name.
14875                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14876                        if (removed == null) {
14877                            removed = new ArrayList<PersistentPreferredActivity>();
14878                        }
14879                        removed.add(ppa);
14880                    }
14881                }
14882                if (removed != null) {
14883                    for (int j=0; j<removed.size(); j++) {
14884                        PersistentPreferredActivity ppa = removed.get(j);
14885                        ppir.removeFilter(ppa);
14886                    }
14887                    changed = true;
14888                }
14889            }
14890
14891            if (changed) {
14892                scheduleWritePackageRestrictionsLocked(userId);
14893            }
14894        }
14895    }
14896
14897    /**
14898     * Common machinery for picking apart a restored XML blob and passing
14899     * it to a caller-supplied functor to be applied to the running system.
14900     */
14901    private void restoreFromXml(XmlPullParser parser, int userId,
14902            String expectedStartTag, BlobXmlRestorer functor)
14903            throws IOException, XmlPullParserException {
14904        int type;
14905        while ((type = parser.next()) != XmlPullParser.START_TAG
14906                && type != XmlPullParser.END_DOCUMENT) {
14907        }
14908        if (type != XmlPullParser.START_TAG) {
14909            // oops didn't find a start tag?!
14910            if (DEBUG_BACKUP) {
14911                Slog.e(TAG, "Didn't find start tag during restore");
14912            }
14913            return;
14914        }
14915Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14916        // this is supposed to be TAG_PREFERRED_BACKUP
14917        if (!expectedStartTag.equals(parser.getName())) {
14918            if (DEBUG_BACKUP) {
14919                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14920            }
14921            return;
14922        }
14923
14924        // skip interfering stuff, then we're aligned with the backing implementation
14925        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14926Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14927        functor.apply(parser, userId);
14928    }
14929
14930    private interface BlobXmlRestorer {
14931        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14932    }
14933
14934    /**
14935     * Non-Binder method, support for the backup/restore mechanism: write the
14936     * full set of preferred activities in its canonical XML format.  Returns the
14937     * XML output as a byte array, or null if there is none.
14938     */
14939    @Override
14940    public byte[] getPreferredActivityBackup(int userId) {
14941        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14942            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14943        }
14944
14945        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14946        try {
14947            final XmlSerializer serializer = new FastXmlSerializer();
14948            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14949            serializer.startDocument(null, true);
14950            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14951
14952            synchronized (mPackages) {
14953                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14954            }
14955
14956            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14957            serializer.endDocument();
14958            serializer.flush();
14959        } catch (Exception e) {
14960            if (DEBUG_BACKUP) {
14961                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14962            }
14963            return null;
14964        }
14965
14966        return dataStream.toByteArray();
14967    }
14968
14969    @Override
14970    public void restorePreferredActivities(byte[] backup, int userId) {
14971        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14972            throw new SecurityException("Only the system may call restorePreferredActivities()");
14973        }
14974
14975        try {
14976            final XmlPullParser parser = Xml.newPullParser();
14977            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14978            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14979                    new BlobXmlRestorer() {
14980                        @Override
14981                        public void apply(XmlPullParser parser, int userId)
14982                                throws XmlPullParserException, IOException {
14983                            synchronized (mPackages) {
14984                                mSettings.readPreferredActivitiesLPw(parser, userId);
14985                            }
14986                        }
14987                    } );
14988        } catch (Exception e) {
14989            if (DEBUG_BACKUP) {
14990                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14991            }
14992        }
14993    }
14994
14995    /**
14996     * Non-Binder method, support for the backup/restore mechanism: write the
14997     * default browser (etc) settings in its canonical XML format.  Returns the default
14998     * browser XML representation as a byte array, or null if there is none.
14999     */
15000    @Override
15001    public byte[] getDefaultAppsBackup(int userId) {
15002        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15003            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15004        }
15005
15006        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15007        try {
15008            final XmlSerializer serializer = new FastXmlSerializer();
15009            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15010            serializer.startDocument(null, true);
15011            serializer.startTag(null, TAG_DEFAULT_APPS);
15012
15013            synchronized (mPackages) {
15014                mSettings.writeDefaultAppsLPr(serializer, userId);
15015            }
15016
15017            serializer.endTag(null, TAG_DEFAULT_APPS);
15018            serializer.endDocument();
15019            serializer.flush();
15020        } catch (Exception e) {
15021            if (DEBUG_BACKUP) {
15022                Slog.e(TAG, "Unable to write default apps for backup", e);
15023            }
15024            return null;
15025        }
15026
15027        return dataStream.toByteArray();
15028    }
15029
15030    @Override
15031    public void restoreDefaultApps(byte[] backup, int userId) {
15032        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15033            throw new SecurityException("Only the system may call restoreDefaultApps()");
15034        }
15035
15036        try {
15037            final XmlPullParser parser = Xml.newPullParser();
15038            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15039            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15040                    new BlobXmlRestorer() {
15041                        @Override
15042                        public void apply(XmlPullParser parser, int userId)
15043                                throws XmlPullParserException, IOException {
15044                            synchronized (mPackages) {
15045                                mSettings.readDefaultAppsLPw(parser, userId);
15046                            }
15047                        }
15048                    } );
15049        } catch (Exception e) {
15050            if (DEBUG_BACKUP) {
15051                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15052            }
15053        }
15054    }
15055
15056    @Override
15057    public byte[] getIntentFilterVerificationBackup(int userId) {
15058        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15059            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15060        }
15061
15062        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15063        try {
15064            final XmlSerializer serializer = new FastXmlSerializer();
15065            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15066            serializer.startDocument(null, true);
15067            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15068
15069            synchronized (mPackages) {
15070                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15071            }
15072
15073            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15074            serializer.endDocument();
15075            serializer.flush();
15076        } catch (Exception e) {
15077            if (DEBUG_BACKUP) {
15078                Slog.e(TAG, "Unable to write default apps for backup", e);
15079            }
15080            return null;
15081        }
15082
15083        return dataStream.toByteArray();
15084    }
15085
15086    @Override
15087    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15088        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15089            throw new SecurityException("Only the system may call restorePreferredActivities()");
15090        }
15091
15092        try {
15093            final XmlPullParser parser = Xml.newPullParser();
15094            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15095            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15096                    new BlobXmlRestorer() {
15097                        @Override
15098                        public void apply(XmlPullParser parser, int userId)
15099                                throws XmlPullParserException, IOException {
15100                            synchronized (mPackages) {
15101                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15102                                mSettings.writeLPr();
15103                            }
15104                        }
15105                    } );
15106        } catch (Exception e) {
15107            if (DEBUG_BACKUP) {
15108                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15109            }
15110        }
15111    }
15112
15113    @Override
15114    public byte[] getPermissionGrantBackup(int userId) {
15115        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15116            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15117        }
15118
15119        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15120        try {
15121            final XmlSerializer serializer = new FastXmlSerializer();
15122            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15123            serializer.startDocument(null, true);
15124            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15125
15126            synchronized (mPackages) {
15127                serializeRuntimePermissionGrantsLPr(serializer, userId);
15128            }
15129
15130            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15131            serializer.endDocument();
15132            serializer.flush();
15133        } catch (Exception e) {
15134            if (DEBUG_BACKUP) {
15135                Slog.e(TAG, "Unable to write default apps for backup", e);
15136            }
15137            return null;
15138        }
15139
15140        return dataStream.toByteArray();
15141    }
15142
15143    @Override
15144    public void restorePermissionGrants(byte[] backup, int userId) {
15145        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15146            throw new SecurityException("Only the system may call restorePermissionGrants()");
15147        }
15148
15149        try {
15150            final XmlPullParser parser = Xml.newPullParser();
15151            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15152            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15153                    new BlobXmlRestorer() {
15154                        @Override
15155                        public void apply(XmlPullParser parser, int userId)
15156                                throws XmlPullParserException, IOException {
15157                            synchronized (mPackages) {
15158                                processRestoredPermissionGrantsLPr(parser, userId);
15159                            }
15160                        }
15161                    } );
15162        } catch (Exception e) {
15163            if (DEBUG_BACKUP) {
15164                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15165            }
15166        }
15167    }
15168
15169    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15170            throws IOException {
15171        serializer.startTag(null, TAG_ALL_GRANTS);
15172
15173        final int N = mSettings.mPackages.size();
15174        for (int i = 0; i < N; i++) {
15175            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15176            boolean pkgGrantsKnown = false;
15177
15178            PermissionsState packagePerms = ps.getPermissionsState();
15179
15180            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15181                final int grantFlags = state.getFlags();
15182                // only look at grants that are not system/policy fixed
15183                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15184                    final boolean isGranted = state.isGranted();
15185                    // And only back up the user-twiddled state bits
15186                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15187                        final String packageName = mSettings.mPackages.keyAt(i);
15188                        if (!pkgGrantsKnown) {
15189                            serializer.startTag(null, TAG_GRANT);
15190                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15191                            pkgGrantsKnown = true;
15192                        }
15193
15194                        final boolean userSet =
15195                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15196                        final boolean userFixed =
15197                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15198                        final boolean revoke =
15199                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15200
15201                        serializer.startTag(null, TAG_PERMISSION);
15202                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15203                        if (isGranted) {
15204                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15205                        }
15206                        if (userSet) {
15207                            serializer.attribute(null, ATTR_USER_SET, "true");
15208                        }
15209                        if (userFixed) {
15210                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15211                        }
15212                        if (revoke) {
15213                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15214                        }
15215                        serializer.endTag(null, TAG_PERMISSION);
15216                    }
15217                }
15218            }
15219
15220            if (pkgGrantsKnown) {
15221                serializer.endTag(null, TAG_GRANT);
15222            }
15223        }
15224
15225        serializer.endTag(null, TAG_ALL_GRANTS);
15226    }
15227
15228    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15229            throws XmlPullParserException, IOException {
15230        String pkgName = null;
15231        int outerDepth = parser.getDepth();
15232        int type;
15233        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15234                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15235            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15236                continue;
15237            }
15238
15239            final String tagName = parser.getName();
15240            if (tagName.equals(TAG_GRANT)) {
15241                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15242                if (DEBUG_BACKUP) {
15243                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15244                }
15245            } else if (tagName.equals(TAG_PERMISSION)) {
15246
15247                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15248                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15249
15250                int newFlagSet = 0;
15251                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15252                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15253                }
15254                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15255                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15256                }
15257                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15258                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15259                }
15260                if (DEBUG_BACKUP) {
15261                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15262                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15263                }
15264                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15265                if (ps != null) {
15266                    // Already installed so we apply the grant immediately
15267                    if (DEBUG_BACKUP) {
15268                        Slog.v(TAG, "        + already installed; applying");
15269                    }
15270                    PermissionsState perms = ps.getPermissionsState();
15271                    BasePermission bp = mSettings.mPermissions.get(permName);
15272                    if (bp != null) {
15273                        if (isGranted) {
15274                            perms.grantRuntimePermission(bp, userId);
15275                        }
15276                        if (newFlagSet != 0) {
15277                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15278                        }
15279                    }
15280                } else {
15281                    // Need to wait for post-restore install to apply the grant
15282                    if (DEBUG_BACKUP) {
15283                        Slog.v(TAG, "        - not yet installed; saving for later");
15284                    }
15285                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15286                            isGranted, newFlagSet, userId);
15287                }
15288            } else {
15289                PackageManagerService.reportSettingsProblem(Log.WARN,
15290                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15291                XmlUtils.skipCurrentTag(parser);
15292            }
15293        }
15294
15295        scheduleWriteSettingsLocked();
15296        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15297    }
15298
15299    @Override
15300    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15301            int sourceUserId, int targetUserId, int flags) {
15302        mContext.enforceCallingOrSelfPermission(
15303                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15304        int callingUid = Binder.getCallingUid();
15305        enforceOwnerRights(ownerPackage, callingUid);
15306        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15307        if (intentFilter.countActions() == 0) {
15308            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15309            return;
15310        }
15311        synchronized (mPackages) {
15312            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15313                    ownerPackage, targetUserId, flags);
15314            CrossProfileIntentResolver resolver =
15315                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15316            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15317            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15318            if (existing != null) {
15319                int size = existing.size();
15320                for (int i = 0; i < size; i++) {
15321                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15322                        return;
15323                    }
15324                }
15325            }
15326            resolver.addFilter(newFilter);
15327            scheduleWritePackageRestrictionsLocked(sourceUserId);
15328        }
15329    }
15330
15331    @Override
15332    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15333        mContext.enforceCallingOrSelfPermission(
15334                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15335        int callingUid = Binder.getCallingUid();
15336        enforceOwnerRights(ownerPackage, callingUid);
15337        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15338        synchronized (mPackages) {
15339            CrossProfileIntentResolver resolver =
15340                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15341            ArraySet<CrossProfileIntentFilter> set =
15342                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15343            for (CrossProfileIntentFilter filter : set) {
15344                if (filter.getOwnerPackage().equals(ownerPackage)) {
15345                    resolver.removeFilter(filter);
15346                }
15347            }
15348            scheduleWritePackageRestrictionsLocked(sourceUserId);
15349        }
15350    }
15351
15352    // Enforcing that callingUid is owning pkg on userId
15353    private void enforceOwnerRights(String pkg, int callingUid) {
15354        // The system owns everything.
15355        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15356            return;
15357        }
15358        int callingUserId = UserHandle.getUserId(callingUid);
15359        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15360        if (pi == null) {
15361            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15362                    + callingUserId);
15363        }
15364        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15365            throw new SecurityException("Calling uid " + callingUid
15366                    + " does not own package " + pkg);
15367        }
15368    }
15369
15370    @Override
15371    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15372        Intent intent = new Intent(Intent.ACTION_MAIN);
15373        intent.addCategory(Intent.CATEGORY_HOME);
15374
15375        final int callingUserId = UserHandle.getCallingUserId();
15376        List<ResolveInfo> list = queryIntentActivities(intent, null,
15377                PackageManager.GET_META_DATA, callingUserId);
15378        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15379                true, false, false, callingUserId);
15380
15381        allHomeCandidates.clear();
15382        if (list != null) {
15383            for (ResolveInfo ri : list) {
15384                allHomeCandidates.add(ri);
15385            }
15386        }
15387        return (preferred == null || preferred.activityInfo == null)
15388                ? null
15389                : new ComponentName(preferred.activityInfo.packageName,
15390                        preferred.activityInfo.name);
15391    }
15392
15393    @Override
15394    public void setApplicationEnabledSetting(String appPackageName,
15395            int newState, int flags, int userId, String callingPackage) {
15396        if (!sUserManager.exists(userId)) return;
15397        if (callingPackage == null) {
15398            callingPackage = Integer.toString(Binder.getCallingUid());
15399        }
15400        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15401    }
15402
15403    @Override
15404    public void setComponentEnabledSetting(ComponentName componentName,
15405            int newState, int flags, int userId) {
15406        if (!sUserManager.exists(userId)) return;
15407        setEnabledSetting(componentName.getPackageName(),
15408                componentName.getClassName(), newState, flags, userId, null);
15409    }
15410
15411    private void setEnabledSetting(final String packageName, String className, int newState,
15412            final int flags, int userId, String callingPackage) {
15413        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15414              || newState == COMPONENT_ENABLED_STATE_ENABLED
15415              || newState == COMPONENT_ENABLED_STATE_DISABLED
15416              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15417              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15418            throw new IllegalArgumentException("Invalid new component state: "
15419                    + newState);
15420        }
15421        PackageSetting pkgSetting;
15422        final int uid = Binder.getCallingUid();
15423        final int permission = mContext.checkCallingOrSelfPermission(
15424                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15425        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15426        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15427        boolean sendNow = false;
15428        boolean isApp = (className == null);
15429        String componentName = isApp ? packageName : className;
15430        int packageUid = -1;
15431        ArrayList<String> components;
15432
15433        // writer
15434        synchronized (mPackages) {
15435            pkgSetting = mSettings.mPackages.get(packageName);
15436            if (pkgSetting == null) {
15437                if (className == null) {
15438                    throw new IllegalArgumentException("Unknown package: " + packageName);
15439                }
15440                throw new IllegalArgumentException(
15441                        "Unknown component: " + packageName + "/" + className);
15442            }
15443            // Allow root and verify that userId is not being specified by a different user
15444            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15445                throw new SecurityException(
15446                        "Permission Denial: attempt to change component state from pid="
15447                        + Binder.getCallingPid()
15448                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15449            }
15450            if (className == null) {
15451                // We're dealing with an application/package level state change
15452                if (pkgSetting.getEnabled(userId) == newState) {
15453                    // Nothing to do
15454                    return;
15455                }
15456                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15457                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15458                    // Don't care about who enables an app.
15459                    callingPackage = null;
15460                }
15461                pkgSetting.setEnabled(newState, userId, callingPackage);
15462                // pkgSetting.pkg.mSetEnabled = newState;
15463            } else {
15464                // We're dealing with a component level state change
15465                // First, verify that this is a valid class name.
15466                PackageParser.Package pkg = pkgSetting.pkg;
15467                if (pkg == null || !pkg.hasComponentClassName(className)) {
15468                    if (pkg != null &&
15469                            pkg.applicationInfo.targetSdkVersion >=
15470                                    Build.VERSION_CODES.JELLY_BEAN) {
15471                        throw new IllegalArgumentException("Component class " + className
15472                                + " does not exist in " + packageName);
15473                    } else {
15474                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15475                                + className + " does not exist in " + packageName);
15476                    }
15477                }
15478                switch (newState) {
15479                case COMPONENT_ENABLED_STATE_ENABLED:
15480                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15481                        return;
15482                    }
15483                    break;
15484                case COMPONENT_ENABLED_STATE_DISABLED:
15485                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15486                        return;
15487                    }
15488                    break;
15489                case COMPONENT_ENABLED_STATE_DEFAULT:
15490                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15491                        return;
15492                    }
15493                    break;
15494                default:
15495                    Slog.e(TAG, "Invalid new component state: " + newState);
15496                    return;
15497                }
15498            }
15499            scheduleWritePackageRestrictionsLocked(userId);
15500            components = mPendingBroadcasts.get(userId, packageName);
15501            final boolean newPackage = components == null;
15502            if (newPackage) {
15503                components = new ArrayList<String>();
15504            }
15505            if (!components.contains(componentName)) {
15506                components.add(componentName);
15507            }
15508            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15509                sendNow = true;
15510                // Purge entry from pending broadcast list if another one exists already
15511                // since we are sending one right away.
15512                mPendingBroadcasts.remove(userId, packageName);
15513            } else {
15514                if (newPackage) {
15515                    mPendingBroadcasts.put(userId, packageName, components);
15516                }
15517                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15518                    // Schedule a message
15519                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15520                }
15521            }
15522        }
15523
15524        long callingId = Binder.clearCallingIdentity();
15525        try {
15526            if (sendNow) {
15527                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15528                sendPackageChangedBroadcast(packageName,
15529                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15530            }
15531        } finally {
15532            Binder.restoreCallingIdentity(callingId);
15533        }
15534    }
15535
15536    private void sendPackageChangedBroadcast(String packageName,
15537            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15538        if (DEBUG_INSTALL)
15539            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15540                    + componentNames);
15541        Bundle extras = new Bundle(4);
15542        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15543        String nameList[] = new String[componentNames.size()];
15544        componentNames.toArray(nameList);
15545        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15546        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15547        extras.putInt(Intent.EXTRA_UID, packageUid);
15548        // If this is not reporting a change of the overall package, then only send it
15549        // to registered receivers.  We don't want to launch a swath of apps for every
15550        // little component state change.
15551        final int flags = !componentNames.contains(packageName)
15552                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15553        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15554                new int[] {UserHandle.getUserId(packageUid)});
15555    }
15556
15557    @Override
15558    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15559        if (!sUserManager.exists(userId)) return;
15560        final int uid = Binder.getCallingUid();
15561        final int permission = mContext.checkCallingOrSelfPermission(
15562                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15563        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15564        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15565        // writer
15566        synchronized (mPackages) {
15567            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15568                    allowedByPermission, uid, userId)) {
15569                scheduleWritePackageRestrictionsLocked(userId);
15570            }
15571        }
15572    }
15573
15574    @Override
15575    public String getInstallerPackageName(String packageName) {
15576        // reader
15577        synchronized (mPackages) {
15578            return mSettings.getInstallerPackageNameLPr(packageName);
15579        }
15580    }
15581
15582    @Override
15583    public int getApplicationEnabledSetting(String packageName, int userId) {
15584        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15585        int uid = Binder.getCallingUid();
15586        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15587        // reader
15588        synchronized (mPackages) {
15589            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15590        }
15591    }
15592
15593    @Override
15594    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15595        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15596        int uid = Binder.getCallingUid();
15597        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15598        // reader
15599        synchronized (mPackages) {
15600            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15601        }
15602    }
15603
15604    @Override
15605    public void enterSafeMode() {
15606        enforceSystemOrRoot("Only the system can request entering safe mode");
15607
15608        if (!mSystemReady) {
15609            mSafeMode = true;
15610        }
15611    }
15612
15613    @Override
15614    public void systemReady() {
15615        mSystemReady = true;
15616
15617        // Read the compatibilty setting when the system is ready.
15618        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15619                mContext.getContentResolver(),
15620                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15621        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15622        if (DEBUG_SETTINGS) {
15623            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15624        }
15625
15626        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15627
15628        synchronized (mPackages) {
15629            // Verify that all of the preferred activity components actually
15630            // exist.  It is possible for applications to be updated and at
15631            // that point remove a previously declared activity component that
15632            // had been set as a preferred activity.  We try to clean this up
15633            // the next time we encounter that preferred activity, but it is
15634            // possible for the user flow to never be able to return to that
15635            // situation so here we do a sanity check to make sure we haven't
15636            // left any junk around.
15637            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15638            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15639                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15640                removed.clear();
15641                for (PreferredActivity pa : pir.filterSet()) {
15642                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15643                        removed.add(pa);
15644                    }
15645                }
15646                if (removed.size() > 0) {
15647                    for (int r=0; r<removed.size(); r++) {
15648                        PreferredActivity pa = removed.get(r);
15649                        Slog.w(TAG, "Removing dangling preferred activity: "
15650                                + pa.mPref.mComponent);
15651                        pir.removeFilter(pa);
15652                    }
15653                    mSettings.writePackageRestrictionsLPr(
15654                            mSettings.mPreferredActivities.keyAt(i));
15655                }
15656            }
15657
15658            for (int userId : UserManagerService.getInstance().getUserIds()) {
15659                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15660                    grantPermissionsUserIds = ArrayUtils.appendInt(
15661                            grantPermissionsUserIds, userId);
15662                }
15663            }
15664        }
15665        sUserManager.systemReady();
15666
15667        // If we upgraded grant all default permissions before kicking off.
15668        for (int userId : grantPermissionsUserIds) {
15669            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15670        }
15671
15672        // Kick off any messages waiting for system ready
15673        if (mPostSystemReadyMessages != null) {
15674            for (Message msg : mPostSystemReadyMessages) {
15675                msg.sendToTarget();
15676            }
15677            mPostSystemReadyMessages = null;
15678        }
15679
15680        // Watch for external volumes that come and go over time
15681        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15682        storage.registerListener(mStorageListener);
15683
15684        mInstallerService.systemReady();
15685        mPackageDexOptimizer.systemReady();
15686
15687        MountServiceInternal mountServiceInternal = LocalServices.getService(
15688                MountServiceInternal.class);
15689        mountServiceInternal.addExternalStoragePolicy(
15690                new MountServiceInternal.ExternalStorageMountPolicy() {
15691            @Override
15692            public int getMountMode(int uid, String packageName) {
15693                if (Process.isIsolated(uid)) {
15694                    return Zygote.MOUNT_EXTERNAL_NONE;
15695                }
15696                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15697                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15698                }
15699                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15700                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15701                }
15702                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15703                    return Zygote.MOUNT_EXTERNAL_READ;
15704                }
15705                return Zygote.MOUNT_EXTERNAL_WRITE;
15706            }
15707
15708            @Override
15709            public boolean hasExternalStorage(int uid, String packageName) {
15710                return true;
15711            }
15712        });
15713    }
15714
15715    @Override
15716    public boolean isSafeMode() {
15717        return mSafeMode;
15718    }
15719
15720    @Override
15721    public boolean hasSystemUidErrors() {
15722        return mHasSystemUidErrors;
15723    }
15724
15725    static String arrayToString(int[] array) {
15726        StringBuffer buf = new StringBuffer(128);
15727        buf.append('[');
15728        if (array != null) {
15729            for (int i=0; i<array.length; i++) {
15730                if (i > 0) buf.append(", ");
15731                buf.append(array[i]);
15732            }
15733        }
15734        buf.append(']');
15735        return buf.toString();
15736    }
15737
15738    static class DumpState {
15739        public static final int DUMP_LIBS = 1 << 0;
15740        public static final int DUMP_FEATURES = 1 << 1;
15741        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15742        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15743        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15744        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15745        public static final int DUMP_PERMISSIONS = 1 << 6;
15746        public static final int DUMP_PACKAGES = 1 << 7;
15747        public static final int DUMP_SHARED_USERS = 1 << 8;
15748        public static final int DUMP_MESSAGES = 1 << 9;
15749        public static final int DUMP_PROVIDERS = 1 << 10;
15750        public static final int DUMP_VERIFIERS = 1 << 11;
15751        public static final int DUMP_PREFERRED = 1 << 12;
15752        public static final int DUMP_PREFERRED_XML = 1 << 13;
15753        public static final int DUMP_KEYSETS = 1 << 14;
15754        public static final int DUMP_VERSION = 1 << 15;
15755        public static final int DUMP_INSTALLS = 1 << 16;
15756        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15757        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15758
15759        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15760
15761        private int mTypes;
15762
15763        private int mOptions;
15764
15765        private boolean mTitlePrinted;
15766
15767        private SharedUserSetting mSharedUser;
15768
15769        public boolean isDumping(int type) {
15770            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15771                return true;
15772            }
15773
15774            return (mTypes & type) != 0;
15775        }
15776
15777        public void setDump(int type) {
15778            mTypes |= type;
15779        }
15780
15781        public boolean isOptionEnabled(int option) {
15782            return (mOptions & option) != 0;
15783        }
15784
15785        public void setOptionEnabled(int option) {
15786            mOptions |= option;
15787        }
15788
15789        public boolean onTitlePrinted() {
15790            final boolean printed = mTitlePrinted;
15791            mTitlePrinted = true;
15792            return printed;
15793        }
15794
15795        public boolean getTitlePrinted() {
15796            return mTitlePrinted;
15797        }
15798
15799        public void setTitlePrinted(boolean enabled) {
15800            mTitlePrinted = enabled;
15801        }
15802
15803        public SharedUserSetting getSharedUser() {
15804            return mSharedUser;
15805        }
15806
15807        public void setSharedUser(SharedUserSetting user) {
15808            mSharedUser = user;
15809        }
15810    }
15811
15812    @Override
15813    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15814            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15815        (new PackageManagerShellCommand(this)).exec(
15816                this, in, out, err, args, resultReceiver);
15817    }
15818
15819    @Override
15820    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15821        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15822                != PackageManager.PERMISSION_GRANTED) {
15823            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15824                    + Binder.getCallingPid()
15825                    + ", uid=" + Binder.getCallingUid()
15826                    + " without permission "
15827                    + android.Manifest.permission.DUMP);
15828            return;
15829        }
15830
15831        DumpState dumpState = new DumpState();
15832        boolean fullPreferred = false;
15833        boolean checkin = false;
15834
15835        String packageName = null;
15836        ArraySet<String> permissionNames = null;
15837
15838        int opti = 0;
15839        while (opti < args.length) {
15840            String opt = args[opti];
15841            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15842                break;
15843            }
15844            opti++;
15845
15846            if ("-a".equals(opt)) {
15847                // Right now we only know how to print all.
15848            } else if ("-h".equals(opt)) {
15849                pw.println("Package manager dump options:");
15850                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15851                pw.println("    --checkin: dump for a checkin");
15852                pw.println("    -f: print details of intent filters");
15853                pw.println("    -h: print this help");
15854                pw.println("  cmd may be one of:");
15855                pw.println("    l[ibraries]: list known shared libraries");
15856                pw.println("    f[eatures]: list device features");
15857                pw.println("    k[eysets]: print known keysets");
15858                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15859                pw.println("    perm[issions]: dump permissions");
15860                pw.println("    permission [name ...]: dump declaration and use of given permission");
15861                pw.println("    pref[erred]: print preferred package settings");
15862                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15863                pw.println("    prov[iders]: dump content providers");
15864                pw.println("    p[ackages]: dump installed packages");
15865                pw.println("    s[hared-users]: dump shared user IDs");
15866                pw.println("    m[essages]: print collected runtime messages");
15867                pw.println("    v[erifiers]: print package verifier info");
15868                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15869                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15870                pw.println("    version: print database version info");
15871                pw.println("    write: write current settings now");
15872                pw.println("    installs: details about install sessions");
15873                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15874                pw.println("    <package.name>: info about given package");
15875                return;
15876            } else if ("--checkin".equals(opt)) {
15877                checkin = true;
15878            } else if ("-f".equals(opt)) {
15879                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15880            } else {
15881                pw.println("Unknown argument: " + opt + "; use -h for help");
15882            }
15883        }
15884
15885        // Is the caller requesting to dump a particular piece of data?
15886        if (opti < args.length) {
15887            String cmd = args[opti];
15888            opti++;
15889            // Is this a package name?
15890            if ("android".equals(cmd) || cmd.contains(".")) {
15891                packageName = cmd;
15892                // When dumping a single package, we always dump all of its
15893                // filter information since the amount of data will be reasonable.
15894                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15895            } else if ("check-permission".equals(cmd)) {
15896                if (opti >= args.length) {
15897                    pw.println("Error: check-permission missing permission argument");
15898                    return;
15899                }
15900                String perm = args[opti];
15901                opti++;
15902                if (opti >= args.length) {
15903                    pw.println("Error: check-permission missing package argument");
15904                    return;
15905                }
15906                String pkg = args[opti];
15907                opti++;
15908                int user = UserHandle.getUserId(Binder.getCallingUid());
15909                if (opti < args.length) {
15910                    try {
15911                        user = Integer.parseInt(args[opti]);
15912                    } catch (NumberFormatException e) {
15913                        pw.println("Error: check-permission user argument is not a number: "
15914                                + args[opti]);
15915                        return;
15916                    }
15917                }
15918                pw.println(checkPermission(perm, pkg, user));
15919                return;
15920            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15921                dumpState.setDump(DumpState.DUMP_LIBS);
15922            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15923                dumpState.setDump(DumpState.DUMP_FEATURES);
15924            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15925                if (opti >= args.length) {
15926                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15927                            | DumpState.DUMP_SERVICE_RESOLVERS
15928                            | DumpState.DUMP_RECEIVER_RESOLVERS
15929                            | DumpState.DUMP_CONTENT_RESOLVERS);
15930                } else {
15931                    while (opti < args.length) {
15932                        String name = args[opti];
15933                        if ("a".equals(name) || "activity".equals(name)) {
15934                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15935                        } else if ("s".equals(name) || "service".equals(name)) {
15936                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15937                        } else if ("r".equals(name) || "receiver".equals(name)) {
15938                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15939                        } else if ("c".equals(name) || "content".equals(name)) {
15940                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15941                        } else {
15942                            pw.println("Error: unknown resolver table type: " + name);
15943                            return;
15944                        }
15945                        opti++;
15946                    }
15947                }
15948            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15949                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15950            } else if ("permission".equals(cmd)) {
15951                if (opti >= args.length) {
15952                    pw.println("Error: permission requires permission name");
15953                    return;
15954                }
15955                permissionNames = new ArraySet<>();
15956                while (opti < args.length) {
15957                    permissionNames.add(args[opti]);
15958                    opti++;
15959                }
15960                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15961                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15962            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15963                dumpState.setDump(DumpState.DUMP_PREFERRED);
15964            } else if ("preferred-xml".equals(cmd)) {
15965                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15966                if (opti < args.length && "--full".equals(args[opti])) {
15967                    fullPreferred = true;
15968                    opti++;
15969                }
15970            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15971                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15972            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15973                dumpState.setDump(DumpState.DUMP_PACKAGES);
15974            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15975                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15976            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15977                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15978            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15979                dumpState.setDump(DumpState.DUMP_MESSAGES);
15980            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15981                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15982            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15983                    || "intent-filter-verifiers".equals(cmd)) {
15984                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15985            } else if ("version".equals(cmd)) {
15986                dumpState.setDump(DumpState.DUMP_VERSION);
15987            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15988                dumpState.setDump(DumpState.DUMP_KEYSETS);
15989            } else if ("installs".equals(cmd)) {
15990                dumpState.setDump(DumpState.DUMP_INSTALLS);
15991            } else if ("write".equals(cmd)) {
15992                synchronized (mPackages) {
15993                    mSettings.writeLPr();
15994                    pw.println("Settings written.");
15995                    return;
15996                }
15997            }
15998        }
15999
16000        if (checkin) {
16001            pw.println("vers,1");
16002        }
16003
16004        // reader
16005        synchronized (mPackages) {
16006            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16007                if (!checkin) {
16008                    if (dumpState.onTitlePrinted())
16009                        pw.println();
16010                    pw.println("Database versions:");
16011                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16012                }
16013            }
16014
16015            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16016                if (!checkin) {
16017                    if (dumpState.onTitlePrinted())
16018                        pw.println();
16019                    pw.println("Verifiers:");
16020                    pw.print("  Required: ");
16021                    pw.print(mRequiredVerifierPackage);
16022                    pw.print(" (uid=");
16023                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16024                            UserHandle.USER_SYSTEM));
16025                    pw.println(")");
16026                } else if (mRequiredVerifierPackage != null) {
16027                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16028                    pw.print(",");
16029                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16030                            UserHandle.USER_SYSTEM));
16031                }
16032            }
16033
16034            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16035                    packageName == null) {
16036                if (mIntentFilterVerifierComponent != null) {
16037                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16038                    if (!checkin) {
16039                        if (dumpState.onTitlePrinted())
16040                            pw.println();
16041                        pw.println("Intent Filter Verifier:");
16042                        pw.print("  Using: ");
16043                        pw.print(verifierPackageName);
16044                        pw.print(" (uid=");
16045                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16046                                UserHandle.USER_SYSTEM));
16047                        pw.println(")");
16048                    } else if (verifierPackageName != null) {
16049                        pw.print("ifv,"); pw.print(verifierPackageName);
16050                        pw.print(",");
16051                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16052                                UserHandle.USER_SYSTEM));
16053                    }
16054                } else {
16055                    pw.println();
16056                    pw.println("No Intent Filter Verifier available!");
16057                }
16058            }
16059
16060            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16061                boolean printedHeader = false;
16062                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16063                while (it.hasNext()) {
16064                    String name = it.next();
16065                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16066                    if (!checkin) {
16067                        if (!printedHeader) {
16068                            if (dumpState.onTitlePrinted())
16069                                pw.println();
16070                            pw.println("Libraries:");
16071                            printedHeader = true;
16072                        }
16073                        pw.print("  ");
16074                    } else {
16075                        pw.print("lib,");
16076                    }
16077                    pw.print(name);
16078                    if (!checkin) {
16079                        pw.print(" -> ");
16080                    }
16081                    if (ent.path != null) {
16082                        if (!checkin) {
16083                            pw.print("(jar) ");
16084                            pw.print(ent.path);
16085                        } else {
16086                            pw.print(",jar,");
16087                            pw.print(ent.path);
16088                        }
16089                    } else {
16090                        if (!checkin) {
16091                            pw.print("(apk) ");
16092                            pw.print(ent.apk);
16093                        } else {
16094                            pw.print(",apk,");
16095                            pw.print(ent.apk);
16096                        }
16097                    }
16098                    pw.println();
16099                }
16100            }
16101
16102            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16103                if (dumpState.onTitlePrinted())
16104                    pw.println();
16105                if (!checkin) {
16106                    pw.println("Features:");
16107                }
16108                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16109                while (it.hasNext()) {
16110                    String name = it.next();
16111                    if (!checkin) {
16112                        pw.print("  ");
16113                    } else {
16114                        pw.print("feat,");
16115                    }
16116                    pw.println(name);
16117                }
16118            }
16119
16120            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16121                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16122                        : "Activity Resolver Table:", "  ", packageName,
16123                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16124                    dumpState.setTitlePrinted(true);
16125                }
16126            }
16127            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16128                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16129                        : "Receiver Resolver Table:", "  ", packageName,
16130                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16131                    dumpState.setTitlePrinted(true);
16132                }
16133            }
16134            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16135                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16136                        : "Service Resolver Table:", "  ", packageName,
16137                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16138                    dumpState.setTitlePrinted(true);
16139                }
16140            }
16141            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16142                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16143                        : "Provider Resolver Table:", "  ", packageName,
16144                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16145                    dumpState.setTitlePrinted(true);
16146                }
16147            }
16148
16149            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16150                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16151                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16152                    int user = mSettings.mPreferredActivities.keyAt(i);
16153                    if (pir.dump(pw,
16154                            dumpState.getTitlePrinted()
16155                                ? "\nPreferred Activities User " + user + ":"
16156                                : "Preferred Activities User " + user + ":", "  ",
16157                            packageName, true, false)) {
16158                        dumpState.setTitlePrinted(true);
16159                    }
16160                }
16161            }
16162
16163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16164                pw.flush();
16165                FileOutputStream fout = new FileOutputStream(fd);
16166                BufferedOutputStream str = new BufferedOutputStream(fout);
16167                XmlSerializer serializer = new FastXmlSerializer();
16168                try {
16169                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16170                    serializer.startDocument(null, true);
16171                    serializer.setFeature(
16172                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16173                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16174                    serializer.endDocument();
16175                    serializer.flush();
16176                } catch (IllegalArgumentException e) {
16177                    pw.println("Failed writing: " + e);
16178                } catch (IllegalStateException e) {
16179                    pw.println("Failed writing: " + e);
16180                } catch (IOException e) {
16181                    pw.println("Failed writing: " + e);
16182                }
16183            }
16184
16185            if (!checkin
16186                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16187                    && packageName == null) {
16188                pw.println();
16189                int count = mSettings.mPackages.size();
16190                if (count == 0) {
16191                    pw.println("No applications!");
16192                    pw.println();
16193                } else {
16194                    final String prefix = "  ";
16195                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16196                    if (allPackageSettings.size() == 0) {
16197                        pw.println("No domain preferred apps!");
16198                        pw.println();
16199                    } else {
16200                        pw.println("App verification status:");
16201                        pw.println();
16202                        count = 0;
16203                        for (PackageSetting ps : allPackageSettings) {
16204                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16205                            if (ivi == null || ivi.getPackageName() == null) continue;
16206                            pw.println(prefix + "Package: " + ivi.getPackageName());
16207                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16208                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16209                            pw.println();
16210                            count++;
16211                        }
16212                        if (count == 0) {
16213                            pw.println(prefix + "No app verification established.");
16214                            pw.println();
16215                        }
16216                        for (int userId : sUserManager.getUserIds()) {
16217                            pw.println("App linkages for user " + userId + ":");
16218                            pw.println();
16219                            count = 0;
16220                            for (PackageSetting ps : allPackageSettings) {
16221                                final long status = ps.getDomainVerificationStatusForUser(userId);
16222                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16223                                    continue;
16224                                }
16225                                pw.println(prefix + "Package: " + ps.name);
16226                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16227                                String statusStr = IntentFilterVerificationInfo.
16228                                        getStatusStringFromValue(status);
16229                                pw.println(prefix + "Status:  " + statusStr);
16230                                pw.println();
16231                                count++;
16232                            }
16233                            if (count == 0) {
16234                                pw.println(prefix + "No configured app linkages.");
16235                                pw.println();
16236                            }
16237                        }
16238                    }
16239                }
16240            }
16241
16242            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16243                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16244                if (packageName == null && permissionNames == null) {
16245                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16246                        if (iperm == 0) {
16247                            if (dumpState.onTitlePrinted())
16248                                pw.println();
16249                            pw.println("AppOp Permissions:");
16250                        }
16251                        pw.print("  AppOp Permission ");
16252                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16253                        pw.println(":");
16254                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16255                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16256                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16257                        }
16258                    }
16259                }
16260            }
16261
16262            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16263                boolean printedSomething = false;
16264                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16265                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16266                        continue;
16267                    }
16268                    if (!printedSomething) {
16269                        if (dumpState.onTitlePrinted())
16270                            pw.println();
16271                        pw.println("Registered ContentProviders:");
16272                        printedSomething = true;
16273                    }
16274                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16275                    pw.print("    "); pw.println(p.toString());
16276                }
16277                printedSomething = false;
16278                for (Map.Entry<String, PackageParser.Provider> entry :
16279                        mProvidersByAuthority.entrySet()) {
16280                    PackageParser.Provider p = entry.getValue();
16281                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16282                        continue;
16283                    }
16284                    if (!printedSomething) {
16285                        if (dumpState.onTitlePrinted())
16286                            pw.println();
16287                        pw.println("ContentProvider Authorities:");
16288                        printedSomething = true;
16289                    }
16290                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16291                    pw.print("    "); pw.println(p.toString());
16292                    if (p.info != null && p.info.applicationInfo != null) {
16293                        final String appInfo = p.info.applicationInfo.toString();
16294                        pw.print("      applicationInfo="); pw.println(appInfo);
16295                    }
16296                }
16297            }
16298
16299            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16300                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16301            }
16302
16303            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16304                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16305            }
16306
16307            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16308                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16309            }
16310
16311            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16312                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16313            }
16314
16315            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16316                // XXX should handle packageName != null by dumping only install data that
16317                // the given package is involved with.
16318                if (dumpState.onTitlePrinted()) pw.println();
16319                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16320            }
16321
16322            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16323                if (dumpState.onTitlePrinted()) pw.println();
16324                mSettings.dumpReadMessagesLPr(pw, dumpState);
16325
16326                pw.println();
16327                pw.println("Package warning messages:");
16328                BufferedReader in = null;
16329                String line = null;
16330                try {
16331                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16332                    while ((line = in.readLine()) != null) {
16333                        if (line.contains("ignored: updated version")) continue;
16334                        pw.println(line);
16335                    }
16336                } catch (IOException ignored) {
16337                } finally {
16338                    IoUtils.closeQuietly(in);
16339                }
16340            }
16341
16342            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16343                BufferedReader in = null;
16344                String line = null;
16345                try {
16346                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16347                    while ((line = in.readLine()) != null) {
16348                        if (line.contains("ignored: updated version")) continue;
16349                        pw.print("msg,");
16350                        pw.println(line);
16351                    }
16352                } catch (IOException ignored) {
16353                } finally {
16354                    IoUtils.closeQuietly(in);
16355                }
16356            }
16357        }
16358    }
16359
16360    private String dumpDomainString(String packageName) {
16361        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16362        List<IntentFilter> filters = getAllIntentFilters(packageName);
16363
16364        ArraySet<String> result = new ArraySet<>();
16365        if (iviList.size() > 0) {
16366            for (IntentFilterVerificationInfo ivi : iviList) {
16367                for (String host : ivi.getDomains()) {
16368                    result.add(host);
16369                }
16370            }
16371        }
16372        if (filters != null && filters.size() > 0) {
16373            for (IntentFilter filter : filters) {
16374                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16375                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16376                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16377                    result.addAll(filter.getHostsList());
16378                }
16379            }
16380        }
16381
16382        StringBuilder sb = new StringBuilder(result.size() * 16);
16383        for (String domain : result) {
16384            if (sb.length() > 0) sb.append(" ");
16385            sb.append(domain);
16386        }
16387        return sb.toString();
16388    }
16389
16390    // ------- apps on sdcard specific code -------
16391    static final boolean DEBUG_SD_INSTALL = false;
16392
16393    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16394
16395    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16396
16397    private boolean mMediaMounted = false;
16398
16399    static String getEncryptKey() {
16400        try {
16401            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16402                    SD_ENCRYPTION_KEYSTORE_NAME);
16403            if (sdEncKey == null) {
16404                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16405                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16406                if (sdEncKey == null) {
16407                    Slog.e(TAG, "Failed to create encryption keys");
16408                    return null;
16409                }
16410            }
16411            return sdEncKey;
16412        } catch (NoSuchAlgorithmException nsae) {
16413            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16414            return null;
16415        } catch (IOException ioe) {
16416            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16417            return null;
16418        }
16419    }
16420
16421    /*
16422     * Update media status on PackageManager.
16423     */
16424    @Override
16425    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16426        int callingUid = Binder.getCallingUid();
16427        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16428            throw new SecurityException("Media status can only be updated by the system");
16429        }
16430        // reader; this apparently protects mMediaMounted, but should probably
16431        // be a different lock in that case.
16432        synchronized (mPackages) {
16433            Log.i(TAG, "Updating external media status from "
16434                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16435                    + (mediaStatus ? "mounted" : "unmounted"));
16436            if (DEBUG_SD_INSTALL)
16437                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16438                        + ", mMediaMounted=" + mMediaMounted);
16439            if (mediaStatus == mMediaMounted) {
16440                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16441                        : 0, -1);
16442                mHandler.sendMessage(msg);
16443                return;
16444            }
16445            mMediaMounted = mediaStatus;
16446        }
16447        // Queue up an async operation since the package installation may take a
16448        // little while.
16449        mHandler.post(new Runnable() {
16450            public void run() {
16451                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16452            }
16453        });
16454    }
16455
16456    /**
16457     * Called by MountService when the initial ASECs to scan are available.
16458     * Should block until all the ASEC containers are finished being scanned.
16459     */
16460    public void scanAvailableAsecs() {
16461        updateExternalMediaStatusInner(true, false, false);
16462    }
16463
16464    /*
16465     * Collect information of applications on external media, map them against
16466     * existing containers and update information based on current mount status.
16467     * Please note that we always have to report status if reportStatus has been
16468     * set to true especially when unloading packages.
16469     */
16470    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16471            boolean externalStorage) {
16472        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16473        int[] uidArr = EmptyArray.INT;
16474
16475        final String[] list = PackageHelper.getSecureContainerList();
16476        if (ArrayUtils.isEmpty(list)) {
16477            Log.i(TAG, "No secure containers found");
16478        } else {
16479            // Process list of secure containers and categorize them
16480            // as active or stale based on their package internal state.
16481
16482            // reader
16483            synchronized (mPackages) {
16484                for (String cid : list) {
16485                    // Leave stages untouched for now; installer service owns them
16486                    if (PackageInstallerService.isStageName(cid)) continue;
16487
16488                    if (DEBUG_SD_INSTALL)
16489                        Log.i(TAG, "Processing container " + cid);
16490                    String pkgName = getAsecPackageName(cid);
16491                    if (pkgName == null) {
16492                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16493                        continue;
16494                    }
16495                    if (DEBUG_SD_INSTALL)
16496                        Log.i(TAG, "Looking for pkg : " + pkgName);
16497
16498                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16499                    if (ps == null) {
16500                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16501                        continue;
16502                    }
16503
16504                    /*
16505                     * Skip packages that are not external if we're unmounting
16506                     * external storage.
16507                     */
16508                    if (externalStorage && !isMounted && !isExternal(ps)) {
16509                        continue;
16510                    }
16511
16512                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16513                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16514                    // The package status is changed only if the code path
16515                    // matches between settings and the container id.
16516                    if (ps.codePathString != null
16517                            && ps.codePathString.startsWith(args.getCodePath())) {
16518                        if (DEBUG_SD_INSTALL) {
16519                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16520                                    + " at code path: " + ps.codePathString);
16521                        }
16522
16523                        // We do have a valid package installed on sdcard
16524                        processCids.put(args, ps.codePathString);
16525                        final int uid = ps.appId;
16526                        if (uid != -1) {
16527                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16528                        }
16529                    } else {
16530                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16531                                + ps.codePathString);
16532                    }
16533                }
16534            }
16535
16536            Arrays.sort(uidArr);
16537        }
16538
16539        // Process packages with valid entries.
16540        if (isMounted) {
16541            if (DEBUG_SD_INSTALL)
16542                Log.i(TAG, "Loading packages");
16543            loadMediaPackages(processCids, uidArr, externalStorage);
16544            startCleaningPackages();
16545            mInstallerService.onSecureContainersAvailable();
16546        } else {
16547            if (DEBUG_SD_INSTALL)
16548                Log.i(TAG, "Unloading packages");
16549            unloadMediaPackages(processCids, uidArr, reportStatus);
16550        }
16551    }
16552
16553    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16554            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16555        final int size = infos.size();
16556        final String[] packageNames = new String[size];
16557        final int[] packageUids = new int[size];
16558        for (int i = 0; i < size; i++) {
16559            final ApplicationInfo info = infos.get(i);
16560            packageNames[i] = info.packageName;
16561            packageUids[i] = info.uid;
16562        }
16563        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16564                finishedReceiver);
16565    }
16566
16567    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16568            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16569        sendResourcesChangedBroadcast(mediaStatus, replacing,
16570                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16571    }
16572
16573    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16574            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16575        int size = pkgList.length;
16576        if (size > 0) {
16577            // Send broadcasts here
16578            Bundle extras = new Bundle();
16579            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16580            if (uidArr != null) {
16581                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16582            }
16583            if (replacing) {
16584                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16585            }
16586            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16587                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16588            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16589        }
16590    }
16591
16592   /*
16593     * Look at potentially valid container ids from processCids If package
16594     * information doesn't match the one on record or package scanning fails,
16595     * the cid is added to list of removeCids. We currently don't delete stale
16596     * containers.
16597     */
16598    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16599            boolean externalStorage) {
16600        ArrayList<String> pkgList = new ArrayList<String>();
16601        Set<AsecInstallArgs> keys = processCids.keySet();
16602
16603        for (AsecInstallArgs args : keys) {
16604            String codePath = processCids.get(args);
16605            if (DEBUG_SD_INSTALL)
16606                Log.i(TAG, "Loading container : " + args.cid);
16607            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16608            try {
16609                // Make sure there are no container errors first.
16610                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16611                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16612                            + " when installing from sdcard");
16613                    continue;
16614                }
16615                // Check code path here.
16616                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16617                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16618                            + " does not match one in settings " + codePath);
16619                    continue;
16620                }
16621                // Parse package
16622                int parseFlags = mDefParseFlags;
16623                if (args.isExternalAsec()) {
16624                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16625                }
16626                if (args.isFwdLocked()) {
16627                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16628                }
16629
16630                synchronized (mInstallLock) {
16631                    PackageParser.Package pkg = null;
16632                    try {
16633                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16634                    } catch (PackageManagerException e) {
16635                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16636                    }
16637                    // Scan the package
16638                    if (pkg != null) {
16639                        /*
16640                         * TODO why is the lock being held? doPostInstall is
16641                         * called in other places without the lock. This needs
16642                         * to be straightened out.
16643                         */
16644                        // writer
16645                        synchronized (mPackages) {
16646                            retCode = PackageManager.INSTALL_SUCCEEDED;
16647                            pkgList.add(pkg.packageName);
16648                            // Post process args
16649                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16650                                    pkg.applicationInfo.uid);
16651                        }
16652                    } else {
16653                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16654                    }
16655                }
16656
16657            } finally {
16658                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16659                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16660                }
16661            }
16662        }
16663        // writer
16664        synchronized (mPackages) {
16665            // If the platform SDK has changed since the last time we booted,
16666            // we need to re-grant app permission to catch any new ones that
16667            // appear. This is really a hack, and means that apps can in some
16668            // cases get permissions that the user didn't initially explicitly
16669            // allow... it would be nice to have some better way to handle
16670            // this situation.
16671            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16672                    : mSettings.getInternalVersion();
16673            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16674                    : StorageManager.UUID_PRIVATE_INTERNAL;
16675
16676            int updateFlags = UPDATE_PERMISSIONS_ALL;
16677            if (ver.sdkVersion != mSdkVersion) {
16678                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16679                        + mSdkVersion + "; regranting permissions for external");
16680                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16681            }
16682            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16683
16684            // Yay, everything is now upgraded
16685            ver.forceCurrent();
16686
16687            // can downgrade to reader
16688            // Persist settings
16689            mSettings.writeLPr();
16690        }
16691        // Send a broadcast to let everyone know we are done processing
16692        if (pkgList.size() > 0) {
16693            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16694        }
16695    }
16696
16697   /*
16698     * Utility method to unload a list of specified containers
16699     */
16700    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16701        // Just unmount all valid containers.
16702        for (AsecInstallArgs arg : cidArgs) {
16703            synchronized (mInstallLock) {
16704                arg.doPostDeleteLI(false);
16705           }
16706       }
16707   }
16708
16709    /*
16710     * Unload packages mounted on external media. This involves deleting package
16711     * data from internal structures, sending broadcasts about diabled packages,
16712     * gc'ing to free up references, unmounting all secure containers
16713     * corresponding to packages on external media, and posting a
16714     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16715     * that we always have to post this message if status has been requested no
16716     * matter what.
16717     */
16718    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16719            final boolean reportStatus) {
16720        if (DEBUG_SD_INSTALL)
16721            Log.i(TAG, "unloading media packages");
16722        ArrayList<String> pkgList = new ArrayList<String>();
16723        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16724        final Set<AsecInstallArgs> keys = processCids.keySet();
16725        for (AsecInstallArgs args : keys) {
16726            String pkgName = args.getPackageName();
16727            if (DEBUG_SD_INSTALL)
16728                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16729            // Delete package internally
16730            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16731            synchronized (mInstallLock) {
16732                boolean res = deletePackageLI(pkgName, null, false, null, null,
16733                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16734                if (res) {
16735                    pkgList.add(pkgName);
16736                } else {
16737                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16738                    failedList.add(args);
16739                }
16740            }
16741        }
16742
16743        // reader
16744        synchronized (mPackages) {
16745            // We didn't update the settings after removing each package;
16746            // write them now for all packages.
16747            mSettings.writeLPr();
16748        }
16749
16750        // We have to absolutely send UPDATED_MEDIA_STATUS only
16751        // after confirming that all the receivers processed the ordered
16752        // broadcast when packages get disabled, force a gc to clean things up.
16753        // and unload all the containers.
16754        if (pkgList.size() > 0) {
16755            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16756                    new IIntentReceiver.Stub() {
16757                public void performReceive(Intent intent, int resultCode, String data,
16758                        Bundle extras, boolean ordered, boolean sticky,
16759                        int sendingUser) throws RemoteException {
16760                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16761                            reportStatus ? 1 : 0, 1, keys);
16762                    mHandler.sendMessage(msg);
16763                }
16764            });
16765        } else {
16766            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16767                    keys);
16768            mHandler.sendMessage(msg);
16769        }
16770    }
16771
16772    private void loadPrivatePackages(final VolumeInfo vol) {
16773        mHandler.post(new Runnable() {
16774            @Override
16775            public void run() {
16776                loadPrivatePackagesInner(vol);
16777            }
16778        });
16779    }
16780
16781    private void loadPrivatePackagesInner(VolumeInfo vol) {
16782        final String volumeUuid = vol.fsUuid;
16783        if (TextUtils.isEmpty(volumeUuid)) {
16784            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16785            return;
16786        }
16787
16788        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16789        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16790
16791        final VersionInfo ver;
16792        final List<PackageSetting> packages;
16793        synchronized (mPackages) {
16794            ver = mSettings.findOrCreateVersion(volumeUuid);
16795            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16796        }
16797
16798        // TODO: introduce a new concept similar to "frozen" to prevent these
16799        // apps from being launched until after data has been fully reconciled
16800        for (PackageSetting ps : packages) {
16801            synchronized (mInstallLock) {
16802                final PackageParser.Package pkg;
16803                try {
16804                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16805                    loaded.add(pkg.applicationInfo);
16806
16807                } catch (PackageManagerException e) {
16808                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16809                }
16810
16811                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16812                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16813                }
16814            }
16815        }
16816
16817        // Reconcile app data for all started/unlocked users
16818        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16819        final UserManager um = mContext.getSystemService(UserManager.class);
16820        for (UserInfo user : um.getUsers()) {
16821            final int flags;
16822            if (um.isUserUnlocked(user.id)) {
16823                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16824            } else if (um.isUserRunning(user.id)) {
16825                flags = StorageManager.FLAG_STORAGE_DE;
16826            } else {
16827                continue;
16828            }
16829
16830            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
16831            reconcileAppsData(volumeUuid, user.id, flags);
16832        }
16833
16834        synchronized (mPackages) {
16835            int updateFlags = UPDATE_PERMISSIONS_ALL;
16836            if (ver.sdkVersion != mSdkVersion) {
16837                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16838                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16839                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16840            }
16841            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16842
16843            // Yay, everything is now upgraded
16844            ver.forceCurrent();
16845
16846            mSettings.writeLPr();
16847        }
16848
16849        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16850        sendResourcesChangedBroadcast(true, false, loaded, null);
16851    }
16852
16853    private void unloadPrivatePackages(final VolumeInfo vol) {
16854        mHandler.post(new Runnable() {
16855            @Override
16856            public void run() {
16857                unloadPrivatePackagesInner(vol);
16858            }
16859        });
16860    }
16861
16862    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16863        final String volumeUuid = vol.fsUuid;
16864        if (TextUtils.isEmpty(volumeUuid)) {
16865            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16866            return;
16867        }
16868
16869        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16870        synchronized (mInstallLock) {
16871        synchronized (mPackages) {
16872            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16873            for (PackageSetting ps : packages) {
16874                if (ps.pkg == null) continue;
16875
16876                final ApplicationInfo info = ps.pkg.applicationInfo;
16877                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16878                if (deletePackageLI(ps.name, null, false, null, null,
16879                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16880                    unloaded.add(info);
16881                } else {
16882                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16883                }
16884            }
16885
16886            mSettings.writeLPr();
16887        }
16888        }
16889
16890        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16891        sendResourcesChangedBroadcast(false, false, unloaded, null);
16892    }
16893
16894    /**
16895     * Examine all users present on given mounted volume, and destroy data
16896     * belonging to users that are no longer valid, or whose user ID has been
16897     * recycled.
16898     */
16899    private void reconcileUsers(String volumeUuid) {
16900        final File[] files = FileUtils
16901                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16902        for (File file : files) {
16903            if (!file.isDirectory()) continue;
16904
16905            final int userId;
16906            final UserInfo info;
16907            try {
16908                userId = Integer.parseInt(file.getName());
16909                info = sUserManager.getUserInfo(userId);
16910            } catch (NumberFormatException e) {
16911                Slog.w(TAG, "Invalid user directory " + file);
16912                continue;
16913            }
16914
16915            boolean destroyUser = false;
16916            if (info == null) {
16917                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16918                        + " because no matching user was found");
16919                destroyUser = true;
16920            } else {
16921                try {
16922                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16923                } catch (IOException e) {
16924                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16925                            + " because we failed to enforce serial number: " + e);
16926                    destroyUser = true;
16927                }
16928            }
16929
16930            if (destroyUser) {
16931                synchronized (mInstallLock) {
16932                    try {
16933                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16934                    } catch (InstallerException e) {
16935                        Slog.w(TAG, "Failed to clean up user dirs", e);
16936                    }
16937                }
16938            }
16939        }
16940    }
16941
16942    private void assertPackageKnown(String volumeUuid, String packageName)
16943            throws PackageManagerException {
16944        synchronized (mPackages) {
16945            final PackageSetting ps = mSettings.mPackages.get(packageName);
16946            if (ps == null) {
16947                throw new PackageManagerException("Package " + packageName + " is unknown");
16948            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16949                throw new PackageManagerException(
16950                        "Package " + packageName + " found on unknown volume " + volumeUuid
16951                                + "; expected volume " + ps.volumeUuid);
16952            }
16953        }
16954    }
16955
16956    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16957            throws PackageManagerException {
16958        synchronized (mPackages) {
16959            final PackageSetting ps = mSettings.mPackages.get(packageName);
16960            if (ps == null) {
16961                throw new PackageManagerException("Package " + packageName + " is unknown");
16962            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16963                throw new PackageManagerException(
16964                        "Package " + packageName + " found on unknown volume " + volumeUuid
16965                                + "; expected volume " + ps.volumeUuid);
16966            } else if (!ps.getInstalled(userId)) {
16967                throw new PackageManagerException(
16968                        "Package " + packageName + " not installed for user " + userId);
16969            }
16970        }
16971    }
16972
16973    /**
16974     * Examine all apps present on given mounted volume, and destroy apps that
16975     * aren't expected, either due to uninstallation or reinstallation on
16976     * another volume.
16977     */
16978    private void reconcileApps(String volumeUuid) {
16979        final File[] files = FileUtils
16980                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16981        for (File file : files) {
16982            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16983                    && !PackageInstallerService.isStageName(file.getName());
16984            if (!isPackage) {
16985                // Ignore entries which are not packages
16986                continue;
16987            }
16988
16989            try {
16990                final PackageLite pkg = PackageParser.parsePackageLite(file,
16991                        PackageParser.PARSE_MUST_BE_APK);
16992                assertPackageKnown(volumeUuid, pkg.packageName);
16993
16994            } catch (PackageParserException | PackageManagerException e) {
16995                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16996                synchronized (mInstallLock) {
16997                    removeCodePathLI(file);
16998                }
16999            }
17000        }
17001    }
17002
17003    /**
17004     * Reconcile all app data for the given user.
17005     * <p>
17006     * Verifies that directories exist and that ownership and labeling is
17007     * correct for all installed apps on all mounted volumes.
17008     */
17009    void reconcileAppsData(int userId, int flags) {
17010        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17011        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17012            final String volumeUuid = vol.getFsUuid();
17013            reconcileAppsData(volumeUuid, userId, flags);
17014        }
17015    }
17016
17017    /**
17018     * Reconcile all app data on given mounted volume.
17019     * <p>
17020     * Destroys app data that isn't expected, either due to uninstallation or
17021     * reinstallation on another volume.
17022     * <p>
17023     * Verifies that directories exist and that ownership and labeling is
17024     * correct for all installed apps.
17025     */
17026    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17027        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17028                + Integer.toHexString(flags));
17029
17030        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17031        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17032
17033        boolean restoreconNeeded = false;
17034
17035        // First look for stale data that doesn't belong, and check if things
17036        // have changed since we did our last restorecon
17037        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17038            if (!isUserKeyUnlocked(userId)) {
17039                throw new RuntimeException(
17040                        "Yikes, someone asked us to reconcile CE storage while " + userId
17041                                + " was still locked; this would have caused massive data loss!");
17042            }
17043
17044            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17045
17046            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17047            for (File file : files) {
17048                final String packageName = file.getName();
17049                try {
17050                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17051                } catch (PackageManagerException e) {
17052                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17053                    synchronized (mInstallLock) {
17054                        destroyAppDataLI(volumeUuid, packageName, userId,
17055                                StorageManager.FLAG_STORAGE_CE);
17056                    }
17057                }
17058            }
17059        }
17060        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17061            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17062
17063            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17064            for (File file : files) {
17065                final String packageName = file.getName();
17066                try {
17067                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17068                } catch (PackageManagerException e) {
17069                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17070                    synchronized (mInstallLock) {
17071                        destroyAppDataLI(volumeUuid, packageName, userId,
17072                                StorageManager.FLAG_STORAGE_DE);
17073                    }
17074                }
17075            }
17076        }
17077
17078        // Ensure that data directories are ready to roll for all packages
17079        // installed for this volume and user
17080        final List<PackageSetting> packages;
17081        synchronized (mPackages) {
17082            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17083        }
17084        int preparedCount = 0;
17085        for (PackageSetting ps : packages) {
17086            final String packageName = ps.name;
17087            if (ps.pkg == null) {
17088                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17089                // TODO: might be due to legacy ASEC apps; we should circle back
17090                // and reconcile again once they're scanned
17091                continue;
17092            }
17093
17094            if (ps.getInstalled(userId)) {
17095                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17096                preparedCount++;
17097            }
17098        }
17099
17100        if (restoreconNeeded) {
17101            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17102                SELinuxMMAC.setRestoreconDone(ceDir);
17103            }
17104            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17105                SELinuxMMAC.setRestoreconDone(deDir);
17106            }
17107        }
17108
17109        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17110                + " packages; restoreconNeeded was " + restoreconNeeded);
17111    }
17112
17113    /**
17114     * Prepare app data for the given app just after it was installed or
17115     * upgraded. This method carefully only touches users that it's installed
17116     * for, and it forces a restorecon to handle any seinfo changes.
17117     * <p>
17118     * Verifies that directories exist and that ownership and labeling is
17119     * correct for all installed apps. If there is an ownership mismatch, it
17120     * will try recovering system apps by wiping data; third-party app data is
17121     * left intact.
17122     */
17123    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17124        final PackageSetting ps;
17125        synchronized (mPackages) {
17126            ps = mSettings.mPackages.get(pkg.packageName);
17127        }
17128
17129        final UserManager um = mContext.getSystemService(UserManager.class);
17130        for (UserInfo user : um.getUsers()) {
17131            final int flags;
17132            if (um.isUserUnlocked(user.id)) {
17133                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17134            } else if (um.isUserRunning(user.id)) {
17135                flags = StorageManager.FLAG_STORAGE_DE;
17136            } else {
17137                continue;
17138            }
17139
17140            if (ps.getInstalled(user.id)) {
17141                // Whenever an app changes, force a restorecon of its data
17142                // TODO: when user data is locked, mark that we're still dirty
17143                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17144            }
17145        }
17146    }
17147
17148    /**
17149     * Prepare app data for the given app.
17150     * <p>
17151     * Verifies that directories exist and that ownership and labeling is
17152     * correct for all installed apps. If there is an ownership mismatch, this
17153     * will try recovering system apps by wiping data; third-party app data is
17154     * left intact.
17155     */
17156    private void prepareAppData(String volumeUuid, int userId, int flags,
17157            PackageParser.Package pkg, boolean restoreconNeeded) {
17158        if (DEBUG_APP_DATA) {
17159            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17160                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17161        }
17162
17163        final String packageName = pkg.packageName;
17164        final ApplicationInfo app = pkg.applicationInfo;
17165        final int appId = UserHandle.getAppId(app.uid);
17166
17167        Preconditions.checkNotNull(app.seinfo);
17168
17169        synchronized (mInstallLock) {
17170            try {
17171                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17172                        appId, app.seinfo, app.targetSdkVersion);
17173            } catch (InstallerException e) {
17174                if (app.isSystemApp()) {
17175                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17176                            + ", but trying to recover: " + e);
17177                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17178                    try {
17179                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17180                                appId, app.seinfo, app.targetSdkVersion);
17181                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17182                    } catch (InstallerException e2) {
17183                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17184                    }
17185                } else {
17186                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17187                }
17188            }
17189
17190            if (restoreconNeeded) {
17191                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17192            }
17193
17194            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17195                // Create a native library symlink only if we have native libraries
17196                // and if the native libraries are 32 bit libraries. We do not provide
17197                // this symlink for 64 bit libraries.
17198                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17199                    final String nativeLibPath = app.nativeLibraryDir;
17200                    try {
17201                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17202                                nativeLibPath, userId);
17203                    } catch (InstallerException e) {
17204                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17205                    }
17206                }
17207            }
17208        }
17209    }
17210
17211    private void unfreezePackage(String packageName) {
17212        synchronized (mPackages) {
17213            final PackageSetting ps = mSettings.mPackages.get(packageName);
17214            if (ps != null) {
17215                ps.frozen = false;
17216            }
17217        }
17218    }
17219
17220    @Override
17221    public int movePackage(final String packageName, final String volumeUuid) {
17222        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17223
17224        final int moveId = mNextMoveId.getAndIncrement();
17225        mHandler.post(new Runnable() {
17226            @Override
17227            public void run() {
17228                try {
17229                    movePackageInternal(packageName, volumeUuid, moveId);
17230                } catch (PackageManagerException e) {
17231                    Slog.w(TAG, "Failed to move " + packageName, e);
17232                    mMoveCallbacks.notifyStatusChanged(moveId,
17233                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17234                }
17235            }
17236        });
17237        return moveId;
17238    }
17239
17240    private void movePackageInternal(final String packageName, final String volumeUuid,
17241            final int moveId) throws PackageManagerException {
17242        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17243        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17244        final PackageManager pm = mContext.getPackageManager();
17245
17246        final boolean currentAsec;
17247        final String currentVolumeUuid;
17248        final File codeFile;
17249        final String installerPackageName;
17250        final String packageAbiOverride;
17251        final int appId;
17252        final String seinfo;
17253        final String label;
17254        final int targetSdkVersion;
17255
17256        // reader
17257        synchronized (mPackages) {
17258            final PackageParser.Package pkg = mPackages.get(packageName);
17259            final PackageSetting ps = mSettings.mPackages.get(packageName);
17260            if (pkg == null || ps == null) {
17261                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17262            }
17263
17264            if (pkg.applicationInfo.isSystemApp()) {
17265                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17266                        "Cannot move system application");
17267            }
17268
17269            if (pkg.applicationInfo.isExternalAsec()) {
17270                currentAsec = true;
17271                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17272            } else if (pkg.applicationInfo.isForwardLocked()) {
17273                currentAsec = true;
17274                currentVolumeUuid = "forward_locked";
17275            } else {
17276                currentAsec = false;
17277                currentVolumeUuid = ps.volumeUuid;
17278
17279                final File probe = new File(pkg.codePath);
17280                final File probeOat = new File(probe, "oat");
17281                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17282                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17283                            "Move only supported for modern cluster style installs");
17284                }
17285            }
17286
17287            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17288                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17289                        "Package already moved to " + volumeUuid);
17290            }
17291
17292            if (ps.frozen) {
17293                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17294                        "Failed to move already frozen package");
17295            }
17296            ps.frozen = true;
17297
17298            codeFile = new File(pkg.codePath);
17299            installerPackageName = ps.installerPackageName;
17300            packageAbiOverride = ps.cpuAbiOverrideString;
17301            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17302            seinfo = pkg.applicationInfo.seinfo;
17303            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17304            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17305        }
17306
17307        // Now that we're guarded by frozen state, kill app during move
17308        final long token = Binder.clearCallingIdentity();
17309        try {
17310            killApplication(packageName, appId, "move pkg");
17311        } finally {
17312            Binder.restoreCallingIdentity(token);
17313        }
17314
17315        final Bundle extras = new Bundle();
17316        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17317        extras.putString(Intent.EXTRA_TITLE, label);
17318        mMoveCallbacks.notifyCreated(moveId, extras);
17319
17320        int installFlags;
17321        final boolean moveCompleteApp;
17322        final File measurePath;
17323
17324        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17325            installFlags = INSTALL_INTERNAL;
17326            moveCompleteApp = !currentAsec;
17327            measurePath = Environment.getDataAppDirectory(volumeUuid);
17328        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17329            installFlags = INSTALL_EXTERNAL;
17330            moveCompleteApp = false;
17331            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17332        } else {
17333            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17334            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17335                    || !volume.isMountedWritable()) {
17336                unfreezePackage(packageName);
17337                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17338                        "Move location not mounted private volume");
17339            }
17340
17341            Preconditions.checkState(!currentAsec);
17342
17343            installFlags = INSTALL_INTERNAL;
17344            moveCompleteApp = true;
17345            measurePath = Environment.getDataAppDirectory(volumeUuid);
17346        }
17347
17348        final PackageStats stats = new PackageStats(null, -1);
17349        synchronized (mInstaller) {
17350            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17351                unfreezePackage(packageName);
17352                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17353                        "Failed to measure package size");
17354            }
17355        }
17356
17357        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17358                + stats.dataSize);
17359
17360        final long startFreeBytes = measurePath.getFreeSpace();
17361        final long sizeBytes;
17362        if (moveCompleteApp) {
17363            sizeBytes = stats.codeSize + stats.dataSize;
17364        } else {
17365            sizeBytes = stats.codeSize;
17366        }
17367
17368        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17369            unfreezePackage(packageName);
17370            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17371                    "Not enough free space to move");
17372        }
17373
17374        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17375
17376        final CountDownLatch installedLatch = new CountDownLatch(1);
17377        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17378            @Override
17379            public void onUserActionRequired(Intent intent) throws RemoteException {
17380                throw new IllegalStateException();
17381            }
17382
17383            @Override
17384            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17385                    Bundle extras) throws RemoteException {
17386                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17387                        + PackageManager.installStatusToString(returnCode, msg));
17388
17389                installedLatch.countDown();
17390
17391                // Regardless of success or failure of the move operation,
17392                // always unfreeze the package
17393                unfreezePackage(packageName);
17394
17395                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17396                switch (status) {
17397                    case PackageInstaller.STATUS_SUCCESS:
17398                        mMoveCallbacks.notifyStatusChanged(moveId,
17399                                PackageManager.MOVE_SUCCEEDED);
17400                        break;
17401                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17402                        mMoveCallbacks.notifyStatusChanged(moveId,
17403                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17404                        break;
17405                    default:
17406                        mMoveCallbacks.notifyStatusChanged(moveId,
17407                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17408                        break;
17409                }
17410            }
17411        };
17412
17413        final MoveInfo move;
17414        if (moveCompleteApp) {
17415            // Kick off a thread to report progress estimates
17416            new Thread() {
17417                @Override
17418                public void run() {
17419                    while (true) {
17420                        try {
17421                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17422                                break;
17423                            }
17424                        } catch (InterruptedException ignored) {
17425                        }
17426
17427                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17428                        final int progress = 10 + (int) MathUtils.constrain(
17429                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17430                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17431                    }
17432                }
17433            }.start();
17434
17435            final String dataAppName = codeFile.getName();
17436            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17437                    dataAppName, appId, seinfo, targetSdkVersion);
17438        } else {
17439            move = null;
17440        }
17441
17442        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17443
17444        final Message msg = mHandler.obtainMessage(INIT_COPY);
17445        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17446        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17447                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17448        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17449        msg.obj = params;
17450
17451        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17452                System.identityHashCode(msg.obj));
17453        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17454                System.identityHashCode(msg.obj));
17455
17456        mHandler.sendMessage(msg);
17457    }
17458
17459    @Override
17460    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17461        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17462
17463        final int realMoveId = mNextMoveId.getAndIncrement();
17464        final Bundle extras = new Bundle();
17465        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17466        mMoveCallbacks.notifyCreated(realMoveId, extras);
17467
17468        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17469            @Override
17470            public void onCreated(int moveId, Bundle extras) {
17471                // Ignored
17472            }
17473
17474            @Override
17475            public void onStatusChanged(int moveId, int status, long estMillis) {
17476                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17477            }
17478        };
17479
17480        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17481        storage.setPrimaryStorageUuid(volumeUuid, callback);
17482        return realMoveId;
17483    }
17484
17485    @Override
17486    public int getMoveStatus(int moveId) {
17487        mContext.enforceCallingOrSelfPermission(
17488                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17489        return mMoveCallbacks.mLastStatus.get(moveId);
17490    }
17491
17492    @Override
17493    public void registerMoveCallback(IPackageMoveObserver callback) {
17494        mContext.enforceCallingOrSelfPermission(
17495                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17496        mMoveCallbacks.register(callback);
17497    }
17498
17499    @Override
17500    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17501        mContext.enforceCallingOrSelfPermission(
17502                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17503        mMoveCallbacks.unregister(callback);
17504    }
17505
17506    @Override
17507    public boolean setInstallLocation(int loc) {
17508        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17509                null);
17510        if (getInstallLocation() == loc) {
17511            return true;
17512        }
17513        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17514                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17515            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17516                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17517            return true;
17518        }
17519        return false;
17520   }
17521
17522    @Override
17523    public int getInstallLocation() {
17524        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17525                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17526                PackageHelper.APP_INSTALL_AUTO);
17527    }
17528
17529    /** Called by UserManagerService */
17530    void cleanUpUser(UserManagerService userManager, int userHandle) {
17531        synchronized (mPackages) {
17532            mDirtyUsers.remove(userHandle);
17533            mUserNeedsBadging.delete(userHandle);
17534            mSettings.removeUserLPw(userHandle);
17535            mPendingBroadcasts.remove(userHandle);
17536            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17537        }
17538        synchronized (mInstallLock) {
17539            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17540            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17541                final String volumeUuid = vol.getFsUuid();
17542                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17543                try {
17544                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17545                } catch (InstallerException e) {
17546                    Slog.w(TAG, "Failed to remove user data", e);
17547                }
17548            }
17549            synchronized (mPackages) {
17550                removeUnusedPackagesLILPw(userManager, userHandle);
17551            }
17552        }
17553    }
17554
17555    /**
17556     * We're removing userHandle and would like to remove any downloaded packages
17557     * that are no longer in use by any other user.
17558     * @param userHandle the user being removed
17559     */
17560    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17561        final boolean DEBUG_CLEAN_APKS = false;
17562        int [] users = userManager.getUserIds();
17563        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17564        while (psit.hasNext()) {
17565            PackageSetting ps = psit.next();
17566            if (ps.pkg == null) {
17567                continue;
17568            }
17569            final String packageName = ps.pkg.packageName;
17570            // Skip over if system app
17571            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17572                continue;
17573            }
17574            if (DEBUG_CLEAN_APKS) {
17575                Slog.i(TAG, "Checking package " + packageName);
17576            }
17577            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17578            if (keep) {
17579                if (DEBUG_CLEAN_APKS) {
17580                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17581                }
17582            } else {
17583                for (int i = 0; i < users.length; i++) {
17584                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17585                        keep = true;
17586                        if (DEBUG_CLEAN_APKS) {
17587                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17588                                    + users[i]);
17589                        }
17590                        break;
17591                    }
17592                }
17593            }
17594            if (!keep) {
17595                if (DEBUG_CLEAN_APKS) {
17596                    Slog.i(TAG, "  Removing package " + packageName);
17597                }
17598                mHandler.post(new Runnable() {
17599                    public void run() {
17600                        deletePackageX(packageName, userHandle, 0);
17601                    } //end run
17602                });
17603            }
17604        }
17605    }
17606
17607    /** Called by UserManagerService */
17608    void createNewUser(int userHandle) {
17609        synchronized (mInstallLock) {
17610            try {
17611                mInstaller.createUserConfig(userHandle);
17612            } catch (InstallerException e) {
17613                Slog.w(TAG, "Failed to create user config", e);
17614            }
17615            mSettings.createNewUserLI(this, mInstaller, userHandle);
17616        }
17617        synchronized (mPackages) {
17618            applyFactoryDefaultBrowserLPw(userHandle);
17619            primeDomainVerificationsLPw(userHandle);
17620        }
17621    }
17622
17623    void newUserCreated(final int userHandle) {
17624        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17625        // If permission review for legacy apps is required, we represent
17626        // dagerous permissions for such apps as always granted runtime
17627        // permissions to keep per user flag state whether review is needed.
17628        // Hence, if a new user is added we have to propagate dangerous
17629        // permission grants for these legacy apps.
17630        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17631            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17632                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17633        }
17634    }
17635
17636    @Override
17637    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17638        mContext.enforceCallingOrSelfPermission(
17639                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17640                "Only package verification agents can read the verifier device identity");
17641
17642        synchronized (mPackages) {
17643            return mSettings.getVerifierDeviceIdentityLPw();
17644        }
17645    }
17646
17647    @Override
17648    public void setPermissionEnforced(String permission, boolean enforced) {
17649        // TODO: Now that we no longer change GID for storage, this should to away.
17650        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17651                "setPermissionEnforced");
17652        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17653            synchronized (mPackages) {
17654                if (mSettings.mReadExternalStorageEnforced == null
17655                        || mSettings.mReadExternalStorageEnforced != enforced) {
17656                    mSettings.mReadExternalStorageEnforced = enforced;
17657                    mSettings.writeLPr();
17658                }
17659            }
17660            // kill any non-foreground processes so we restart them and
17661            // grant/revoke the GID.
17662            final IActivityManager am = ActivityManagerNative.getDefault();
17663            if (am != null) {
17664                final long token = Binder.clearCallingIdentity();
17665                try {
17666                    am.killProcessesBelowForeground("setPermissionEnforcement");
17667                } catch (RemoteException e) {
17668                } finally {
17669                    Binder.restoreCallingIdentity(token);
17670                }
17671            }
17672        } else {
17673            throw new IllegalArgumentException("No selective enforcement for " + permission);
17674        }
17675    }
17676
17677    @Override
17678    @Deprecated
17679    public boolean isPermissionEnforced(String permission) {
17680        return true;
17681    }
17682
17683    @Override
17684    public boolean isStorageLow() {
17685        final long token = Binder.clearCallingIdentity();
17686        try {
17687            final DeviceStorageMonitorInternal
17688                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17689            if (dsm != null) {
17690                return dsm.isMemoryLow();
17691            } else {
17692                return false;
17693            }
17694        } finally {
17695            Binder.restoreCallingIdentity(token);
17696        }
17697    }
17698
17699    @Override
17700    public IPackageInstaller getPackageInstaller() {
17701        return mInstallerService;
17702    }
17703
17704    private boolean userNeedsBadging(int userId) {
17705        int index = mUserNeedsBadging.indexOfKey(userId);
17706        if (index < 0) {
17707            final UserInfo userInfo;
17708            final long token = Binder.clearCallingIdentity();
17709            try {
17710                userInfo = sUserManager.getUserInfo(userId);
17711            } finally {
17712                Binder.restoreCallingIdentity(token);
17713            }
17714            final boolean b;
17715            if (userInfo != null && userInfo.isManagedProfile()) {
17716                b = true;
17717            } else {
17718                b = false;
17719            }
17720            mUserNeedsBadging.put(userId, b);
17721            return b;
17722        }
17723        return mUserNeedsBadging.valueAt(index);
17724    }
17725
17726    @Override
17727    public KeySet getKeySetByAlias(String packageName, String alias) {
17728        if (packageName == null || alias == null) {
17729            return null;
17730        }
17731        synchronized(mPackages) {
17732            final PackageParser.Package pkg = mPackages.get(packageName);
17733            if (pkg == null) {
17734                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17735                throw new IllegalArgumentException("Unknown package: " + packageName);
17736            }
17737            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17738            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17739        }
17740    }
17741
17742    @Override
17743    public KeySet getSigningKeySet(String packageName) {
17744        if (packageName == null) {
17745            return null;
17746        }
17747        synchronized(mPackages) {
17748            final PackageParser.Package pkg = mPackages.get(packageName);
17749            if (pkg == null) {
17750                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17751                throw new IllegalArgumentException("Unknown package: " + packageName);
17752            }
17753            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17754                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17755                throw new SecurityException("May not access signing KeySet of other apps.");
17756            }
17757            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17758            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17759        }
17760    }
17761
17762    @Override
17763    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17764        if (packageName == null || ks == null) {
17765            return false;
17766        }
17767        synchronized(mPackages) {
17768            final PackageParser.Package pkg = mPackages.get(packageName);
17769            if (pkg == null) {
17770                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17771                throw new IllegalArgumentException("Unknown package: " + packageName);
17772            }
17773            IBinder ksh = ks.getToken();
17774            if (ksh instanceof KeySetHandle) {
17775                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17776                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17777            }
17778            return false;
17779        }
17780    }
17781
17782    @Override
17783    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17784        if (packageName == null || ks == null) {
17785            return false;
17786        }
17787        synchronized(mPackages) {
17788            final PackageParser.Package pkg = mPackages.get(packageName);
17789            if (pkg == null) {
17790                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17791                throw new IllegalArgumentException("Unknown package: " + packageName);
17792            }
17793            IBinder ksh = ks.getToken();
17794            if (ksh instanceof KeySetHandle) {
17795                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17796                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17797            }
17798            return false;
17799        }
17800    }
17801
17802    private void deletePackageIfUnusedLPr(final String packageName) {
17803        PackageSetting ps = mSettings.mPackages.get(packageName);
17804        if (ps == null) {
17805            return;
17806        }
17807        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17808            // TODO Implement atomic delete if package is unused
17809            // It is currently possible that the package will be deleted even if it is installed
17810            // after this method returns.
17811            mHandler.post(new Runnable() {
17812                public void run() {
17813                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17814                }
17815            });
17816        }
17817    }
17818
17819    /**
17820     * Check and throw if the given before/after packages would be considered a
17821     * downgrade.
17822     */
17823    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17824            throws PackageManagerException {
17825        if (after.versionCode < before.mVersionCode) {
17826            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17827                    "Update version code " + after.versionCode + " is older than current "
17828                    + before.mVersionCode);
17829        } else if (after.versionCode == before.mVersionCode) {
17830            if (after.baseRevisionCode < before.baseRevisionCode) {
17831                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17832                        "Update base revision code " + after.baseRevisionCode
17833                        + " is older than current " + before.baseRevisionCode);
17834            }
17835
17836            if (!ArrayUtils.isEmpty(after.splitNames)) {
17837                for (int i = 0; i < after.splitNames.length; i++) {
17838                    final String splitName = after.splitNames[i];
17839                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17840                    if (j != -1) {
17841                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17842                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17843                                    "Update split " + splitName + " revision code "
17844                                    + after.splitRevisionCodes[i] + " is older than current "
17845                                    + before.splitRevisionCodes[j]);
17846                        }
17847                    }
17848                }
17849            }
17850        }
17851    }
17852
17853    private static class MoveCallbacks extends Handler {
17854        private static final int MSG_CREATED = 1;
17855        private static final int MSG_STATUS_CHANGED = 2;
17856
17857        private final RemoteCallbackList<IPackageMoveObserver>
17858                mCallbacks = new RemoteCallbackList<>();
17859
17860        private final SparseIntArray mLastStatus = new SparseIntArray();
17861
17862        public MoveCallbacks(Looper looper) {
17863            super(looper);
17864        }
17865
17866        public void register(IPackageMoveObserver callback) {
17867            mCallbacks.register(callback);
17868        }
17869
17870        public void unregister(IPackageMoveObserver callback) {
17871            mCallbacks.unregister(callback);
17872        }
17873
17874        @Override
17875        public void handleMessage(Message msg) {
17876            final SomeArgs args = (SomeArgs) msg.obj;
17877            final int n = mCallbacks.beginBroadcast();
17878            for (int i = 0; i < n; i++) {
17879                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17880                try {
17881                    invokeCallback(callback, msg.what, args);
17882                } catch (RemoteException ignored) {
17883                }
17884            }
17885            mCallbacks.finishBroadcast();
17886            args.recycle();
17887        }
17888
17889        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17890                throws RemoteException {
17891            switch (what) {
17892                case MSG_CREATED: {
17893                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17894                    break;
17895                }
17896                case MSG_STATUS_CHANGED: {
17897                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17898                    break;
17899                }
17900            }
17901        }
17902
17903        private void notifyCreated(int moveId, Bundle extras) {
17904            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17905
17906            final SomeArgs args = SomeArgs.obtain();
17907            args.argi1 = moveId;
17908            args.arg2 = extras;
17909            obtainMessage(MSG_CREATED, args).sendToTarget();
17910        }
17911
17912        private void notifyStatusChanged(int moveId, int status) {
17913            notifyStatusChanged(moveId, status, -1);
17914        }
17915
17916        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17917            Slog.v(TAG, "Move " + moveId + " status " + status);
17918
17919            final SomeArgs args = SomeArgs.obtain();
17920            args.argi1 = moveId;
17921            args.argi2 = status;
17922            args.arg3 = estMillis;
17923            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17924
17925            synchronized (mLastStatus) {
17926                mLastStatus.put(moveId, status);
17927            }
17928        }
17929    }
17930
17931    private final static class OnPermissionChangeListeners extends Handler {
17932        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17933
17934        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17935                new RemoteCallbackList<>();
17936
17937        public OnPermissionChangeListeners(Looper looper) {
17938            super(looper);
17939        }
17940
17941        @Override
17942        public void handleMessage(Message msg) {
17943            switch (msg.what) {
17944                case MSG_ON_PERMISSIONS_CHANGED: {
17945                    final int uid = msg.arg1;
17946                    handleOnPermissionsChanged(uid);
17947                } break;
17948            }
17949        }
17950
17951        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17952            mPermissionListeners.register(listener);
17953
17954        }
17955
17956        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17957            mPermissionListeners.unregister(listener);
17958        }
17959
17960        public void onPermissionsChanged(int uid) {
17961            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17962                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17963            }
17964        }
17965
17966        private void handleOnPermissionsChanged(int uid) {
17967            final int count = mPermissionListeners.beginBroadcast();
17968            try {
17969                for (int i = 0; i < count; i++) {
17970                    IOnPermissionsChangeListener callback = mPermissionListeners
17971                            .getBroadcastItem(i);
17972                    try {
17973                        callback.onPermissionsChanged(uid);
17974                    } catch (RemoteException e) {
17975                        Log.e(TAG, "Permission listener is dead", e);
17976                    }
17977                }
17978            } finally {
17979                mPermissionListeners.finishBroadcast();
17980            }
17981        }
17982    }
17983
17984    private class PackageManagerInternalImpl extends PackageManagerInternal {
17985        @Override
17986        public void setLocationPackagesProvider(PackagesProvider provider) {
17987            synchronized (mPackages) {
17988                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17989            }
17990        }
17991
17992        @Override
17993        public void setImePackagesProvider(PackagesProvider provider) {
17994            synchronized (mPackages) {
17995                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17996            }
17997        }
17998
17999        @Override
18000        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18001            synchronized (mPackages) {
18002                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18003            }
18004        }
18005
18006        @Override
18007        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18008            synchronized (mPackages) {
18009                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18010            }
18011        }
18012
18013        @Override
18014        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18015            synchronized (mPackages) {
18016                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18017            }
18018        }
18019
18020        @Override
18021        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18022            synchronized (mPackages) {
18023                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18024            }
18025        }
18026
18027        @Override
18028        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18029            synchronized (mPackages) {
18030                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18031            }
18032        }
18033
18034        @Override
18035        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18036            synchronized (mPackages) {
18037                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18038                        packageName, userId);
18039            }
18040        }
18041
18042        @Override
18043        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18044            synchronized (mPackages) {
18045                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18046                        packageName, userId);
18047            }
18048        }
18049
18050        @Override
18051        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18052            synchronized (mPackages) {
18053                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18054                        packageName, userId);
18055            }
18056        }
18057
18058        @Override
18059        public void setKeepUninstalledPackages(final List<String> packageList) {
18060            Preconditions.checkNotNull(packageList);
18061            List<String> removedFromList = null;
18062            synchronized (mPackages) {
18063                if (mKeepUninstalledPackages != null) {
18064                    final int packagesCount = mKeepUninstalledPackages.size();
18065                    for (int i = 0; i < packagesCount; i++) {
18066                        String oldPackage = mKeepUninstalledPackages.get(i);
18067                        if (packageList != null && packageList.contains(oldPackage)) {
18068                            continue;
18069                        }
18070                        if (removedFromList == null) {
18071                            removedFromList = new ArrayList<>();
18072                        }
18073                        removedFromList.add(oldPackage);
18074                    }
18075                }
18076                mKeepUninstalledPackages = new ArrayList<>(packageList);
18077                if (removedFromList != null) {
18078                    final int removedCount = removedFromList.size();
18079                    for (int i = 0; i < removedCount; i++) {
18080                        deletePackageIfUnusedLPr(removedFromList.get(i));
18081                    }
18082                }
18083            }
18084        }
18085
18086        @Override
18087        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18088            synchronized (mPackages) {
18089                // If we do not support permission review, done.
18090                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18091                    return false;
18092                }
18093
18094                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18095                if (packageSetting == null) {
18096                    return false;
18097                }
18098
18099                // Permission review applies only to apps not supporting the new permission model.
18100                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18101                    return false;
18102                }
18103
18104                // Legacy apps have the permission and get user consent on launch.
18105                PermissionsState permissionsState = packageSetting.getPermissionsState();
18106                return permissionsState.isPermissionReviewRequired(userId);
18107            }
18108        }
18109    }
18110
18111    @Override
18112    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18113        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18114        synchronized (mPackages) {
18115            final long identity = Binder.clearCallingIdentity();
18116            try {
18117                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18118                        packageNames, userId);
18119            } finally {
18120                Binder.restoreCallingIdentity(identity);
18121            }
18122        }
18123    }
18124
18125    private static void enforceSystemOrPhoneCaller(String tag) {
18126        int callingUid = Binder.getCallingUid();
18127        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18128            throw new SecurityException(
18129                    "Cannot call " + tag + " from UID " + callingUid);
18130        }
18131    }
18132
18133    boolean isHistoricalPackageUsageAvailable() {
18134        return mPackageUsage.isHistoricalPackageUsageAvailable();
18135    }
18136}
18137