PackageManagerService.java revision 415dd94ae5c71aaef62b66463724544b44b1f41f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
72import static android.content.pm.PackageManager.PERMISSION_DENIED;
73import static android.content.pm.PackageManager.PERMISSION_GRANTED;
74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
75import static android.content.pm.PackageParser.isApkFile;
76import static android.os.Process.PACKAGE_INFO_GID;
77import static android.os.Process.SYSTEM_UID;
78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79import static android.system.OsConstants.O_CREAT;
80import static android.system.OsConstants.O_RDWR;
81
82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86import static com.android.internal.util.ArrayUtils.appendInt;
87import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
96
97import android.Manifest;
98import android.annotation.NonNull;
99import android.annotation.Nullable;
100import android.app.ActivityManager;
101import android.app.ActivityManagerNative;
102import android.app.IActivityManager;
103import android.app.admin.IDevicePolicyManager;
104import android.app.backup.IBackupManager;
105import android.content.BroadcastReceiver;
106import android.content.ComponentName;
107import android.content.Context;
108import android.content.IIntentReceiver;
109import android.content.Intent;
110import android.content.IntentFilter;
111import android.content.IntentSender;
112import android.content.IntentSender.SendIntentException;
113import android.content.ServiceConnection;
114import android.content.pm.ActivityInfo;
115import android.content.pm.ApplicationInfo;
116import android.content.pm.AppsQueryHelper;
117import android.content.pm.ComponentInfo;
118import android.content.pm.EphemeralApplicationInfo;
119import android.content.pm.EphemeralResolveInfo;
120import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
121import android.content.pm.FeatureInfo;
122import android.content.pm.IOnPermissionsChangeListener;
123import android.content.pm.IPackageDataObserver;
124import android.content.pm.IPackageDeleteObserver;
125import android.content.pm.IPackageDeleteObserver2;
126import android.content.pm.IPackageInstallObserver2;
127import android.content.pm.IPackageInstaller;
128import android.content.pm.IPackageManager;
129import android.content.pm.IPackageMoveObserver;
130import android.content.pm.IPackageStatsObserver;
131import android.content.pm.InstrumentationInfo;
132import android.content.pm.IntentFilterVerificationInfo;
133import android.content.pm.KeySet;
134import android.content.pm.PackageCleanItem;
135import android.content.pm.PackageInfo;
136import android.content.pm.PackageInfoLite;
137import android.content.pm.PackageInstaller;
138import android.content.pm.PackageManager;
139import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
140import android.content.pm.PackageManagerInternal;
141import android.content.pm.PackageParser;
142import android.content.pm.PackageParser.ActivityIntentInfo;
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.PrintWriter;
267import java.nio.charset.StandardCharsets;
268import java.security.MessageDigest;
269import java.security.NoSuchAlgorithmException;
270import java.security.PublicKey;
271import java.security.cert.CertificateEncodingException;
272import java.security.cert.CertificateException;
273import java.text.SimpleDateFormat;
274import java.util.ArrayList;
275import java.util.Arrays;
276import java.util.Collection;
277import java.util.Collections;
278import java.util.Comparator;
279import java.util.Date;
280import java.util.HashSet;
281import java.util.Iterator;
282import java.util.List;
283import java.util.Map;
284import java.util.Objects;
285import java.util.Set;
286import java.util.concurrent.CountDownLatch;
287import java.util.concurrent.TimeUnit;
288import java.util.concurrent.atomic.AtomicBoolean;
289import java.util.concurrent.atomic.AtomicInteger;
290import java.util.concurrent.atomic.AtomicLong;
291
292/**
293 * Keep track of all those .apks everywhere.
294 *
295 * This is very central to the platform's security; please run the unit
296 * tests whenever making modifications here:
297 *
298runtest -c android.content.pm.PackageManagerTests frameworks-core
299 *
300 * {@hide}
301 */
302public class PackageManagerService extends IPackageManager.Stub {
303    static final String TAG = "PackageManager";
304    static final boolean DEBUG_SETTINGS = false;
305    static final boolean DEBUG_PREFERRED = false;
306    static final boolean DEBUG_UPGRADE = false;
307    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
308    private static final boolean DEBUG_BACKUP = false;
309    private static final boolean DEBUG_INSTALL = false;
310    private static final boolean DEBUG_REMOVE = false;
311    private static final boolean DEBUG_BROADCASTS = false;
312    private static final boolean DEBUG_SHOW_INFO = false;
313    private static final boolean DEBUG_PACKAGE_INFO = false;
314    private static final boolean DEBUG_INTENT_MATCHING = false;
315    private static final boolean DEBUG_PACKAGE_SCANNING = false;
316    private static final boolean DEBUG_VERIFY = false;
317
318    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
319    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
320    // user, but by default initialize to this.
321    static final boolean DEBUG_DEXOPT = false;
322
323    private static final boolean DEBUG_ABI_SELECTION = false;
324    private static final boolean DEBUG_EPHEMERAL = false;
325    private static final boolean DEBUG_TRIAGED_MISSING = false;
326    private static final boolean DEBUG_APP_DATA = false;
327
328    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
329
330    private static final boolean DISABLE_EPHEMERAL_APPS = true;
331
332    private static final int RADIO_UID = Process.PHONE_UID;
333    private static final int LOG_UID = Process.LOG_UID;
334    private static final int NFC_UID = Process.NFC_UID;
335    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
336    private static final int SHELL_UID = Process.SHELL_UID;
337
338    // Cap the size of permission trees that 3rd party apps can define
339    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
340
341    // Suffix used during package installation when copying/moving
342    // package apks to install directory.
343    private static final String INSTALL_PACKAGE_SUFFIX = "-";
344
345    static final int SCAN_NO_DEX = 1<<1;
346    static final int SCAN_FORCE_DEX = 1<<2;
347    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
348    static final int SCAN_NEW_INSTALL = 1<<4;
349    static final int SCAN_NO_PATHS = 1<<5;
350    static final int SCAN_UPDATE_TIME = 1<<6;
351    static final int SCAN_DEFER_DEX = 1<<7;
352    static final int SCAN_BOOTING = 1<<8;
353    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
354    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
355    static final int SCAN_REPLACING = 1<<11;
356    static final int SCAN_REQUIRE_KNOWN = 1<<12;
357    static final int SCAN_MOVE = 1<<13;
358    static final int SCAN_INITIAL = 1<<14;
359    static final int SCAN_CHECK_ONLY = 1<<15;
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
1422                    if (data != null) {
1423                        InstallArgs args = data.args;
1424                        PackageInstalledInfo parentRes = data.res;
1425
1426                        final boolean grantPermissions = (args.installFlags
1427                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1428                        final String[] grantedPermissions = args.installGrantPermissions;
1429
1430                        // Handle the parent package
1431                        handlePackagePostInstall(parentRes, grantPermissions, grantedPermissions,
1432                                args.observer);
1433
1434                        // Handle the child packages
1435                        final int childCount = (parentRes.addedChildPackages != null)
1436                                ? parentRes.addedChildPackages.size() : 0;
1437                        for (int i = 0; i < childCount; i++) {
1438                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1439                            handlePackagePostInstall(childRes, grantPermissions, grantedPermissions,
1440                                    args.observer);
1441                        }
1442
1443                        // Log tracing if needed
1444                        if (args.traceMethod != null) {
1445                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1446                                    args.traceCookie);
1447                        }
1448                    } else {
1449                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1450                    }
1451
1452                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1453                } break;
1454                case UPDATED_MEDIA_STATUS: {
1455                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1456                    boolean reportStatus = msg.arg1 == 1;
1457                    boolean doGc = msg.arg2 == 1;
1458                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1459                    if (doGc) {
1460                        // Force a gc to clear up stale containers.
1461                        Runtime.getRuntime().gc();
1462                    }
1463                    if (msg.obj != null) {
1464                        @SuppressWarnings("unchecked")
1465                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1466                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1467                        // Unload containers
1468                        unloadAllContainers(args);
1469                    }
1470                    if (reportStatus) {
1471                        try {
1472                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1473                            PackageHelper.getMountService().finishMediaUpdate();
1474                        } catch (RemoteException e) {
1475                            Log.e(TAG, "MountService not running?");
1476                        }
1477                    }
1478                } break;
1479                case WRITE_SETTINGS: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_SETTINGS);
1483                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1484                        mSettings.writeLPr();
1485                        mDirtyUsers.clear();
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                } break;
1489                case WRITE_PACKAGE_RESTRICTIONS: {
1490                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1491                    synchronized (mPackages) {
1492                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1493                        for (int userId : mDirtyUsers) {
1494                            mSettings.writePackageRestrictionsLPr(userId);
1495                        }
1496                        mDirtyUsers.clear();
1497                    }
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1499                } break;
1500                case CHECK_PENDING_VERIFICATION: {
1501                    final int verificationId = msg.arg1;
1502                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1503
1504                    if ((state != null) && !state.timeoutExtended()) {
1505                        final InstallArgs args = state.getInstallArgs();
1506                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1507
1508                        Slog.i(TAG, "Verification timed out for " + originUri);
1509                        mPendingVerification.remove(verificationId);
1510
1511                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1512
1513                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1514                            Slog.i(TAG, "Continuing with installation of " + originUri);
1515                            state.setVerifierResponse(Binder.getCallingUid(),
1516                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1517                            broadcastPackageVerified(verificationId, originUri,
1518                                    PackageManager.VERIFICATION_ALLOW,
1519                                    state.getInstallArgs().getUser());
1520                            try {
1521                                ret = args.copyApk(mContainerService, true);
1522                            } catch (RemoteException e) {
1523                                Slog.e(TAG, "Could not contact the ContainerService");
1524                            }
1525                        } else {
1526                            broadcastPackageVerified(verificationId, originUri,
1527                                    PackageManager.VERIFICATION_REJECT,
1528                                    state.getInstallArgs().getUser());
1529                        }
1530
1531                        Trace.asyncTraceEnd(
1532                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1533
1534                        processPendingInstall(args, ret);
1535                        mHandler.sendEmptyMessage(MCS_UNBIND);
1536                    }
1537                    break;
1538                }
1539                case PACKAGE_VERIFIED: {
1540                    final int verificationId = msg.arg1;
1541
1542                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1543                    if (state == null) {
1544                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1545                        break;
1546                    }
1547
1548                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1549
1550                    state.setVerifierResponse(response.callerUid, response.code);
1551
1552                    if (state.isVerificationComplete()) {
1553                        mPendingVerification.remove(verificationId);
1554
1555                        final InstallArgs args = state.getInstallArgs();
1556                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1557
1558                        int ret;
1559                        if (state.isInstallAllowed()) {
1560                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1561                            broadcastPackageVerified(verificationId, originUri,
1562                                    response.code, state.getInstallArgs().getUser());
1563                            try {
1564                                ret = args.copyApk(mContainerService, true);
1565                            } catch (RemoteException e) {
1566                                Slog.e(TAG, "Could not contact the ContainerService");
1567                            }
1568                        } else {
1569                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1570                        }
1571
1572                        Trace.asyncTraceEnd(
1573                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1574
1575                        processPendingInstall(args, ret);
1576                        mHandler.sendEmptyMessage(MCS_UNBIND);
1577                    }
1578
1579                    break;
1580                }
1581                case START_INTENT_FILTER_VERIFICATIONS: {
1582                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1583                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1584                            params.replacing, params.pkg);
1585                    break;
1586                }
1587                case INTENT_FILTER_VERIFIED: {
1588                    final int verificationId = msg.arg1;
1589
1590                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1591                            verificationId);
1592                    if (state == null) {
1593                        Slog.w(TAG, "Invalid IntentFilter verification token "
1594                                + verificationId + " received");
1595                        break;
1596                    }
1597
1598                    final int userId = state.getUserId();
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "Processing IntentFilter verification with token:"
1602                            + verificationId + " and userId:" + userId);
1603
1604                    final IntentFilterVerificationResponse response =
1605                            (IntentFilterVerificationResponse) msg.obj;
1606
1607                    state.setVerifierResponse(response.callerUid, response.code);
1608
1609                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                            "IntentFilter verification with token:" + verificationId
1611                            + " and userId:" + userId
1612                            + " is settings verifier response with response code:"
1613                            + response.code);
1614
1615                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1616                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1617                                + response.getFailedDomainsString());
1618                    }
1619
1620                    if (state.isVerificationComplete()) {
1621                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1622                    } else {
1623                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1624                                "IntentFilter verification with token:" + verificationId
1625                                + " was not said to be complete");
1626                    }
1627
1628                    break;
1629                }
1630            }
1631        }
1632    }
1633
1634    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1635            String[] grantedPermissions, IPackageInstallObserver2 installObserver) {
1636        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1637            // Send the removed broadcasts
1638            if (res.removedInfo != null) {
1639                res.removedInfo.sendPackageRemovedBroadcasts();
1640            }
1641
1642            // Now that we successfully installed the package, grant runtime
1643            // permissions if requested before broadcasting the install.
1644            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1645                    >= Build.VERSION_CODES.M) {
1646                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1647            }
1648
1649            final boolean update = res.removedInfo != null
1650                    && res.removedInfo.removedPackage != null;
1651
1652            // If this is the first time we have child packages for a disabled privileged
1653            // app that had no children, we grant requested runtime permissions to the new
1654            // children if the parent on the system image had them already granted.
1655            if (res.pkg.parentPackage != null) {
1656                synchronized (mPackages) {
1657                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1658                }
1659            }
1660
1661            synchronized (mPackages) {
1662                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1663            }
1664
1665            final String packageName = res.pkg.applicationInfo.packageName;
1666            Bundle extras = new Bundle(1);
1667            extras.putInt(Intent.EXTRA_UID, res.uid);
1668
1669            // Determine the set of users who are adding this package for
1670            // the first time vs. those who are seeing an update.
1671            int[] firstUsers = EMPTY_INT_ARRAY;
1672            int[] updateUsers = EMPTY_INT_ARRAY;
1673            if (res.origUsers == null || res.origUsers.length == 0) {
1674                firstUsers = res.newUsers;
1675            } else {
1676                for (int newUser : res.newUsers) {
1677                    boolean isNew = true;
1678                    for (int origUser : res.origUsers) {
1679                        if (origUser == newUser) {
1680                            isNew = false;
1681                            break;
1682                        }
1683                    }
1684                    if (isNew) {
1685                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1686                    } else {
1687                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1688                    }
1689                }
1690            }
1691
1692            // Send installed broadcasts if the install/update is not ephemeral
1693            if (!isEphemeral(res.pkg)) {
1694                // Send added for users that see the package for the first time
1695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1696                        extras, 0 /*flags*/, null /*targetPackage*/,
1697                        null /*finishedReceiver*/, firstUsers);
1698
1699                // Send added for users that don't see the package for the first time
1700                if (update) {
1701                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1702                }
1703                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1704                        extras, 0 /*flags*/, null /*targetPackage*/,
1705                        null /*finishedReceiver*/, updateUsers);
1706
1707                // Send replaced for users that don't see the package for the first time
1708                if (update) {
1709                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1710                            packageName, extras, 0 /*flags*/,
1711                            null /*targetPackage*/, null /*finishedReceiver*/,
1712                            updateUsers);
1713                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1714                            null /*package*/, null /*extras*/, 0 /*flags*/,
1715                            packageName /*targetPackage*/,
1716                            null /*finishedReceiver*/, updateUsers);
1717                }
1718
1719                // Send broadcast package appeared if forward locked/external for all users
1720                // treat asec-hosted packages like removable media on upgrade
1721                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1722                    if (DEBUG_INSTALL) {
1723                        Slog.i(TAG, "upgrading pkg " + res.pkg
1724                                + " is ASEC-hosted -> AVAILABLE");
1725                    }
1726                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1727                    ArrayList<String> pkgList = new ArrayList<>(1);
1728                    pkgList.add(packageName);
1729                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1730                }
1731            }
1732
1733            // Work that needs to happen on first install within each user
1734            if (firstUsers != null && firstUsers.length > 0) {
1735                synchronized (mPackages) {
1736                    for (int userId : firstUsers) {
1737                        // If this app is a browser and it's newly-installed for some
1738                        // users, clear any default-browser state in those users. The
1739                        // app's nature doesn't depend on the user, so we can just check
1740                        // its browser nature in any user and generalize.
1741                        if (packageIsBrowser(packageName, userId)) {
1742                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1743                        }
1744
1745                        // We may also need to apply pending (restored) runtime
1746                        // permission grants within these users.
1747                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1748                    }
1749                }
1750            }
1751
1752            // Log current value of "unknown sources" setting
1753            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1754                    getUnknownSourcesSettings());
1755
1756            // Force a gc to clear up things
1757            Runtime.getRuntime().gc();
1758
1759            // Remove the replaced package's older resources safely now
1760            // We delete after a gc for applications  on sdcard.
1761            if (res.removedInfo != null && res.removedInfo.args != null) {
1762                synchronized (mInstallLock) {
1763                    res.removedInfo.args.doPostDeleteLI(true);
1764                }
1765            }
1766        }
1767
1768        // If someone is watching installs - notify them
1769        if (installObserver != null) {
1770            try {
1771                Bundle extras = extrasForInstallResult(res);
1772                installObserver.onPackageInstalled(res.name, res.returnCode,
1773                        res.returnMsg, extras);
1774            } catch (RemoteException e) {
1775                Slog.i(TAG, "Observer no longer exists.");
1776            }
1777        }
1778    }
1779
1780    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1781            PackageParser.Package pkg) {
1782        if (pkg.parentPackage == null) {
1783            return;
1784        }
1785        if (pkg.requestedPermissions == null) {
1786            return;
1787        }
1788        final PackageSetting disabledSysParentPs = mSettings
1789                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1790        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1791                || !disabledSysParentPs.isPrivileged()
1792                || (disabledSysParentPs.childPackageNames != null
1793                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1794            return;
1795        }
1796        final int[] allUserIds = sUserManager.getUserIds();
1797        final int permCount = pkg.requestedPermissions.size();
1798        for (int i = 0; i < permCount; i++) {
1799            String permission = pkg.requestedPermissions.get(i);
1800            BasePermission bp = mSettings.mPermissions.get(permission);
1801            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1802                continue;
1803            }
1804            for (int userId : allUserIds) {
1805                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1806                        permission, userId)) {
1807                    grantRuntimePermission(pkg.packageName, permission, userId);
1808                }
1809            }
1810        }
1811    }
1812
1813    private StorageEventListener mStorageListener = new StorageEventListener() {
1814        @Override
1815        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1816            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1817                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1818                    final String volumeUuid = vol.getFsUuid();
1819
1820                    // Clean up any users or apps that were removed or recreated
1821                    // while this volume was missing
1822                    reconcileUsers(volumeUuid);
1823                    reconcileApps(volumeUuid);
1824
1825                    // Clean up any install sessions that expired or were
1826                    // cancelled while this volume was missing
1827                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1828
1829                    loadPrivatePackages(vol);
1830
1831                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1832                    unloadPrivatePackages(vol);
1833                }
1834            }
1835
1836            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1837                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1838                    updateExternalMediaStatus(true, false);
1839                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1840                    updateExternalMediaStatus(false, false);
1841                }
1842            }
1843        }
1844
1845        @Override
1846        public void onVolumeForgotten(String fsUuid) {
1847            if (TextUtils.isEmpty(fsUuid)) {
1848                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1849                return;
1850            }
1851
1852            // Remove any apps installed on the forgotten volume
1853            synchronized (mPackages) {
1854                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1855                for (PackageSetting ps : packages) {
1856                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1857                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1858                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1859                }
1860
1861                mSettings.onVolumeForgotten(fsUuid);
1862                mSettings.writeLPr();
1863            }
1864        }
1865    };
1866
1867    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1868            String[] grantedPermissions) {
1869        for (int userId : userIds) {
1870            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1871        }
1872
1873        // We could have touched GID membership, so flush out packages.list
1874        synchronized (mPackages) {
1875            mSettings.writePackageListLPr();
1876        }
1877    }
1878
1879    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1880            String[] grantedPermissions) {
1881        SettingBase sb = (SettingBase) pkg.mExtras;
1882        if (sb == null) {
1883            return;
1884        }
1885
1886        PermissionsState permissionsState = sb.getPermissionsState();
1887
1888        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1889                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1890
1891        synchronized (mPackages) {
1892            for (String permission : pkg.requestedPermissions) {
1893                BasePermission bp = mSettings.mPermissions.get(permission);
1894                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1895                        && (grantedPermissions == null
1896                               || ArrayUtils.contains(grantedPermissions, permission))) {
1897                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1898                    // Installer cannot change immutable permissions.
1899                    if ((flags & immutableFlags) == 0) {
1900                        grantRuntimePermission(pkg.packageName, permission, userId);
1901                    }
1902                }
1903            }
1904        }
1905    }
1906
1907    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1908        Bundle extras = null;
1909        switch (res.returnCode) {
1910            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1911                extras = new Bundle();
1912                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1913                        res.origPermission);
1914                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1915                        res.origPackage);
1916                break;
1917            }
1918            case PackageManager.INSTALL_SUCCEEDED: {
1919                extras = new Bundle();
1920                extras.putBoolean(Intent.EXTRA_REPLACING,
1921                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1922                break;
1923            }
1924        }
1925        return extras;
1926    }
1927
1928    void scheduleWriteSettingsLocked() {
1929        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1930            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1931        }
1932    }
1933
1934    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1935        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1936        scheduleWritePackageRestrictionsLocked(userId);
1937    }
1938
1939    void scheduleWritePackageRestrictionsLocked(int userId) {
1940        final int[] userIds = (userId == UserHandle.USER_ALL)
1941                ? sUserManager.getUserIds() : new int[]{userId};
1942        for (int nextUserId : userIds) {
1943            if (!sUserManager.exists(nextUserId)) return;
1944            mDirtyUsers.add(nextUserId);
1945            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1946                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1947            }
1948        }
1949    }
1950
1951    public static PackageManagerService main(Context context, Installer installer,
1952            boolean factoryTest, boolean onlyCore) {
1953        PackageManagerService m = new PackageManagerService(context, installer,
1954                factoryTest, onlyCore);
1955        m.enableSystemUserPackages();
1956        ServiceManager.addService("package", m);
1957        return m;
1958    }
1959
1960    private void enableSystemUserPackages() {
1961        if (!UserManager.isSplitSystemUser()) {
1962            return;
1963        }
1964        // For system user, enable apps based on the following conditions:
1965        // - app is whitelisted or belong to one of these groups:
1966        //   -- system app which has no launcher icons
1967        //   -- system app which has INTERACT_ACROSS_USERS permission
1968        //   -- system IME app
1969        // - app is not in the blacklist
1970        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1971        Set<String> enableApps = new ArraySet<>();
1972        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1973                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1974                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1975        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1976        enableApps.addAll(wlApps);
1977        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1978                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1979        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1980        enableApps.removeAll(blApps);
1981        Log.i(TAG, "Applications installed for system user: " + enableApps);
1982        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1983                UserHandle.SYSTEM);
1984        final int allAppsSize = allAps.size();
1985        synchronized (mPackages) {
1986            for (int i = 0; i < allAppsSize; i++) {
1987                String pName = allAps.get(i);
1988                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1989                // Should not happen, but we shouldn't be failing if it does
1990                if (pkgSetting == null) {
1991                    continue;
1992                }
1993                boolean install = enableApps.contains(pName);
1994                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1995                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1996                            + " for system user");
1997                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1998                }
1999            }
2000        }
2001    }
2002
2003    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2004        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2005                Context.DISPLAY_SERVICE);
2006        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2007    }
2008
2009    public PackageManagerService(Context context, Installer installer,
2010            boolean factoryTest, boolean onlyCore) {
2011        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2012                SystemClock.uptimeMillis());
2013
2014        if (mSdkVersion <= 0) {
2015            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2016        }
2017
2018        mContext = context;
2019        mFactoryTest = factoryTest;
2020        mOnlyCore = onlyCore;
2021        mMetrics = new DisplayMetrics();
2022        mSettings = new Settings(mPackages);
2023        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2024                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2025        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2026                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2027        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2028                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2029        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2030                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2031        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2032                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2033        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2034                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2035
2036        String separateProcesses = SystemProperties.get("debug.separate_processes");
2037        if (separateProcesses != null && separateProcesses.length() > 0) {
2038            if ("*".equals(separateProcesses)) {
2039                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2040                mSeparateProcesses = null;
2041                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2042            } else {
2043                mDefParseFlags = 0;
2044                mSeparateProcesses = separateProcesses.split(",");
2045                Slog.w(TAG, "Running with debug.separate_processes: "
2046                        + separateProcesses);
2047            }
2048        } else {
2049            mDefParseFlags = 0;
2050            mSeparateProcesses = null;
2051        }
2052
2053        mInstaller = installer;
2054        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2055                "*dexopt*");
2056        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2057
2058        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2059                FgThread.get().getLooper());
2060
2061        getDefaultDisplayMetrics(context, mMetrics);
2062
2063        SystemConfig systemConfig = SystemConfig.getInstance();
2064        mGlobalGids = systemConfig.getGlobalGids();
2065        mSystemPermissions = systemConfig.getSystemPermissions();
2066        mAvailableFeatures = systemConfig.getAvailableFeatures();
2067
2068        synchronized (mInstallLock) {
2069        // writer
2070        synchronized (mPackages) {
2071            mHandlerThread = new ServiceThread(TAG,
2072                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2073            mHandlerThread.start();
2074            mHandler = new PackageHandler(mHandlerThread.getLooper());
2075            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2076
2077            File dataDir = Environment.getDataDirectory();
2078            mAppInstallDir = new File(dataDir, "app");
2079            mAppLib32InstallDir = new File(dataDir, "app-lib");
2080            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2081            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2082            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2083
2084            sUserManager = new UserManagerService(context, this, mPackages);
2085
2086            // Propagate permission configuration in to package manager.
2087            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2088                    = systemConfig.getPermissions();
2089            for (int i=0; i<permConfig.size(); i++) {
2090                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2091                BasePermission bp = mSettings.mPermissions.get(perm.name);
2092                if (bp == null) {
2093                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2094                    mSettings.mPermissions.put(perm.name, bp);
2095                }
2096                if (perm.gids != null) {
2097                    bp.setGids(perm.gids, perm.perUser);
2098                }
2099            }
2100
2101            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2102            for (int i=0; i<libConfig.size(); i++) {
2103                mSharedLibraries.put(libConfig.keyAt(i),
2104                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2105            }
2106
2107            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2108
2109            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2110
2111            String customResolverActivity = Resources.getSystem().getString(
2112                    R.string.config_customResolverActivity);
2113            if (TextUtils.isEmpty(customResolverActivity)) {
2114                customResolverActivity = null;
2115            } else {
2116                mCustomResolverComponentName = ComponentName.unflattenFromString(
2117                        customResolverActivity);
2118            }
2119
2120            long startTime = SystemClock.uptimeMillis();
2121
2122            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2123                    startTime);
2124
2125            // Set flag to monitor and not change apk file paths when
2126            // scanning install directories.
2127            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2128
2129            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2130            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2131
2132            if (bootClassPath == null) {
2133                Slog.w(TAG, "No BOOTCLASSPATH found!");
2134            }
2135
2136            if (systemServerClassPath == null) {
2137                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2138            }
2139
2140            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2141            final String[] dexCodeInstructionSets =
2142                    getDexCodeInstructionSets(
2143                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2144
2145            /**
2146             * Ensure all external libraries have had dexopt run on them.
2147             */
2148            if (mSharedLibraries.size() > 0) {
2149                // NOTE: For now, we're compiling these system "shared libraries"
2150                // (and framework jars) into all available architectures. It's possible
2151                // to compile them only when we come across an app that uses them (there's
2152                // already logic for that in scanPackageLI) but that adds some complexity.
2153                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2154                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2155                        final String lib = libEntry.path;
2156                        if (lib == null) {
2157                            continue;
2158                        }
2159
2160                        try {
2161                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2162                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2163                                // Shared libraries do not have profiles so we perform a full
2164                                // AOT compilation.
2165                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2166                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2167                                        StorageManager.UUID_PRIVATE_INTERNAL,
2168                                        false /*useProfiles*/);
2169                            }
2170                        } catch (FileNotFoundException e) {
2171                            Slog.w(TAG, "Library not found: " + lib);
2172                        } catch (IOException | InstallerException e) {
2173                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2174                                    + e.getMessage());
2175                        }
2176                    }
2177                }
2178            }
2179
2180            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2181
2182            final VersionInfo ver = mSettings.getInternalVersion();
2183            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2184            // when upgrading from pre-M, promote system app permissions from install to runtime
2185            mPromoteSystemApps =
2186                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2187
2188            // save off the names of pre-existing system packages prior to scanning; we don't
2189            // want to automatically grant runtime permissions for new system apps
2190            if (mPromoteSystemApps) {
2191                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2192                while (pkgSettingIter.hasNext()) {
2193                    PackageSetting ps = pkgSettingIter.next();
2194                    if (isSystemApp(ps)) {
2195                        mExistingSystemPackages.add(ps.name);
2196                    }
2197                }
2198            }
2199
2200            // Collect vendor overlay packages.
2201            // (Do this before scanning any apps.)
2202            // For security and version matching reason, only consider
2203            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2204            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2205            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2206                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2207
2208            // Find base frameworks (resource packages without code).
2209            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2210                    | PackageParser.PARSE_IS_SYSTEM_DIR
2211                    | PackageParser.PARSE_IS_PRIVILEGED,
2212                    scanFlags | SCAN_NO_DEX, 0);
2213
2214            // Collected privileged system packages.
2215            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2216            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2217                    | PackageParser.PARSE_IS_SYSTEM_DIR
2218                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2219
2220            // Collect ordinary system packages.
2221            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2222            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2223                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2224
2225            // Collect all vendor packages.
2226            File vendorAppDir = new File("/vendor/app");
2227            try {
2228                vendorAppDir = vendorAppDir.getCanonicalFile();
2229            } catch (IOException e) {
2230                // failed to look up canonical path, continue with original one
2231            }
2232            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2233                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2234
2235            // Collect all OEM packages.
2236            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2237            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2238                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2239
2240            // Prune any system packages that no longer exist.
2241            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2242            if (!mOnlyCore) {
2243                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2244                while (psit.hasNext()) {
2245                    PackageSetting ps = psit.next();
2246
2247                    /*
2248                     * If this is not a system app, it can't be a
2249                     * disable system app.
2250                     */
2251                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2252                        continue;
2253                    }
2254
2255                    /*
2256                     * If the package is scanned, it's not erased.
2257                     */
2258                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2259                    if (scannedPkg != null) {
2260                        /*
2261                         * If the system app is both scanned and in the
2262                         * disabled packages list, then it must have been
2263                         * added via OTA. Remove it from the currently
2264                         * scanned package so the previously user-installed
2265                         * application can be scanned.
2266                         */
2267                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2268                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2269                                    + ps.name + "; removing system app.  Last known codePath="
2270                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2271                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2272                                    + scannedPkg.mVersionCode);
2273                            removePackageLI(scannedPkg, true);
2274                            mExpectingBetter.put(ps.name, ps.codePath);
2275                        }
2276
2277                        continue;
2278                    }
2279
2280                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2281                        psit.remove();
2282                        logCriticalInfo(Log.WARN, "System package " + ps.name
2283                                + " no longer exists; wiping its data");
2284                        removeDataDirsLI(null, ps.name);
2285                    } else {
2286                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2287                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2288                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2289                        }
2290                    }
2291                }
2292            }
2293
2294            //look for any incomplete package installations
2295            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2296            //clean up list
2297            for(int i = 0; i < deletePkgsList.size(); i++) {
2298                //clean up here
2299                cleanupInstallFailedPackage(deletePkgsList.get(i));
2300            }
2301            //delete tmp files
2302            deleteTempPackageFiles();
2303
2304            // Remove any shared userIDs that have no associated packages
2305            mSettings.pruneSharedUsersLPw();
2306
2307            if (!mOnlyCore) {
2308                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2309                        SystemClock.uptimeMillis());
2310                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2311
2312                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2313                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2314
2315                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2316                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2317
2318                /**
2319                 * Remove disable package settings for any updated system
2320                 * apps that were removed via an OTA. If they're not a
2321                 * previously-updated app, remove them completely.
2322                 * Otherwise, just revoke their system-level permissions.
2323                 */
2324                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2325                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2326                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2327
2328                    String msg;
2329                    if (deletedPkg == null) {
2330                        msg = "Updated system package " + deletedAppName
2331                                + " no longer exists; wiping its data";
2332                        removeDataDirsLI(null, deletedAppName);
2333                    } else {
2334                        msg = "Updated system app + " + deletedAppName
2335                                + " no longer present; removing system privileges for "
2336                                + deletedAppName;
2337
2338                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2339
2340                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2341                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2342                    }
2343                    logCriticalInfo(Log.WARN, msg);
2344                }
2345
2346                /**
2347                 * Make sure all system apps that we expected to appear on
2348                 * the userdata partition actually showed up. If they never
2349                 * appeared, crawl back and revive the system version.
2350                 */
2351                for (int i = 0; i < mExpectingBetter.size(); i++) {
2352                    final String packageName = mExpectingBetter.keyAt(i);
2353                    if (!mPackages.containsKey(packageName)) {
2354                        final File scanFile = mExpectingBetter.valueAt(i);
2355
2356                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2357                                + " but never showed up; reverting to system");
2358
2359                        final int reparseFlags;
2360                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2361                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2362                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2363                                    | PackageParser.PARSE_IS_PRIVILEGED;
2364                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2365                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2366                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2367                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2368                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2369                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2370                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2371                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2372                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2373                        } else {
2374                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2375                            continue;
2376                        }
2377
2378                        mSettings.enableSystemPackageLPw(packageName);
2379
2380                        try {
2381                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2382                        } catch (PackageManagerException e) {
2383                            Slog.e(TAG, "Failed to parse original system package: "
2384                                    + e.getMessage());
2385                        }
2386                    }
2387                }
2388            }
2389            mExpectingBetter.clear();
2390
2391            // Now that we know all of the shared libraries, update all clients to have
2392            // the correct library paths.
2393            updateAllSharedLibrariesLPw();
2394
2395            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2396                // NOTE: We ignore potential failures here during a system scan (like
2397                // the rest of the commands above) because there's precious little we
2398                // can do about it. A settings error is reported, though.
2399                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2400                        false /* boot complete */);
2401            }
2402
2403            // Now that we know all the packages we are keeping,
2404            // read and update their last usage times.
2405            mPackageUsage.readLP();
2406
2407            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2408                    SystemClock.uptimeMillis());
2409            Slog.i(TAG, "Time to scan packages: "
2410                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2411                    + " seconds");
2412
2413            // If the platform SDK has changed since the last time we booted,
2414            // we need to re-grant app permission to catch any new ones that
2415            // appear.  This is really a hack, and means that apps can in some
2416            // cases get permissions that the user didn't initially explicitly
2417            // allow...  it would be nice to have some better way to handle
2418            // this situation.
2419            int updateFlags = UPDATE_PERMISSIONS_ALL;
2420            if (ver.sdkVersion != mSdkVersion) {
2421                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2422                        + mSdkVersion + "; regranting permissions for internal storage");
2423                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2424            }
2425            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2426            ver.sdkVersion = mSdkVersion;
2427
2428            // If this is the first boot or an update from pre-M, and it is a normal
2429            // boot, then we need to initialize the default preferred apps across
2430            // all defined users.
2431            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2432                for (UserInfo user : sUserManager.getUsers(true)) {
2433                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2434                    applyFactoryDefaultBrowserLPw(user.id);
2435                    primeDomainVerificationsLPw(user.id);
2436                }
2437            }
2438
2439            // Prepare storage for system user really early during boot,
2440            // since core system apps like SettingsProvider and SystemUI
2441            // can't wait for user to start
2442            final int storageFlags;
2443            if (StorageManager.isFileBasedEncryptionEnabled()) {
2444                storageFlags = StorageManager.FLAG_STORAGE_DE;
2445            } else {
2446                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2447            }
2448            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2449                    storageFlags);
2450
2451            if (!StorageManager.isFileBasedEncryptionEnabled()
2452                    && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) {
2453                // When upgrading a non-FBE device, we might need to shuffle
2454                // around the default storage location of system apps
2455                final List<UserInfo> users = sUserManager.getUsers(true);
2456                for (PackageSetting ps : mSettings.mPackages.values()) {
2457                    if (ps.pkg == null || !ps.isSystem()) continue;
2458                    final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted()
2459                            ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
2460                    for (UserInfo user : users) {
2461                        if (ps.getInstalled(user.id)) {
2462                            try {
2463                                mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2464                                        ps.name, user.id, storageTarget);
2465                            } catch (InstallerException e) {
2466                                logCriticalInfo(Log.WARN,
2467                                        "Failed to migrate " + ps.name + ": " + e.getMessage());
2468                            }
2469                            // We may have just shuffled around app data
2470                            // directories, so prepare it one more time
2471                            prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id,
2472                                    storageFlags, ps.pkg, false);
2473                        }
2474                    }
2475                }
2476            }
2477
2478            // If this is first boot after an OTA, and a normal boot, then
2479            // we need to clear code cache directories.
2480            if (mIsUpgrade && !onlyCore) {
2481                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2482                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2483                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2484                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2485                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2486                    }
2487                }
2488                ver.fingerprint = Build.FINGERPRINT;
2489            }
2490
2491            checkDefaultBrowser();
2492
2493            // clear only after permissions and other defaults have been updated
2494            mExistingSystemPackages.clear();
2495            mPromoteSystemApps = false;
2496
2497            // All the changes are done during package scanning.
2498            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2499
2500            // can downgrade to reader
2501            mSettings.writeLPr();
2502
2503            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2504                    SystemClock.uptimeMillis());
2505
2506            if (!mOnlyCore) {
2507                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2508                mRequiredInstallerPackage = getRequiredInstallerLPr();
2509                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2510                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2511                        mIntentFilterVerifierComponent);
2512            } else {
2513                mRequiredVerifierPackage = null;
2514                mRequiredInstallerPackage = null;
2515                mIntentFilterVerifierComponent = null;
2516                mIntentFilterVerifier = null;
2517            }
2518
2519            mInstallerService = new PackageInstallerService(context, this);
2520
2521            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2522            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2523            // both the installer and resolver must be present to enable ephemeral
2524            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2525                if (DEBUG_EPHEMERAL) {
2526                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2527                            + " installer:" + ephemeralInstallerComponent);
2528                }
2529                mEphemeralResolverComponent = ephemeralResolverComponent;
2530                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2531                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2532                mEphemeralResolverConnection =
2533                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2534            } else {
2535                if (DEBUG_EPHEMERAL) {
2536                    final String missingComponent =
2537                            (ephemeralResolverComponent == null)
2538                            ? (ephemeralInstallerComponent == null)
2539                                    ? "resolver and installer"
2540                                    : "resolver"
2541                            : "installer";
2542                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2543                }
2544                mEphemeralResolverComponent = null;
2545                mEphemeralInstallerComponent = null;
2546                mEphemeralResolverConnection = null;
2547            }
2548
2549            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2550        } // synchronized (mPackages)
2551        } // synchronized (mInstallLock)
2552
2553        // Now after opening every single application zip, make sure they
2554        // are all flushed.  Not really needed, but keeps things nice and
2555        // tidy.
2556        Runtime.getRuntime().gc();
2557
2558        // The initial scanning above does many calls into installd while
2559        // holding the mPackages lock, but we're mostly interested in yelling
2560        // once we have a booted system.
2561        mInstaller.setWarnIfHeld(mPackages);
2562
2563        // Expose private service for system components to use.
2564        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2565    }
2566
2567    @Override
2568    public boolean isFirstBoot() {
2569        return !mRestoredSettings;
2570    }
2571
2572    @Override
2573    public boolean isOnlyCoreApps() {
2574        return mOnlyCore;
2575    }
2576
2577    @Override
2578    public boolean isUpgrade() {
2579        return mIsUpgrade;
2580    }
2581
2582    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2583        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2584
2585        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2586                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2587        if (matches.size() == 1) {
2588            return matches.get(0).getComponentInfo().packageName;
2589        } else {
2590            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2591            return null;
2592        }
2593    }
2594
2595    private @NonNull String getRequiredInstallerLPr() {
2596        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2597        intent.addCategory(Intent.CATEGORY_DEFAULT);
2598        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2599
2600        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2601                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2602        if (matches.size() == 1) {
2603            return matches.get(0).getComponentInfo().packageName;
2604        } else {
2605            throw new RuntimeException("There must be exactly one installer; found " + matches);
2606        }
2607    }
2608
2609    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2610        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2611
2612        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2613                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2614        ResolveInfo best = null;
2615        final int N = matches.size();
2616        for (int i = 0; i < N; i++) {
2617            final ResolveInfo cur = matches.get(i);
2618            final String packageName = cur.getComponentInfo().packageName;
2619            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2620                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2621                continue;
2622            }
2623
2624            if (best == null || cur.priority > best.priority) {
2625                best = cur;
2626            }
2627        }
2628
2629        if (best != null) {
2630            return best.getComponentInfo().getComponentName();
2631        } else {
2632            throw new RuntimeException("There must be at least one intent filter verifier");
2633        }
2634    }
2635
2636    private @Nullable ComponentName getEphemeralResolverLPr() {
2637        final String[] packageArray =
2638                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2639        if (packageArray.length == 0) {
2640            if (DEBUG_EPHEMERAL) {
2641                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2642            }
2643            return null;
2644        }
2645
2646        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2647        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2648                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2649
2650        final int N = resolvers.size();
2651        if (N == 0) {
2652            if (DEBUG_EPHEMERAL) {
2653                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2654            }
2655            return null;
2656        }
2657
2658        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2659        for (int i = 0; i < N; i++) {
2660            final ResolveInfo info = resolvers.get(i);
2661
2662            if (info.serviceInfo == null) {
2663                continue;
2664            }
2665
2666            final String packageName = info.serviceInfo.packageName;
2667            if (!possiblePackages.contains(packageName)) {
2668                if (DEBUG_EPHEMERAL) {
2669                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2670                            + " pkg: " + packageName + ", info:" + info);
2671                }
2672                continue;
2673            }
2674
2675            if (DEBUG_EPHEMERAL) {
2676                Slog.v(TAG, "Ephemeral resolver found;"
2677                        + " pkg: " + packageName + ", info:" + info);
2678            }
2679            return new ComponentName(packageName, info.serviceInfo.name);
2680        }
2681        if (DEBUG_EPHEMERAL) {
2682            Slog.v(TAG, "Ephemeral resolver NOT found");
2683        }
2684        return null;
2685    }
2686
2687    private @Nullable ComponentName getEphemeralInstallerLPr() {
2688        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2689        intent.addCategory(Intent.CATEGORY_DEFAULT);
2690        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2691
2692        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2693                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2694        if (matches.size() == 0) {
2695            return null;
2696        } else if (matches.size() == 1) {
2697            return matches.get(0).getComponentInfo().getComponentName();
2698        } else {
2699            throw new RuntimeException(
2700                    "There must be at most one ephemeral installer; found " + matches);
2701        }
2702    }
2703
2704    private void primeDomainVerificationsLPw(int userId) {
2705        if (DEBUG_DOMAIN_VERIFICATION) {
2706            Slog.d(TAG, "Priming domain verifications in user " + userId);
2707        }
2708
2709        SystemConfig systemConfig = SystemConfig.getInstance();
2710        ArraySet<String> packages = systemConfig.getLinkedApps();
2711        ArraySet<String> domains = new ArraySet<String>();
2712
2713        for (String packageName : packages) {
2714            PackageParser.Package pkg = mPackages.get(packageName);
2715            if (pkg != null) {
2716                if (!pkg.isSystemApp()) {
2717                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2718                    continue;
2719                }
2720
2721                domains.clear();
2722                for (PackageParser.Activity a : pkg.activities) {
2723                    for (ActivityIntentInfo filter : a.intents) {
2724                        if (hasValidDomains(filter)) {
2725                            domains.addAll(filter.getHostsList());
2726                        }
2727                    }
2728                }
2729
2730                if (domains.size() > 0) {
2731                    if (DEBUG_DOMAIN_VERIFICATION) {
2732                        Slog.v(TAG, "      + " + packageName);
2733                    }
2734                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2735                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2736                    // and then 'always' in the per-user state actually used for intent resolution.
2737                    final IntentFilterVerificationInfo ivi;
2738                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2739                            new ArrayList<String>(domains));
2740                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2741                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2742                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2743                } else {
2744                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2745                            + "' does not handle web links");
2746                }
2747            } else {
2748                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2749            }
2750        }
2751
2752        scheduleWritePackageRestrictionsLocked(userId);
2753        scheduleWriteSettingsLocked();
2754    }
2755
2756    private void applyFactoryDefaultBrowserLPw(int userId) {
2757        // The default browser app's package name is stored in a string resource,
2758        // with a product-specific overlay used for vendor customization.
2759        String browserPkg = mContext.getResources().getString(
2760                com.android.internal.R.string.default_browser);
2761        if (!TextUtils.isEmpty(browserPkg)) {
2762            // non-empty string => required to be a known package
2763            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2764            if (ps == null) {
2765                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2766                browserPkg = null;
2767            } else {
2768                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2769            }
2770        }
2771
2772        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2773        // default.  If there's more than one, just leave everything alone.
2774        if (browserPkg == null) {
2775            calculateDefaultBrowserLPw(userId);
2776        }
2777    }
2778
2779    private void calculateDefaultBrowserLPw(int userId) {
2780        List<String> allBrowsers = resolveAllBrowserApps(userId);
2781        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2782        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2783    }
2784
2785    private List<String> resolveAllBrowserApps(int userId) {
2786        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2787        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2788                PackageManager.MATCH_ALL, userId);
2789
2790        final int count = list.size();
2791        List<String> result = new ArrayList<String>(count);
2792        for (int i=0; i<count; i++) {
2793            ResolveInfo info = list.get(i);
2794            if (info.activityInfo == null
2795                    || !info.handleAllWebDataURI
2796                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2797                    || result.contains(info.activityInfo.packageName)) {
2798                continue;
2799            }
2800            result.add(info.activityInfo.packageName);
2801        }
2802
2803        return result;
2804    }
2805
2806    private boolean packageIsBrowser(String packageName, int userId) {
2807        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2808                PackageManager.MATCH_ALL, userId);
2809        final int N = list.size();
2810        for (int i = 0; i < N; i++) {
2811            ResolveInfo info = list.get(i);
2812            if (packageName.equals(info.activityInfo.packageName)) {
2813                return true;
2814            }
2815        }
2816        return false;
2817    }
2818
2819    private void checkDefaultBrowser() {
2820        final int myUserId = UserHandle.myUserId();
2821        final String packageName = getDefaultBrowserPackageName(myUserId);
2822        if (packageName != null) {
2823            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2824            if (info == null) {
2825                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2826                synchronized (mPackages) {
2827                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2828                }
2829            }
2830        }
2831    }
2832
2833    @Override
2834    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2835            throws RemoteException {
2836        try {
2837            return super.onTransact(code, data, reply, flags);
2838        } catch (RuntimeException e) {
2839            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2840                Slog.wtf(TAG, "Package Manager Crash", e);
2841            }
2842            throw e;
2843        }
2844    }
2845
2846    void cleanupInstallFailedPackage(PackageSetting ps) {
2847        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2848
2849        removeDataDirsLI(ps.volumeUuid, ps.name);
2850        if (ps.codePath != null) {
2851            removeCodePathLI(ps.codePath);
2852        }
2853        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2854            if (ps.resourcePath.isDirectory()) {
2855                FileUtils.deleteContents(ps.resourcePath);
2856            }
2857            ps.resourcePath.delete();
2858        }
2859        mSettings.removePackageLPw(ps.name);
2860    }
2861
2862    static int[] appendInts(int[] cur, int[] add) {
2863        if (add == null) return cur;
2864        if (cur == null) return add;
2865        final int N = add.length;
2866        for (int i=0; i<N; i++) {
2867            cur = appendInt(cur, add[i]);
2868        }
2869        return cur;
2870    }
2871
2872    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2873        if (!sUserManager.exists(userId)) return null;
2874        final PackageSetting ps = (PackageSetting) p.mExtras;
2875        if (ps == null) {
2876            return null;
2877        }
2878
2879        final PermissionsState permissionsState = ps.getPermissionsState();
2880
2881        final int[] gids = permissionsState.computeGids(userId);
2882        final Set<String> permissions = permissionsState.getPermissions(userId);
2883        final PackageUserState state = ps.readUserState(userId);
2884
2885        return PackageParser.generatePackageInfo(p, gids, flags,
2886                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2887    }
2888
2889    @Override
2890    public void checkPackageStartable(String packageName, int userId) {
2891        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2892
2893        synchronized (mPackages) {
2894            final PackageSetting ps = mSettings.mPackages.get(packageName);
2895            if (ps == null) {
2896                throw new SecurityException("Package " + packageName + " was not found!");
2897            }
2898
2899            if (mSafeMode && !ps.isSystem()) {
2900                throw new SecurityException("Package " + packageName + " not a system app!");
2901            }
2902
2903            if (ps.frozen) {
2904                throw new SecurityException("Package " + packageName + " is currently frozen!");
2905            }
2906
2907            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2908                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2909                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2910            }
2911        }
2912    }
2913
2914    @Override
2915    public boolean isPackageAvailable(String packageName, int userId) {
2916        if (!sUserManager.exists(userId)) return false;
2917        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2918        synchronized (mPackages) {
2919            PackageParser.Package p = mPackages.get(packageName);
2920            if (p != null) {
2921                final PackageSetting ps = (PackageSetting) p.mExtras;
2922                if (ps != null) {
2923                    final PackageUserState state = ps.readUserState(userId);
2924                    if (state != null) {
2925                        return PackageParser.isAvailable(state);
2926                    }
2927                }
2928            }
2929        }
2930        return false;
2931    }
2932
2933    @Override
2934    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2935        if (!sUserManager.exists(userId)) return null;
2936        flags = updateFlagsForPackage(flags, userId, packageName);
2937        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2938        // reader
2939        synchronized (mPackages) {
2940            PackageParser.Package p = mPackages.get(packageName);
2941            if (DEBUG_PACKAGE_INFO)
2942                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2943            if (p != null) {
2944                return generatePackageInfo(p, flags, userId);
2945            }
2946            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2947                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2948            }
2949        }
2950        return null;
2951    }
2952
2953    @Override
2954    public String[] currentToCanonicalPackageNames(String[] names) {
2955        String[] out = new String[names.length];
2956        // reader
2957        synchronized (mPackages) {
2958            for (int i=names.length-1; i>=0; i--) {
2959                PackageSetting ps = mSettings.mPackages.get(names[i]);
2960                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2961            }
2962        }
2963        return out;
2964    }
2965
2966    @Override
2967    public String[] canonicalToCurrentPackageNames(String[] names) {
2968        String[] out = new String[names.length];
2969        // reader
2970        synchronized (mPackages) {
2971            for (int i=names.length-1; i>=0; i--) {
2972                String cur = mSettings.mRenamedPackages.get(names[i]);
2973                out[i] = cur != null ? cur : names[i];
2974            }
2975        }
2976        return out;
2977    }
2978
2979    @Override
2980    public int getPackageUid(String packageName, int flags, int userId) {
2981        if (!sUserManager.exists(userId)) return -1;
2982        flags = updateFlagsForPackage(flags, userId, packageName);
2983        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2984
2985        // reader
2986        synchronized (mPackages) {
2987            final PackageParser.Package p = mPackages.get(packageName);
2988            if (p != null && p.isMatch(flags)) {
2989                return UserHandle.getUid(userId, p.applicationInfo.uid);
2990            }
2991            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2992                final PackageSetting ps = mSettings.mPackages.get(packageName);
2993                if (ps != null && ps.isMatch(flags)) {
2994                    return UserHandle.getUid(userId, ps.appId);
2995                }
2996            }
2997        }
2998
2999        return -1;
3000    }
3001
3002    @Override
3003    public int[] getPackageGids(String packageName, int flags, int userId) {
3004        if (!sUserManager.exists(userId)) return null;
3005        flags = updateFlagsForPackage(flags, userId, packageName);
3006        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3007                "getPackageGids");
3008
3009        // reader
3010        synchronized (mPackages) {
3011            final PackageParser.Package p = mPackages.get(packageName);
3012            if (p != null && p.isMatch(flags)) {
3013                PackageSetting ps = (PackageSetting) p.mExtras;
3014                return ps.getPermissionsState().computeGids(userId);
3015            }
3016            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3017                final PackageSetting ps = mSettings.mPackages.get(packageName);
3018                if (ps != null && ps.isMatch(flags)) {
3019                    return ps.getPermissionsState().computeGids(userId);
3020                }
3021            }
3022        }
3023
3024        return null;
3025    }
3026
3027    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3028        if (bp.perm != null) {
3029            return PackageParser.generatePermissionInfo(bp.perm, flags);
3030        }
3031        PermissionInfo pi = new PermissionInfo();
3032        pi.name = bp.name;
3033        pi.packageName = bp.sourcePackage;
3034        pi.nonLocalizedLabel = bp.name;
3035        pi.protectionLevel = bp.protectionLevel;
3036        return pi;
3037    }
3038
3039    @Override
3040    public PermissionInfo getPermissionInfo(String name, int flags) {
3041        // reader
3042        synchronized (mPackages) {
3043            final BasePermission p = mSettings.mPermissions.get(name);
3044            if (p != null) {
3045                return generatePermissionInfo(p, flags);
3046            }
3047            return null;
3048        }
3049    }
3050
3051    @Override
3052    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
3053        // reader
3054        synchronized (mPackages) {
3055            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3056            for (BasePermission p : mSettings.mPermissions.values()) {
3057                if (group == null) {
3058                    if (p.perm == null || p.perm.info.group == null) {
3059                        out.add(generatePermissionInfo(p, flags));
3060                    }
3061                } else {
3062                    if (p.perm != null && group.equals(p.perm.info.group)) {
3063                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3064                    }
3065                }
3066            }
3067
3068            if (out.size() > 0) {
3069                return out;
3070            }
3071            return mPermissionGroups.containsKey(group) ? out : null;
3072        }
3073    }
3074
3075    @Override
3076    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3077        // reader
3078        synchronized (mPackages) {
3079            return PackageParser.generatePermissionGroupInfo(
3080                    mPermissionGroups.get(name), flags);
3081        }
3082    }
3083
3084    @Override
3085    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3086        // reader
3087        synchronized (mPackages) {
3088            final int N = mPermissionGroups.size();
3089            ArrayList<PermissionGroupInfo> out
3090                    = new ArrayList<PermissionGroupInfo>(N);
3091            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3092                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3093            }
3094            return out;
3095        }
3096    }
3097
3098    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3099            int userId) {
3100        if (!sUserManager.exists(userId)) return null;
3101        PackageSetting ps = mSettings.mPackages.get(packageName);
3102        if (ps != null) {
3103            if (ps.pkg == null) {
3104                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3105                        flags, userId);
3106                if (pInfo != null) {
3107                    return pInfo.applicationInfo;
3108                }
3109                return null;
3110            }
3111            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3112                    ps.readUserState(userId), userId);
3113        }
3114        return null;
3115    }
3116
3117    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3118            int userId) {
3119        if (!sUserManager.exists(userId)) return null;
3120        PackageSetting ps = mSettings.mPackages.get(packageName);
3121        if (ps != null) {
3122            PackageParser.Package pkg = ps.pkg;
3123            if (pkg == null) {
3124                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3125                    return null;
3126                }
3127                // Only data remains, so we aren't worried about code paths
3128                pkg = new PackageParser.Package(packageName);
3129                pkg.applicationInfo.packageName = packageName;
3130                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3131                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3132                pkg.applicationInfo.uid = ps.appId;
3133                pkg.applicationInfo.initForUser(userId);
3134                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3135                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3136            }
3137            return generatePackageInfo(pkg, flags, userId);
3138        }
3139        return null;
3140    }
3141
3142    @Override
3143    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3144        if (!sUserManager.exists(userId)) return null;
3145        flags = updateFlagsForApplication(flags, userId, packageName);
3146        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3147        // writer
3148        synchronized (mPackages) {
3149            PackageParser.Package p = mPackages.get(packageName);
3150            if (DEBUG_PACKAGE_INFO) Log.v(
3151                    TAG, "getApplicationInfo " + packageName
3152                    + ": " + p);
3153            if (p != null) {
3154                PackageSetting ps = mSettings.mPackages.get(packageName);
3155                if (ps == null) return null;
3156                // Note: isEnabledLP() does not apply here - always return info
3157                return PackageParser.generateApplicationInfo(
3158                        p, flags, ps.readUserState(userId), userId);
3159            }
3160            if ("android".equals(packageName)||"system".equals(packageName)) {
3161                return mAndroidApplication;
3162            }
3163            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3164                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3165            }
3166        }
3167        return null;
3168    }
3169
3170    @Override
3171    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3172            final IPackageDataObserver observer) {
3173        mContext.enforceCallingOrSelfPermission(
3174                android.Manifest.permission.CLEAR_APP_CACHE, null);
3175        // Queue up an async operation since clearing cache may take a little while.
3176        mHandler.post(new Runnable() {
3177            public void run() {
3178                mHandler.removeCallbacks(this);
3179                boolean success = true;
3180                synchronized (mInstallLock) {
3181                    try {
3182                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3183                    } catch (InstallerException e) {
3184                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3185                        success = false;
3186                    }
3187                }
3188                if (observer != null) {
3189                    try {
3190                        observer.onRemoveCompleted(null, success);
3191                    } catch (RemoteException e) {
3192                        Slog.w(TAG, "RemoveException when invoking call back");
3193                    }
3194                }
3195            }
3196        });
3197    }
3198
3199    @Override
3200    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3201            final IntentSender pi) {
3202        mContext.enforceCallingOrSelfPermission(
3203                android.Manifest.permission.CLEAR_APP_CACHE, null);
3204        // Queue up an async operation since clearing cache may take a little while.
3205        mHandler.post(new Runnable() {
3206            public void run() {
3207                mHandler.removeCallbacks(this);
3208                boolean success = true;
3209                synchronized (mInstallLock) {
3210                    try {
3211                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3212                    } catch (InstallerException e) {
3213                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3214                        success = false;
3215                    }
3216                }
3217                if(pi != null) {
3218                    try {
3219                        // Callback via pending intent
3220                        int code = success ? 1 : 0;
3221                        pi.sendIntent(null, code, null,
3222                                null, null);
3223                    } catch (SendIntentException e1) {
3224                        Slog.i(TAG, "Failed to send pending intent");
3225                    }
3226                }
3227            }
3228        });
3229    }
3230
3231    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3232        synchronized (mInstallLock) {
3233            try {
3234                mInstaller.freeCache(volumeUuid, freeStorageSize);
3235            } catch (InstallerException e) {
3236                throw new IOException("Failed to free enough space", e);
3237            }
3238        }
3239    }
3240
3241    /**
3242     * Return if the user key is currently unlocked.
3243     */
3244    private boolean isUserKeyUnlocked(int userId) {
3245        if (StorageManager.isFileBasedEncryptionEnabled()) {
3246            final IMountService mount = IMountService.Stub
3247                    .asInterface(ServiceManager.getService("mount"));
3248            if (mount == null) {
3249                Slog.w(TAG, "Early during boot, assuming locked");
3250                return false;
3251            }
3252            final long token = Binder.clearCallingIdentity();
3253            try {
3254                return mount.isUserKeyUnlocked(userId);
3255            } catch (RemoteException e) {
3256                throw e.rethrowAsRuntimeException();
3257            } finally {
3258                Binder.restoreCallingIdentity(token);
3259            }
3260        } else {
3261            return true;
3262        }
3263    }
3264
3265    /**
3266     * Update given flags based on encryption status of current user.
3267     */
3268    private int updateFlags(int flags, int userId) {
3269        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3270                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3271            // Caller expressed an explicit opinion about what encryption
3272            // aware/unaware components they want to see, so fall through and
3273            // give them what they want
3274        } else {
3275            // Caller expressed no opinion, so match based on user state
3276            if (isUserKeyUnlocked(userId)) {
3277                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3278            } else {
3279                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3280            }
3281        }
3282        return flags;
3283    }
3284
3285    /**
3286     * Update given flags when being used to request {@link PackageInfo}.
3287     */
3288    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3289        boolean triaged = true;
3290        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3291                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3292            // Caller is asking for component details, so they'd better be
3293            // asking for specific encryption matching behavior, or be triaged
3294            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3295                    | PackageManager.MATCH_ENCRYPTION_AWARE
3296                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3297                triaged = false;
3298            }
3299        }
3300        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3301                | PackageManager.MATCH_SYSTEM_ONLY
3302                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3303            triaged = false;
3304        }
3305        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3306            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3307                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3308        }
3309        return updateFlags(flags, userId);
3310    }
3311
3312    /**
3313     * Update given flags when being used to request {@link ApplicationInfo}.
3314     */
3315    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3316        return updateFlagsForPackage(flags, userId, cookie);
3317    }
3318
3319    /**
3320     * Update given flags when being used to request {@link ComponentInfo}.
3321     */
3322    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3323        if (cookie instanceof Intent) {
3324            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3325                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3326            }
3327        }
3328
3329        boolean triaged = true;
3330        // Caller is asking for component details, so they'd better be
3331        // asking for specific encryption matching behavior, or be triaged
3332        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3333                | PackageManager.MATCH_ENCRYPTION_AWARE
3334                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3335            triaged = false;
3336        }
3337        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3338            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3339                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3340        }
3341
3342        // Safe mode means we shouldn't match any third-party components
3343        if (mSafeMode) {
3344            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3345        }
3346
3347        return updateFlags(flags, userId);
3348    }
3349
3350    /**
3351     * Update given flags when being used to request {@link ResolveInfo}.
3352     */
3353    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3354        return updateFlagsForComponent(flags, userId, cookie);
3355    }
3356
3357    @Override
3358    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3359        if (!sUserManager.exists(userId)) return null;
3360        flags = updateFlagsForComponent(flags, userId, component);
3361        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3362        synchronized (mPackages) {
3363            PackageParser.Activity a = mActivities.mActivities.get(component);
3364
3365            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3366            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3367                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3368                if (ps == null) return null;
3369                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3370                        userId);
3371            }
3372            if (mResolveComponentName.equals(component)) {
3373                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3374                        new PackageUserState(), userId);
3375            }
3376        }
3377        return null;
3378    }
3379
3380    @Override
3381    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3382            String resolvedType) {
3383        synchronized (mPackages) {
3384            if (component.equals(mResolveComponentName)) {
3385                // The resolver supports EVERYTHING!
3386                return true;
3387            }
3388            PackageParser.Activity a = mActivities.mActivities.get(component);
3389            if (a == null) {
3390                return false;
3391            }
3392            for (int i=0; i<a.intents.size(); i++) {
3393                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3394                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3395                    return true;
3396                }
3397            }
3398            return false;
3399        }
3400    }
3401
3402    @Override
3403    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3404        if (!sUserManager.exists(userId)) return null;
3405        flags = updateFlagsForComponent(flags, userId, component);
3406        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3407        synchronized (mPackages) {
3408            PackageParser.Activity a = mReceivers.mActivities.get(component);
3409            if (DEBUG_PACKAGE_INFO) Log.v(
3410                TAG, "getReceiverInfo " + component + ": " + a);
3411            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3412                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3413                if (ps == null) return null;
3414                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3415                        userId);
3416            }
3417        }
3418        return null;
3419    }
3420
3421    @Override
3422    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3423        if (!sUserManager.exists(userId)) return null;
3424        flags = updateFlagsForComponent(flags, userId, component);
3425        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3426        synchronized (mPackages) {
3427            PackageParser.Service s = mServices.mServices.get(component);
3428            if (DEBUG_PACKAGE_INFO) Log.v(
3429                TAG, "getServiceInfo " + component + ": " + s);
3430            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3431                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3432                if (ps == null) return null;
3433                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3434                        userId);
3435            }
3436        }
3437        return null;
3438    }
3439
3440    @Override
3441    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3442        if (!sUserManager.exists(userId)) return null;
3443        flags = updateFlagsForComponent(flags, userId, component);
3444        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3445        synchronized (mPackages) {
3446            PackageParser.Provider p = mProviders.mProviders.get(component);
3447            if (DEBUG_PACKAGE_INFO) Log.v(
3448                TAG, "getProviderInfo " + component + ": " + p);
3449            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3450                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3451                if (ps == null) return null;
3452                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3453                        userId);
3454            }
3455        }
3456        return null;
3457    }
3458
3459    @Override
3460    public String[] getSystemSharedLibraryNames() {
3461        Set<String> libSet;
3462        synchronized (mPackages) {
3463            libSet = mSharedLibraries.keySet();
3464            int size = libSet.size();
3465            if (size > 0) {
3466                String[] libs = new String[size];
3467                libSet.toArray(libs);
3468                return libs;
3469            }
3470        }
3471        return null;
3472    }
3473
3474    @Override
3475    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3476        synchronized (mPackages) {
3477            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3478                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3479            if (libraryEntry != null) {
3480                return libraryEntry.apk;
3481            }
3482        }
3483        return null;
3484    }
3485
3486    @Override
3487    public FeatureInfo[] getSystemAvailableFeatures() {
3488        Collection<FeatureInfo> featSet;
3489        synchronized (mPackages) {
3490            featSet = mAvailableFeatures.values();
3491            int size = featSet.size();
3492            if (size > 0) {
3493                FeatureInfo[] features = new FeatureInfo[size+1];
3494                featSet.toArray(features);
3495                FeatureInfo fi = new FeatureInfo();
3496                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3497                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3498                features[size] = fi;
3499                return features;
3500            }
3501        }
3502        return null;
3503    }
3504
3505    @Override
3506    public boolean hasSystemFeature(String name, int version) {
3507        synchronized (mPackages) {
3508            final FeatureInfo feat = mAvailableFeatures.get(name);
3509            if (feat == null) {
3510                return false;
3511            } else {
3512                return feat.version >= version;
3513            }
3514        }
3515    }
3516
3517    @Override
3518    public int checkPermission(String permName, String pkgName, int userId) {
3519        if (!sUserManager.exists(userId)) {
3520            return PackageManager.PERMISSION_DENIED;
3521        }
3522
3523        synchronized (mPackages) {
3524            final PackageParser.Package p = mPackages.get(pkgName);
3525            if (p != null && p.mExtras != null) {
3526                final PackageSetting ps = (PackageSetting) p.mExtras;
3527                final PermissionsState permissionsState = ps.getPermissionsState();
3528                if (permissionsState.hasPermission(permName, userId)) {
3529                    return PackageManager.PERMISSION_GRANTED;
3530                }
3531                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3532                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3533                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3534                    return PackageManager.PERMISSION_GRANTED;
3535                }
3536            }
3537        }
3538
3539        return PackageManager.PERMISSION_DENIED;
3540    }
3541
3542    @Override
3543    public int checkUidPermission(String permName, int uid) {
3544        final int userId = UserHandle.getUserId(uid);
3545
3546        if (!sUserManager.exists(userId)) {
3547            return PackageManager.PERMISSION_DENIED;
3548        }
3549
3550        synchronized (mPackages) {
3551            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3552            if (obj != null) {
3553                final SettingBase ps = (SettingBase) obj;
3554                final PermissionsState permissionsState = ps.getPermissionsState();
3555                if (permissionsState.hasPermission(permName, userId)) {
3556                    return PackageManager.PERMISSION_GRANTED;
3557                }
3558                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3559                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3560                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3561                    return PackageManager.PERMISSION_GRANTED;
3562                }
3563            } else {
3564                ArraySet<String> perms = mSystemPermissions.get(uid);
3565                if (perms != null) {
3566                    if (perms.contains(permName)) {
3567                        return PackageManager.PERMISSION_GRANTED;
3568                    }
3569                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3570                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3571                        return PackageManager.PERMISSION_GRANTED;
3572                    }
3573                }
3574            }
3575        }
3576
3577        return PackageManager.PERMISSION_DENIED;
3578    }
3579
3580    @Override
3581    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3582        if (UserHandle.getCallingUserId() != userId) {
3583            mContext.enforceCallingPermission(
3584                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3585                    "isPermissionRevokedByPolicy for user " + userId);
3586        }
3587
3588        if (checkPermission(permission, packageName, userId)
3589                == PackageManager.PERMISSION_GRANTED) {
3590            return false;
3591        }
3592
3593        final long identity = Binder.clearCallingIdentity();
3594        try {
3595            final int flags = getPermissionFlags(permission, packageName, userId);
3596            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3597        } finally {
3598            Binder.restoreCallingIdentity(identity);
3599        }
3600    }
3601
3602    @Override
3603    public String getPermissionControllerPackageName() {
3604        synchronized (mPackages) {
3605            return mRequiredInstallerPackage;
3606        }
3607    }
3608
3609    /**
3610     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3611     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3612     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3613     * @param message the message to log on security exception
3614     */
3615    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3616            boolean checkShell, String message) {
3617        if (userId < 0) {
3618            throw new IllegalArgumentException("Invalid userId " + userId);
3619        }
3620        if (checkShell) {
3621            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3622        }
3623        if (userId == UserHandle.getUserId(callingUid)) return;
3624        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3625            if (requireFullPermission) {
3626                mContext.enforceCallingOrSelfPermission(
3627                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3628            } else {
3629                try {
3630                    mContext.enforceCallingOrSelfPermission(
3631                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3632                } catch (SecurityException se) {
3633                    mContext.enforceCallingOrSelfPermission(
3634                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3635                }
3636            }
3637        }
3638    }
3639
3640    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3641        if (callingUid == Process.SHELL_UID) {
3642            if (userHandle >= 0
3643                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3644                throw new SecurityException("Shell does not have permission to access user "
3645                        + userHandle);
3646            } else if (userHandle < 0) {
3647                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3648                        + Debug.getCallers(3));
3649            }
3650        }
3651    }
3652
3653    private BasePermission findPermissionTreeLP(String permName) {
3654        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3655            if (permName.startsWith(bp.name) &&
3656                    permName.length() > bp.name.length() &&
3657                    permName.charAt(bp.name.length()) == '.') {
3658                return bp;
3659            }
3660        }
3661        return null;
3662    }
3663
3664    private BasePermission checkPermissionTreeLP(String permName) {
3665        if (permName != null) {
3666            BasePermission bp = findPermissionTreeLP(permName);
3667            if (bp != null) {
3668                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3669                    return bp;
3670                }
3671                throw new SecurityException("Calling uid "
3672                        + Binder.getCallingUid()
3673                        + " is not allowed to add to permission tree "
3674                        + bp.name + " owned by uid " + bp.uid);
3675            }
3676        }
3677        throw new SecurityException("No permission tree found for " + permName);
3678    }
3679
3680    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3681        if (s1 == null) {
3682            return s2 == null;
3683        }
3684        if (s2 == null) {
3685            return false;
3686        }
3687        if (s1.getClass() != s2.getClass()) {
3688            return false;
3689        }
3690        return s1.equals(s2);
3691    }
3692
3693    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3694        if (pi1.icon != pi2.icon) return false;
3695        if (pi1.logo != pi2.logo) return false;
3696        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3697        if (!compareStrings(pi1.name, pi2.name)) return false;
3698        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3699        // We'll take care of setting this one.
3700        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3701        // These are not currently stored in settings.
3702        //if (!compareStrings(pi1.group, pi2.group)) return false;
3703        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3704        //if (pi1.labelRes != pi2.labelRes) return false;
3705        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3706        return true;
3707    }
3708
3709    int permissionInfoFootprint(PermissionInfo info) {
3710        int size = info.name.length();
3711        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3712        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3713        return size;
3714    }
3715
3716    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3717        int size = 0;
3718        for (BasePermission perm : mSettings.mPermissions.values()) {
3719            if (perm.uid == tree.uid) {
3720                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3721            }
3722        }
3723        return size;
3724    }
3725
3726    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3727        // We calculate the max size of permissions defined by this uid and throw
3728        // if that plus the size of 'info' would exceed our stated maximum.
3729        if (tree.uid != Process.SYSTEM_UID) {
3730            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3731            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3732                throw new SecurityException("Permission tree size cap exceeded");
3733            }
3734        }
3735    }
3736
3737    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3738        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3739            throw new SecurityException("Label must be specified in permission");
3740        }
3741        BasePermission tree = checkPermissionTreeLP(info.name);
3742        BasePermission bp = mSettings.mPermissions.get(info.name);
3743        boolean added = bp == null;
3744        boolean changed = true;
3745        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3746        if (added) {
3747            enforcePermissionCapLocked(info, tree);
3748            bp = new BasePermission(info.name, tree.sourcePackage,
3749                    BasePermission.TYPE_DYNAMIC);
3750        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3751            throw new SecurityException(
3752                    "Not allowed to modify non-dynamic permission "
3753                    + info.name);
3754        } else {
3755            if (bp.protectionLevel == fixedLevel
3756                    && bp.perm.owner.equals(tree.perm.owner)
3757                    && bp.uid == tree.uid
3758                    && comparePermissionInfos(bp.perm.info, info)) {
3759                changed = false;
3760            }
3761        }
3762        bp.protectionLevel = fixedLevel;
3763        info = new PermissionInfo(info);
3764        info.protectionLevel = fixedLevel;
3765        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3766        bp.perm.info.packageName = tree.perm.info.packageName;
3767        bp.uid = tree.uid;
3768        if (added) {
3769            mSettings.mPermissions.put(info.name, bp);
3770        }
3771        if (changed) {
3772            if (!async) {
3773                mSettings.writeLPr();
3774            } else {
3775                scheduleWriteSettingsLocked();
3776            }
3777        }
3778        return added;
3779    }
3780
3781    @Override
3782    public boolean addPermission(PermissionInfo info) {
3783        synchronized (mPackages) {
3784            return addPermissionLocked(info, false);
3785        }
3786    }
3787
3788    @Override
3789    public boolean addPermissionAsync(PermissionInfo info) {
3790        synchronized (mPackages) {
3791            return addPermissionLocked(info, true);
3792        }
3793    }
3794
3795    @Override
3796    public void removePermission(String name) {
3797        synchronized (mPackages) {
3798            checkPermissionTreeLP(name);
3799            BasePermission bp = mSettings.mPermissions.get(name);
3800            if (bp != null) {
3801                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3802                    throw new SecurityException(
3803                            "Not allowed to modify non-dynamic permission "
3804                            + name);
3805                }
3806                mSettings.mPermissions.remove(name);
3807                mSettings.writeLPr();
3808            }
3809        }
3810    }
3811
3812    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3813            BasePermission bp) {
3814        int index = pkg.requestedPermissions.indexOf(bp.name);
3815        if (index == -1) {
3816            throw new SecurityException("Package " + pkg.packageName
3817                    + " has not requested permission " + bp.name);
3818        }
3819        if (!bp.isRuntime() && !bp.isDevelopment()) {
3820            throw new SecurityException("Permission " + bp.name
3821                    + " is not a changeable permission type");
3822        }
3823    }
3824
3825    @Override
3826    public void grantRuntimePermission(String packageName, String name, final int userId) {
3827        if (!sUserManager.exists(userId)) {
3828            Log.e(TAG, "No such user:" + userId);
3829            return;
3830        }
3831
3832        mContext.enforceCallingOrSelfPermission(
3833                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3834                "grantRuntimePermission");
3835
3836        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3837                "grantRuntimePermission");
3838
3839        final int uid;
3840        final SettingBase sb;
3841
3842        synchronized (mPackages) {
3843            final PackageParser.Package pkg = mPackages.get(packageName);
3844            if (pkg == null) {
3845                throw new IllegalArgumentException("Unknown package: " + packageName);
3846            }
3847
3848            final BasePermission bp = mSettings.mPermissions.get(name);
3849            if (bp == null) {
3850                throw new IllegalArgumentException("Unknown permission: " + name);
3851            }
3852
3853            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3854
3855            // If a permission review is required for legacy apps we represent
3856            // their permissions as always granted runtime ones since we need
3857            // to keep the review required permission flag per user while an
3858            // install permission's state is shared across all users.
3859            if (Build.PERMISSIONS_REVIEW_REQUIRED
3860                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3861                    && bp.isRuntime()) {
3862                return;
3863            }
3864
3865            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3866            sb = (SettingBase) pkg.mExtras;
3867            if (sb == null) {
3868                throw new IllegalArgumentException("Unknown package: " + packageName);
3869            }
3870
3871            final PermissionsState permissionsState = sb.getPermissionsState();
3872
3873            final int flags = permissionsState.getPermissionFlags(name, userId);
3874            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3875                throw new SecurityException("Cannot grant system fixed permission "
3876                        + name + " for package " + packageName);
3877            }
3878
3879            if (bp.isDevelopment()) {
3880                // Development permissions must be handled specially, since they are not
3881                // normal runtime permissions.  For now they apply to all users.
3882                if (permissionsState.grantInstallPermission(bp) !=
3883                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3884                    scheduleWriteSettingsLocked();
3885                }
3886                return;
3887            }
3888
3889            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3890                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3891                return;
3892            }
3893
3894            final int result = permissionsState.grantRuntimePermission(bp, userId);
3895            switch (result) {
3896                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3897                    return;
3898                }
3899
3900                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3901                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3902                    mHandler.post(new Runnable() {
3903                        @Override
3904                        public void run() {
3905                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3906                        }
3907                    });
3908                }
3909                break;
3910            }
3911
3912            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3913
3914            // Not critical if that is lost - app has to request again.
3915            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3916        }
3917
3918        // Only need to do this if user is initialized. Otherwise it's a new user
3919        // and there are no processes running as the user yet and there's no need
3920        // to make an expensive call to remount processes for the changed permissions.
3921        if (READ_EXTERNAL_STORAGE.equals(name)
3922                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3923            final long token = Binder.clearCallingIdentity();
3924            try {
3925                if (sUserManager.isInitialized(userId)) {
3926                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3927                            MountServiceInternal.class);
3928                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3929                }
3930            } finally {
3931                Binder.restoreCallingIdentity(token);
3932            }
3933        }
3934    }
3935
3936    @Override
3937    public void revokeRuntimePermission(String packageName, String name, int userId) {
3938        if (!sUserManager.exists(userId)) {
3939            Log.e(TAG, "No such user:" + userId);
3940            return;
3941        }
3942
3943        mContext.enforceCallingOrSelfPermission(
3944                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3945                "revokeRuntimePermission");
3946
3947        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3948                "revokeRuntimePermission");
3949
3950        final int appId;
3951
3952        synchronized (mPackages) {
3953            final PackageParser.Package pkg = mPackages.get(packageName);
3954            if (pkg == null) {
3955                throw new IllegalArgumentException("Unknown package: " + packageName);
3956            }
3957
3958            final BasePermission bp = mSettings.mPermissions.get(name);
3959            if (bp == null) {
3960                throw new IllegalArgumentException("Unknown permission: " + name);
3961            }
3962
3963            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3964
3965            // If a permission review is required for legacy apps we represent
3966            // their permissions as always granted runtime ones since we need
3967            // to keep the review required permission flag per user while an
3968            // install permission's state is shared across all users.
3969            if (Build.PERMISSIONS_REVIEW_REQUIRED
3970                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3971                    && bp.isRuntime()) {
3972                return;
3973            }
3974
3975            SettingBase sb = (SettingBase) pkg.mExtras;
3976            if (sb == null) {
3977                throw new IllegalArgumentException("Unknown package: " + packageName);
3978            }
3979
3980            final PermissionsState permissionsState = sb.getPermissionsState();
3981
3982            final int flags = permissionsState.getPermissionFlags(name, userId);
3983            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3984                throw new SecurityException("Cannot revoke system fixed permission "
3985                        + name + " for package " + packageName);
3986            }
3987
3988            if (bp.isDevelopment()) {
3989                // Development permissions must be handled specially, since they are not
3990                // normal runtime permissions.  For now they apply to all users.
3991                if (permissionsState.revokeInstallPermission(bp) !=
3992                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3993                    scheduleWriteSettingsLocked();
3994                }
3995                return;
3996            }
3997
3998            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3999                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4000                return;
4001            }
4002
4003            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4004
4005            // Critical, after this call app should never have the permission.
4006            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4007
4008            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4009        }
4010
4011        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4012    }
4013
4014    @Override
4015    public void resetRuntimePermissions() {
4016        mContext.enforceCallingOrSelfPermission(
4017                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4018                "revokeRuntimePermission");
4019
4020        int callingUid = Binder.getCallingUid();
4021        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4022            mContext.enforceCallingOrSelfPermission(
4023                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4024                    "resetRuntimePermissions");
4025        }
4026
4027        synchronized (mPackages) {
4028            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4029            for (int userId : UserManagerService.getInstance().getUserIds()) {
4030                final int packageCount = mPackages.size();
4031                for (int i = 0; i < packageCount; i++) {
4032                    PackageParser.Package pkg = mPackages.valueAt(i);
4033                    if (!(pkg.mExtras instanceof PackageSetting)) {
4034                        continue;
4035                    }
4036                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4037                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4038                }
4039            }
4040        }
4041    }
4042
4043    @Override
4044    public int getPermissionFlags(String name, String packageName, int userId) {
4045        if (!sUserManager.exists(userId)) {
4046            return 0;
4047        }
4048
4049        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4050
4051        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4052                "getPermissionFlags");
4053
4054        synchronized (mPackages) {
4055            final PackageParser.Package pkg = mPackages.get(packageName);
4056            if (pkg == null) {
4057                throw new IllegalArgumentException("Unknown package: " + packageName);
4058            }
4059
4060            final BasePermission bp = mSettings.mPermissions.get(name);
4061            if (bp == null) {
4062                throw new IllegalArgumentException("Unknown permission: " + name);
4063            }
4064
4065            SettingBase sb = (SettingBase) pkg.mExtras;
4066            if (sb == null) {
4067                throw new IllegalArgumentException("Unknown package: " + packageName);
4068            }
4069
4070            PermissionsState permissionsState = sb.getPermissionsState();
4071            return permissionsState.getPermissionFlags(name, userId);
4072        }
4073    }
4074
4075    @Override
4076    public void updatePermissionFlags(String name, String packageName, int flagMask,
4077            int flagValues, int userId) {
4078        if (!sUserManager.exists(userId)) {
4079            return;
4080        }
4081
4082        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4083
4084        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4085                "updatePermissionFlags");
4086
4087        // Only the system can change these flags and nothing else.
4088        if (getCallingUid() != Process.SYSTEM_UID) {
4089            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4090            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4091            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4092            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4093            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4094        }
4095
4096        synchronized (mPackages) {
4097            final PackageParser.Package pkg = mPackages.get(packageName);
4098            if (pkg == null) {
4099                throw new IllegalArgumentException("Unknown package: " + packageName);
4100            }
4101
4102            final BasePermission bp = mSettings.mPermissions.get(name);
4103            if (bp == null) {
4104                throw new IllegalArgumentException("Unknown permission: " + name);
4105            }
4106
4107            SettingBase sb = (SettingBase) pkg.mExtras;
4108            if (sb == null) {
4109                throw new IllegalArgumentException("Unknown package: " + packageName);
4110            }
4111
4112            PermissionsState permissionsState = sb.getPermissionsState();
4113
4114            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4115
4116            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4117                // Install and runtime permissions are stored in different places,
4118                // so figure out what permission changed and persist the change.
4119                if (permissionsState.getInstallPermissionState(name) != null) {
4120                    scheduleWriteSettingsLocked();
4121                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4122                        || hadState) {
4123                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4124                }
4125            }
4126        }
4127    }
4128
4129    /**
4130     * Update the permission flags for all packages and runtime permissions of a user in order
4131     * to allow device or profile owner to remove POLICY_FIXED.
4132     */
4133    @Override
4134    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4135        if (!sUserManager.exists(userId)) {
4136            return;
4137        }
4138
4139        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4140
4141        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4142                "updatePermissionFlagsForAllApps");
4143
4144        // Only the system can change system fixed flags.
4145        if (getCallingUid() != Process.SYSTEM_UID) {
4146            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4147            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4148        }
4149
4150        synchronized (mPackages) {
4151            boolean changed = false;
4152            final int packageCount = mPackages.size();
4153            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4154                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4155                SettingBase sb = (SettingBase) pkg.mExtras;
4156                if (sb == null) {
4157                    continue;
4158                }
4159                PermissionsState permissionsState = sb.getPermissionsState();
4160                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4161                        userId, flagMask, flagValues);
4162            }
4163            if (changed) {
4164                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4165            }
4166        }
4167    }
4168
4169    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4170        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4171                != PackageManager.PERMISSION_GRANTED
4172            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4173                != PackageManager.PERMISSION_GRANTED) {
4174            throw new SecurityException(message + " requires "
4175                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4176                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4177        }
4178    }
4179
4180    @Override
4181    public boolean shouldShowRequestPermissionRationale(String permissionName,
4182            String packageName, int userId) {
4183        if (UserHandle.getCallingUserId() != userId) {
4184            mContext.enforceCallingPermission(
4185                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4186                    "canShowRequestPermissionRationale for user " + userId);
4187        }
4188
4189        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4190        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4191            return false;
4192        }
4193
4194        if (checkPermission(permissionName, packageName, userId)
4195                == PackageManager.PERMISSION_GRANTED) {
4196            return false;
4197        }
4198
4199        final int flags;
4200
4201        final long identity = Binder.clearCallingIdentity();
4202        try {
4203            flags = getPermissionFlags(permissionName,
4204                    packageName, userId);
4205        } finally {
4206            Binder.restoreCallingIdentity(identity);
4207        }
4208
4209        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4210                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4211                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4212
4213        if ((flags & fixedFlags) != 0) {
4214            return false;
4215        }
4216
4217        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4218    }
4219
4220    @Override
4221    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4222        mContext.enforceCallingOrSelfPermission(
4223                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4224                "addOnPermissionsChangeListener");
4225
4226        synchronized (mPackages) {
4227            mOnPermissionChangeListeners.addListenerLocked(listener);
4228        }
4229    }
4230
4231    @Override
4232    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4233        synchronized (mPackages) {
4234            mOnPermissionChangeListeners.removeListenerLocked(listener);
4235        }
4236    }
4237
4238    @Override
4239    public boolean isProtectedBroadcast(String actionName) {
4240        synchronized (mPackages) {
4241            if (mProtectedBroadcasts.contains(actionName)) {
4242                return true;
4243            } else if (actionName != null) {
4244                // TODO: remove these terrible hacks
4245                if (actionName.startsWith("android.net.netmon.lingerExpired")
4246                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4247                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")) {
4248                    return true;
4249                }
4250            }
4251        }
4252        return false;
4253    }
4254
4255    @Override
4256    public int checkSignatures(String pkg1, String pkg2) {
4257        synchronized (mPackages) {
4258            final PackageParser.Package p1 = mPackages.get(pkg1);
4259            final PackageParser.Package p2 = mPackages.get(pkg2);
4260            if (p1 == null || p1.mExtras == null
4261                    || p2 == null || p2.mExtras == null) {
4262                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4263            }
4264            return compareSignatures(p1.mSignatures, p2.mSignatures);
4265        }
4266    }
4267
4268    @Override
4269    public int checkUidSignatures(int uid1, int uid2) {
4270        // Map to base uids.
4271        uid1 = UserHandle.getAppId(uid1);
4272        uid2 = UserHandle.getAppId(uid2);
4273        // reader
4274        synchronized (mPackages) {
4275            Signature[] s1;
4276            Signature[] s2;
4277            Object obj = mSettings.getUserIdLPr(uid1);
4278            if (obj != null) {
4279                if (obj instanceof SharedUserSetting) {
4280                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4281                } else if (obj instanceof PackageSetting) {
4282                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4283                } else {
4284                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4285                }
4286            } else {
4287                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4288            }
4289            obj = mSettings.getUserIdLPr(uid2);
4290            if (obj != null) {
4291                if (obj instanceof SharedUserSetting) {
4292                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4293                } else if (obj instanceof PackageSetting) {
4294                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4295                } else {
4296                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4297                }
4298            } else {
4299                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4300            }
4301            return compareSignatures(s1, s2);
4302        }
4303    }
4304
4305    private void killUid(int appId, int userId, String reason) {
4306        final long identity = Binder.clearCallingIdentity();
4307        try {
4308            IActivityManager am = ActivityManagerNative.getDefault();
4309            if (am != null) {
4310                try {
4311                    am.killUid(appId, userId, reason);
4312                } catch (RemoteException e) {
4313                    /* ignore - same process */
4314                }
4315            }
4316        } finally {
4317            Binder.restoreCallingIdentity(identity);
4318        }
4319    }
4320
4321    /**
4322     * Compares two sets of signatures. Returns:
4323     * <br />
4324     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4325     * <br />
4326     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4327     * <br />
4328     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4329     * <br />
4330     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4331     * <br />
4332     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4333     */
4334    static int compareSignatures(Signature[] s1, Signature[] s2) {
4335        if (s1 == null) {
4336            return s2 == null
4337                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4338                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4339        }
4340
4341        if (s2 == null) {
4342            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4343        }
4344
4345        if (s1.length != s2.length) {
4346            return PackageManager.SIGNATURE_NO_MATCH;
4347        }
4348
4349        // Since both signature sets are of size 1, we can compare without HashSets.
4350        if (s1.length == 1) {
4351            return s1[0].equals(s2[0]) ?
4352                    PackageManager.SIGNATURE_MATCH :
4353                    PackageManager.SIGNATURE_NO_MATCH;
4354        }
4355
4356        ArraySet<Signature> set1 = new ArraySet<Signature>();
4357        for (Signature sig : s1) {
4358            set1.add(sig);
4359        }
4360        ArraySet<Signature> set2 = new ArraySet<Signature>();
4361        for (Signature sig : s2) {
4362            set2.add(sig);
4363        }
4364        // Make sure s2 contains all signatures in s1.
4365        if (set1.equals(set2)) {
4366            return PackageManager.SIGNATURE_MATCH;
4367        }
4368        return PackageManager.SIGNATURE_NO_MATCH;
4369    }
4370
4371    /**
4372     * If the database version for this type of package (internal storage or
4373     * external storage) is less than the version where package signatures
4374     * were updated, return true.
4375     */
4376    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4377        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4378        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4379    }
4380
4381    /**
4382     * Used for backward compatibility to make sure any packages with
4383     * certificate chains get upgraded to the new style. {@code existingSigs}
4384     * will be in the old format (since they were stored on disk from before the
4385     * system upgrade) and {@code scannedSigs} will be in the newer format.
4386     */
4387    private int compareSignaturesCompat(PackageSignatures existingSigs,
4388            PackageParser.Package scannedPkg) {
4389        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4390            return PackageManager.SIGNATURE_NO_MATCH;
4391        }
4392
4393        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4394        for (Signature sig : existingSigs.mSignatures) {
4395            existingSet.add(sig);
4396        }
4397        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4398        for (Signature sig : scannedPkg.mSignatures) {
4399            try {
4400                Signature[] chainSignatures = sig.getChainSignatures();
4401                for (Signature chainSig : chainSignatures) {
4402                    scannedCompatSet.add(chainSig);
4403                }
4404            } catch (CertificateEncodingException e) {
4405                scannedCompatSet.add(sig);
4406            }
4407        }
4408        /*
4409         * Make sure the expanded scanned set contains all signatures in the
4410         * existing one.
4411         */
4412        if (scannedCompatSet.equals(existingSet)) {
4413            // Migrate the old signatures to the new scheme.
4414            existingSigs.assignSignatures(scannedPkg.mSignatures);
4415            // The new KeySets will be re-added later in the scanning process.
4416            synchronized (mPackages) {
4417                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4418            }
4419            return PackageManager.SIGNATURE_MATCH;
4420        }
4421        return PackageManager.SIGNATURE_NO_MATCH;
4422    }
4423
4424    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4425        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4426        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4427    }
4428
4429    private int compareSignaturesRecover(PackageSignatures existingSigs,
4430            PackageParser.Package scannedPkg) {
4431        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4432            return PackageManager.SIGNATURE_NO_MATCH;
4433        }
4434
4435        String msg = null;
4436        try {
4437            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4438                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4439                        + scannedPkg.packageName);
4440                return PackageManager.SIGNATURE_MATCH;
4441            }
4442        } catch (CertificateException e) {
4443            msg = e.getMessage();
4444        }
4445
4446        logCriticalInfo(Log.INFO,
4447                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4448        return PackageManager.SIGNATURE_NO_MATCH;
4449    }
4450
4451    @Override
4452    public String[] getPackagesForUid(int uid) {
4453        uid = UserHandle.getAppId(uid);
4454        // reader
4455        synchronized (mPackages) {
4456            Object obj = mSettings.getUserIdLPr(uid);
4457            if (obj instanceof SharedUserSetting) {
4458                final SharedUserSetting sus = (SharedUserSetting) obj;
4459                final int N = sus.packages.size();
4460                final String[] res = new String[N];
4461                final Iterator<PackageSetting> it = sus.packages.iterator();
4462                int i = 0;
4463                while (it.hasNext()) {
4464                    res[i++] = it.next().name;
4465                }
4466                return res;
4467            } else if (obj instanceof PackageSetting) {
4468                final PackageSetting ps = (PackageSetting) obj;
4469                return new String[] { ps.name };
4470            }
4471        }
4472        return null;
4473    }
4474
4475    @Override
4476    public String getNameForUid(int uid) {
4477        // reader
4478        synchronized (mPackages) {
4479            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4480            if (obj instanceof SharedUserSetting) {
4481                final SharedUserSetting sus = (SharedUserSetting) obj;
4482                return sus.name + ":" + sus.userId;
4483            } else if (obj instanceof PackageSetting) {
4484                final PackageSetting ps = (PackageSetting) obj;
4485                return ps.name;
4486            }
4487        }
4488        return null;
4489    }
4490
4491    @Override
4492    public int getUidForSharedUser(String sharedUserName) {
4493        if(sharedUserName == null) {
4494            return -1;
4495        }
4496        // reader
4497        synchronized (mPackages) {
4498            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4499            if (suid == null) {
4500                return -1;
4501            }
4502            return suid.userId;
4503        }
4504    }
4505
4506    @Override
4507    public int getFlagsForUid(int uid) {
4508        synchronized (mPackages) {
4509            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4510            if (obj instanceof SharedUserSetting) {
4511                final SharedUserSetting sus = (SharedUserSetting) obj;
4512                return sus.pkgFlags;
4513            } else if (obj instanceof PackageSetting) {
4514                final PackageSetting ps = (PackageSetting) obj;
4515                return ps.pkgFlags;
4516            }
4517        }
4518        return 0;
4519    }
4520
4521    @Override
4522    public int getPrivateFlagsForUid(int uid) {
4523        synchronized (mPackages) {
4524            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4525            if (obj instanceof SharedUserSetting) {
4526                final SharedUserSetting sus = (SharedUserSetting) obj;
4527                return sus.pkgPrivateFlags;
4528            } else if (obj instanceof PackageSetting) {
4529                final PackageSetting ps = (PackageSetting) obj;
4530                return ps.pkgPrivateFlags;
4531            }
4532        }
4533        return 0;
4534    }
4535
4536    @Override
4537    public boolean isUidPrivileged(int uid) {
4538        uid = UserHandle.getAppId(uid);
4539        // reader
4540        synchronized (mPackages) {
4541            Object obj = mSettings.getUserIdLPr(uid);
4542            if (obj instanceof SharedUserSetting) {
4543                final SharedUserSetting sus = (SharedUserSetting) obj;
4544                final Iterator<PackageSetting> it = sus.packages.iterator();
4545                while (it.hasNext()) {
4546                    if (it.next().isPrivileged()) {
4547                        return true;
4548                    }
4549                }
4550            } else if (obj instanceof PackageSetting) {
4551                final PackageSetting ps = (PackageSetting) obj;
4552                return ps.isPrivileged();
4553            }
4554        }
4555        return false;
4556    }
4557
4558    @Override
4559    public String[] getAppOpPermissionPackages(String permissionName) {
4560        synchronized (mPackages) {
4561            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4562            if (pkgs == null) {
4563                return null;
4564            }
4565            return pkgs.toArray(new String[pkgs.size()]);
4566        }
4567    }
4568
4569    @Override
4570    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4571            int flags, int userId) {
4572        if (!sUserManager.exists(userId)) return null;
4573        flags = updateFlagsForResolve(flags, userId, intent);
4574        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4575        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4576        final ResolveInfo bestChoice =
4577                chooseBestActivity(intent, resolvedType, flags, query, userId);
4578
4579        if (isEphemeralAllowed(intent, query, userId)) {
4580            final EphemeralResolveInfo ai =
4581                    getEphemeralResolveInfo(intent, resolvedType, userId);
4582            if (ai != null) {
4583                if (DEBUG_EPHEMERAL) {
4584                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4585                }
4586                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4587                bestChoice.ephemeralResolveInfo = ai;
4588            }
4589        }
4590        return bestChoice;
4591    }
4592
4593    @Override
4594    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4595            IntentFilter filter, int match, ComponentName activity) {
4596        final int userId = UserHandle.getCallingUserId();
4597        if (DEBUG_PREFERRED) {
4598            Log.v(TAG, "setLastChosenActivity intent=" + intent
4599                + " resolvedType=" + resolvedType
4600                + " flags=" + flags
4601                + " filter=" + filter
4602                + " match=" + match
4603                + " activity=" + activity);
4604            filter.dump(new PrintStreamPrinter(System.out), "    ");
4605        }
4606        intent.setComponent(null);
4607        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4608        // Find any earlier preferred or last chosen entries and nuke them
4609        findPreferredActivity(intent, resolvedType,
4610                flags, query, 0, false, true, false, userId);
4611        // Add the new activity as the last chosen for this filter
4612        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4613                "Setting last chosen");
4614    }
4615
4616    @Override
4617    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4618        final int userId = UserHandle.getCallingUserId();
4619        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4620        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4621        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4622                false, false, false, userId);
4623    }
4624
4625
4626    private boolean isEphemeralAllowed(
4627            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4628        // Short circuit and return early if possible.
4629        if (DISABLE_EPHEMERAL_APPS) {
4630            return false;
4631        }
4632        final int callingUser = UserHandle.getCallingUserId();
4633        if (callingUser != UserHandle.USER_SYSTEM) {
4634            return false;
4635        }
4636        if (mEphemeralResolverConnection == null) {
4637            return false;
4638        }
4639        if (intent.getComponent() != null) {
4640            return false;
4641        }
4642        if (intent.getPackage() != null) {
4643            return false;
4644        }
4645        final boolean isWebUri = hasWebURI(intent);
4646        if (!isWebUri) {
4647            return false;
4648        }
4649        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4650        synchronized (mPackages) {
4651            final int count = resolvedActivites.size();
4652            for (int n = 0; n < count; n++) {
4653                ResolveInfo info = resolvedActivites.get(n);
4654                String packageName = info.activityInfo.packageName;
4655                PackageSetting ps = mSettings.mPackages.get(packageName);
4656                if (ps != null) {
4657                    // Try to get the status from User settings first
4658                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4659                    int status = (int) (packedStatus >> 32);
4660                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4661                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4662                        if (DEBUG_EPHEMERAL) {
4663                            Slog.v(TAG, "DENY ephemeral apps;"
4664                                + " pkg: " + packageName + ", status: " + status);
4665                        }
4666                        return false;
4667                    }
4668                }
4669            }
4670        }
4671        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4672        return true;
4673    }
4674
4675    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4676            int userId) {
4677        MessageDigest digest = null;
4678        try {
4679            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4680        } catch (NoSuchAlgorithmException e) {
4681            // If we can't create a digest, ignore ephemeral apps.
4682            return null;
4683        }
4684
4685        final byte[] hostBytes = intent.getData().getHost().getBytes();
4686        final byte[] digestBytes = digest.digest(hostBytes);
4687        int shaPrefix =
4688                digestBytes[0] << 24
4689                | digestBytes[1] << 16
4690                | digestBytes[2] << 8
4691                | digestBytes[3] << 0;
4692        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4693                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4694        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4695            // No hash prefix match; there are no ephemeral apps for this domain.
4696            return null;
4697        }
4698        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4699            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4700            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4701                continue;
4702            }
4703            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4704            // No filters; this should never happen.
4705            if (filters.isEmpty()) {
4706                continue;
4707            }
4708            // We have a domain match; resolve the filters to see if anything matches.
4709            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4710            for (int j = filters.size() - 1; j >= 0; --j) {
4711                final EphemeralResolveIntentInfo intentInfo =
4712                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4713                ephemeralResolver.addFilter(intentInfo);
4714            }
4715            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4716                    intent, resolvedType, false /*defaultOnly*/, userId);
4717            if (!matchedResolveInfoList.isEmpty()) {
4718                return matchedResolveInfoList.get(0);
4719            }
4720        }
4721        // Hash or filter mis-match; no ephemeral apps for this domain.
4722        return null;
4723    }
4724
4725    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4726            int flags, List<ResolveInfo> query, int userId) {
4727        if (query != null) {
4728            final int N = query.size();
4729            if (N == 1) {
4730                return query.get(0);
4731            } else if (N > 1) {
4732                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4733                // If there is more than one activity with the same priority,
4734                // then let the user decide between them.
4735                ResolveInfo r0 = query.get(0);
4736                ResolveInfo r1 = query.get(1);
4737                if (DEBUG_INTENT_MATCHING || debug) {
4738                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4739                            + r1.activityInfo.name + "=" + r1.priority);
4740                }
4741                // If the first activity has a higher priority, or a different
4742                // default, then it is always desirable to pick it.
4743                if (r0.priority != r1.priority
4744                        || r0.preferredOrder != r1.preferredOrder
4745                        || r0.isDefault != r1.isDefault) {
4746                    return query.get(0);
4747                }
4748                // If we have saved a preference for a preferred activity for
4749                // this Intent, use that.
4750                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4751                        flags, query, r0.priority, true, false, debug, userId);
4752                if (ri != null) {
4753                    return ri;
4754                }
4755                ri = new ResolveInfo(mResolveInfo);
4756                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4757                ri.activityInfo.applicationInfo = new ApplicationInfo(
4758                        ri.activityInfo.applicationInfo);
4759                if (userId != 0) {
4760                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4761                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4762                }
4763                // Make sure that the resolver is displayable in car mode
4764                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4765                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4766                return ri;
4767            }
4768        }
4769        return null;
4770    }
4771
4772    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4773            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4774        final int N = query.size();
4775        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4776                .get(userId);
4777        // Get the list of persistent preferred activities that handle the intent
4778        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4779        List<PersistentPreferredActivity> pprefs = ppir != null
4780                ? ppir.queryIntent(intent, resolvedType,
4781                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4782                : null;
4783        if (pprefs != null && pprefs.size() > 0) {
4784            final int M = pprefs.size();
4785            for (int i=0; i<M; i++) {
4786                final PersistentPreferredActivity ppa = pprefs.get(i);
4787                if (DEBUG_PREFERRED || debug) {
4788                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4789                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4790                            + "\n  component=" + ppa.mComponent);
4791                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4792                }
4793                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4794                        flags | MATCH_DISABLED_COMPONENTS, userId);
4795                if (DEBUG_PREFERRED || debug) {
4796                    Slog.v(TAG, "Found persistent preferred activity:");
4797                    if (ai != null) {
4798                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4799                    } else {
4800                        Slog.v(TAG, "  null");
4801                    }
4802                }
4803                if (ai == null) {
4804                    // This previously registered persistent preferred activity
4805                    // component is no longer known. Ignore it and do NOT remove it.
4806                    continue;
4807                }
4808                for (int j=0; j<N; j++) {
4809                    final ResolveInfo ri = query.get(j);
4810                    if (!ri.activityInfo.applicationInfo.packageName
4811                            .equals(ai.applicationInfo.packageName)) {
4812                        continue;
4813                    }
4814                    if (!ri.activityInfo.name.equals(ai.name)) {
4815                        continue;
4816                    }
4817                    //  Found a persistent preference that can handle the intent.
4818                    if (DEBUG_PREFERRED || debug) {
4819                        Slog.v(TAG, "Returning persistent preferred activity: " +
4820                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4821                    }
4822                    return ri;
4823                }
4824            }
4825        }
4826        return null;
4827    }
4828
4829    // TODO: handle preferred activities missing while user has amnesia
4830    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4831            List<ResolveInfo> query, int priority, boolean always,
4832            boolean removeMatches, boolean debug, int userId) {
4833        if (!sUserManager.exists(userId)) return null;
4834        flags = updateFlagsForResolve(flags, userId, intent);
4835        // writer
4836        synchronized (mPackages) {
4837            if (intent.getSelector() != null) {
4838                intent = intent.getSelector();
4839            }
4840            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4841
4842            // Try to find a matching persistent preferred activity.
4843            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4844                    debug, userId);
4845
4846            // If a persistent preferred activity matched, use it.
4847            if (pri != null) {
4848                return pri;
4849            }
4850
4851            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4852            // Get the list of preferred activities that handle the intent
4853            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4854            List<PreferredActivity> prefs = pir != null
4855                    ? pir.queryIntent(intent, resolvedType,
4856                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4857                    : null;
4858            if (prefs != null && prefs.size() > 0) {
4859                boolean changed = false;
4860                try {
4861                    // First figure out how good the original match set is.
4862                    // We will only allow preferred activities that came
4863                    // from the same match quality.
4864                    int match = 0;
4865
4866                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4867
4868                    final int N = query.size();
4869                    for (int j=0; j<N; j++) {
4870                        final ResolveInfo ri = query.get(j);
4871                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4872                                + ": 0x" + Integer.toHexString(match));
4873                        if (ri.match > match) {
4874                            match = ri.match;
4875                        }
4876                    }
4877
4878                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4879                            + Integer.toHexString(match));
4880
4881                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4882                    final int M = prefs.size();
4883                    for (int i=0; i<M; i++) {
4884                        final PreferredActivity pa = prefs.get(i);
4885                        if (DEBUG_PREFERRED || debug) {
4886                            Slog.v(TAG, "Checking PreferredActivity ds="
4887                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4888                                    + "\n  component=" + pa.mPref.mComponent);
4889                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4890                        }
4891                        if (pa.mPref.mMatch != match) {
4892                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4893                                    + Integer.toHexString(pa.mPref.mMatch));
4894                            continue;
4895                        }
4896                        // If it's not an "always" type preferred activity and that's what we're
4897                        // looking for, skip it.
4898                        if (always && !pa.mPref.mAlways) {
4899                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4900                            continue;
4901                        }
4902                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4903                                flags | MATCH_DISABLED_COMPONENTS, userId);
4904                        if (DEBUG_PREFERRED || debug) {
4905                            Slog.v(TAG, "Found preferred activity:");
4906                            if (ai != null) {
4907                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4908                            } else {
4909                                Slog.v(TAG, "  null");
4910                            }
4911                        }
4912                        if (ai == null) {
4913                            // This previously registered preferred activity
4914                            // component is no longer known.  Most likely an update
4915                            // to the app was installed and in the new version this
4916                            // component no longer exists.  Clean it up by removing
4917                            // it from the preferred activities list, and skip it.
4918                            Slog.w(TAG, "Removing dangling preferred activity: "
4919                                    + pa.mPref.mComponent);
4920                            pir.removeFilter(pa);
4921                            changed = true;
4922                            continue;
4923                        }
4924                        for (int j=0; j<N; j++) {
4925                            final ResolveInfo ri = query.get(j);
4926                            if (!ri.activityInfo.applicationInfo.packageName
4927                                    .equals(ai.applicationInfo.packageName)) {
4928                                continue;
4929                            }
4930                            if (!ri.activityInfo.name.equals(ai.name)) {
4931                                continue;
4932                            }
4933
4934                            if (removeMatches) {
4935                                pir.removeFilter(pa);
4936                                changed = true;
4937                                if (DEBUG_PREFERRED) {
4938                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4939                                }
4940                                break;
4941                            }
4942
4943                            // Okay we found a previously set preferred or last chosen app.
4944                            // If the result set is different from when this
4945                            // was created, we need to clear it and re-ask the
4946                            // user their preference, if we're looking for an "always" type entry.
4947                            if (always && !pa.mPref.sameSet(query)) {
4948                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4949                                        + intent + " type " + resolvedType);
4950                                if (DEBUG_PREFERRED) {
4951                                    Slog.v(TAG, "Removing preferred activity since set changed "
4952                                            + pa.mPref.mComponent);
4953                                }
4954                                pir.removeFilter(pa);
4955                                // Re-add the filter as a "last chosen" entry (!always)
4956                                PreferredActivity lastChosen = new PreferredActivity(
4957                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4958                                pir.addFilter(lastChosen);
4959                                changed = true;
4960                                return null;
4961                            }
4962
4963                            // Yay! Either the set matched or we're looking for the last chosen
4964                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4965                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4966                            return ri;
4967                        }
4968                    }
4969                } finally {
4970                    if (changed) {
4971                        if (DEBUG_PREFERRED) {
4972                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4973                        }
4974                        scheduleWritePackageRestrictionsLocked(userId);
4975                    }
4976                }
4977            }
4978        }
4979        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4980        return null;
4981    }
4982
4983    /*
4984     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4985     */
4986    @Override
4987    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4988            int targetUserId) {
4989        mContext.enforceCallingOrSelfPermission(
4990                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4991        List<CrossProfileIntentFilter> matches =
4992                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4993        if (matches != null) {
4994            int size = matches.size();
4995            for (int i = 0; i < size; i++) {
4996                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4997            }
4998        }
4999        if (hasWebURI(intent)) {
5000            // cross-profile app linking works only towards the parent.
5001            final UserInfo parent = getProfileParent(sourceUserId);
5002            synchronized(mPackages) {
5003                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5004                        intent, resolvedType, 0, sourceUserId, parent.id);
5005                return xpDomainInfo != null;
5006            }
5007        }
5008        return false;
5009    }
5010
5011    private UserInfo getProfileParent(int userId) {
5012        final long identity = Binder.clearCallingIdentity();
5013        try {
5014            return sUserManager.getProfileParent(userId);
5015        } finally {
5016            Binder.restoreCallingIdentity(identity);
5017        }
5018    }
5019
5020    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5021            String resolvedType, int userId) {
5022        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5023        if (resolver != null) {
5024            return resolver.queryIntent(intent, resolvedType, false, userId);
5025        }
5026        return null;
5027    }
5028
5029    @Override
5030    public List<ResolveInfo> queryIntentActivities(Intent intent,
5031            String resolvedType, int flags, int userId) {
5032        if (!sUserManager.exists(userId)) return Collections.emptyList();
5033        flags = updateFlagsForResolve(flags, userId, intent);
5034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
5035        ComponentName comp = intent.getComponent();
5036        if (comp == null) {
5037            if (intent.getSelector() != null) {
5038                intent = intent.getSelector();
5039                comp = intent.getComponent();
5040            }
5041        }
5042
5043        if (comp != null) {
5044            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5045            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5046            if (ai != null) {
5047                final ResolveInfo ri = new ResolveInfo();
5048                ri.activityInfo = ai;
5049                list.add(ri);
5050            }
5051            return list;
5052        }
5053
5054        // reader
5055        synchronized (mPackages) {
5056            final String pkgName = intent.getPackage();
5057            if (pkgName == null) {
5058                List<CrossProfileIntentFilter> matchingFilters =
5059                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5060                // Check for results that need to skip the current profile.
5061                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5062                        resolvedType, flags, userId);
5063                if (xpResolveInfo != null) {
5064                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5065                    result.add(xpResolveInfo);
5066                    return filterIfNotSystemUser(result, userId);
5067                }
5068
5069                // Check for results in the current profile.
5070                List<ResolveInfo> result = mActivities.queryIntent(
5071                        intent, resolvedType, flags, userId);
5072                result = filterIfNotSystemUser(result, userId);
5073
5074                // Check for cross profile results.
5075                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5076                xpResolveInfo = queryCrossProfileIntents(
5077                        matchingFilters, intent, resolvedType, flags, userId,
5078                        hasNonNegativePriorityResult);
5079                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5080                    boolean isVisibleToUser = filterIfNotSystemUser(
5081                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5082                    if (isVisibleToUser) {
5083                        result.add(xpResolveInfo);
5084                        Collections.sort(result, mResolvePrioritySorter);
5085                    }
5086                }
5087                if (hasWebURI(intent)) {
5088                    CrossProfileDomainInfo xpDomainInfo = null;
5089                    final UserInfo parent = getProfileParent(userId);
5090                    if (parent != null) {
5091                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5092                                flags, userId, parent.id);
5093                    }
5094                    if (xpDomainInfo != null) {
5095                        if (xpResolveInfo != null) {
5096                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5097                            // in the result.
5098                            result.remove(xpResolveInfo);
5099                        }
5100                        if (result.size() == 0) {
5101                            result.add(xpDomainInfo.resolveInfo);
5102                            return result;
5103                        }
5104                    } else if (result.size() <= 1) {
5105                        return result;
5106                    }
5107                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5108                            xpDomainInfo, userId);
5109                    Collections.sort(result, mResolvePrioritySorter);
5110                }
5111                return result;
5112            }
5113            final PackageParser.Package pkg = mPackages.get(pkgName);
5114            if (pkg != null) {
5115                return filterIfNotSystemUser(
5116                        mActivities.queryIntentForPackage(
5117                                intent, resolvedType, flags, pkg.activities, userId),
5118                        userId);
5119            }
5120            return new ArrayList<ResolveInfo>();
5121        }
5122    }
5123
5124    private static class CrossProfileDomainInfo {
5125        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5126        ResolveInfo resolveInfo;
5127        /* Best domain verification status of the activities found in the other profile */
5128        int bestDomainVerificationStatus;
5129    }
5130
5131    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5132            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5133        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5134                sourceUserId)) {
5135            return null;
5136        }
5137        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5138                resolvedType, flags, parentUserId);
5139
5140        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5141            return null;
5142        }
5143        CrossProfileDomainInfo result = null;
5144        int size = resultTargetUser.size();
5145        for (int i = 0; i < size; i++) {
5146            ResolveInfo riTargetUser = resultTargetUser.get(i);
5147            // Intent filter verification is only for filters that specify a host. So don't return
5148            // those that handle all web uris.
5149            if (riTargetUser.handleAllWebDataURI) {
5150                continue;
5151            }
5152            String packageName = riTargetUser.activityInfo.packageName;
5153            PackageSetting ps = mSettings.mPackages.get(packageName);
5154            if (ps == null) {
5155                continue;
5156            }
5157            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5158            int status = (int)(verificationState >> 32);
5159            if (result == null) {
5160                result = new CrossProfileDomainInfo();
5161                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5162                        sourceUserId, parentUserId);
5163                result.bestDomainVerificationStatus = status;
5164            } else {
5165                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5166                        result.bestDomainVerificationStatus);
5167            }
5168        }
5169        // Don't consider matches with status NEVER across profiles.
5170        if (result != null && result.bestDomainVerificationStatus
5171                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5172            return null;
5173        }
5174        return result;
5175    }
5176
5177    /**
5178     * Verification statuses are ordered from the worse to the best, except for
5179     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5180     */
5181    private int bestDomainVerificationStatus(int status1, int status2) {
5182        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5183            return status2;
5184        }
5185        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5186            return status1;
5187        }
5188        return (int) MathUtils.max(status1, status2);
5189    }
5190
5191    private boolean isUserEnabled(int userId) {
5192        long callingId = Binder.clearCallingIdentity();
5193        try {
5194            UserInfo userInfo = sUserManager.getUserInfo(userId);
5195            return userInfo != null && userInfo.isEnabled();
5196        } finally {
5197            Binder.restoreCallingIdentity(callingId);
5198        }
5199    }
5200
5201    /**
5202     * Filter out activities with systemUserOnly flag set, when current user is not System.
5203     *
5204     * @return filtered list
5205     */
5206    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5207        if (userId == UserHandle.USER_SYSTEM) {
5208            return resolveInfos;
5209        }
5210        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5211            ResolveInfo info = resolveInfos.get(i);
5212            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5213                resolveInfos.remove(i);
5214            }
5215        }
5216        return resolveInfos;
5217    }
5218
5219    /**
5220     * @param resolveInfos list of resolve infos in descending priority order
5221     * @return if the list contains a resolve info with non-negative priority
5222     */
5223    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5224        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5225    }
5226
5227    private static boolean hasWebURI(Intent intent) {
5228        if (intent.getData() == null) {
5229            return false;
5230        }
5231        final String scheme = intent.getScheme();
5232        if (TextUtils.isEmpty(scheme)) {
5233            return false;
5234        }
5235        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5236    }
5237
5238    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5239            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5240            int userId) {
5241        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5242
5243        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5244            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5245                    candidates.size());
5246        }
5247
5248        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5249        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5250        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5251        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5252        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5253        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5254
5255        synchronized (mPackages) {
5256            final int count = candidates.size();
5257            // First, try to use linked apps. Partition the candidates into four lists:
5258            // one for the final results, one for the "do not use ever", one for "undefined status"
5259            // and finally one for "browser app type".
5260            for (int n=0; n<count; n++) {
5261                ResolveInfo info = candidates.get(n);
5262                String packageName = info.activityInfo.packageName;
5263                PackageSetting ps = mSettings.mPackages.get(packageName);
5264                if (ps != null) {
5265                    // Add to the special match all list (Browser use case)
5266                    if (info.handleAllWebDataURI) {
5267                        matchAllList.add(info);
5268                        continue;
5269                    }
5270                    // Try to get the status from User settings first
5271                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5272                    int status = (int)(packedStatus >> 32);
5273                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5274                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5275                        if (DEBUG_DOMAIN_VERIFICATION) {
5276                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5277                                    + " : linkgen=" + linkGeneration);
5278                        }
5279                        // Use link-enabled generation as preferredOrder, i.e.
5280                        // prefer newly-enabled over earlier-enabled.
5281                        info.preferredOrder = linkGeneration;
5282                        alwaysList.add(info);
5283                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5284                        if (DEBUG_DOMAIN_VERIFICATION) {
5285                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5286                        }
5287                        neverList.add(info);
5288                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5289                        if (DEBUG_DOMAIN_VERIFICATION) {
5290                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5291                        }
5292                        alwaysAskList.add(info);
5293                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5294                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5295                        if (DEBUG_DOMAIN_VERIFICATION) {
5296                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5297                        }
5298                        undefinedList.add(info);
5299                    }
5300                }
5301            }
5302
5303            // We'll want to include browser possibilities in a few cases
5304            boolean includeBrowser = false;
5305
5306            // First try to add the "always" resolution(s) for the current user, if any
5307            if (alwaysList.size() > 0) {
5308                result.addAll(alwaysList);
5309            } else {
5310                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5311                result.addAll(undefinedList);
5312                // Maybe add one for the other profile.
5313                if (xpDomainInfo != null && (
5314                        xpDomainInfo.bestDomainVerificationStatus
5315                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5316                    result.add(xpDomainInfo.resolveInfo);
5317                }
5318                includeBrowser = true;
5319            }
5320
5321            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5322            // If there were 'always' entries their preferred order has been set, so we also
5323            // back that off to make the alternatives equivalent
5324            if (alwaysAskList.size() > 0) {
5325                for (ResolveInfo i : result) {
5326                    i.preferredOrder = 0;
5327                }
5328                result.addAll(alwaysAskList);
5329                includeBrowser = true;
5330            }
5331
5332            if (includeBrowser) {
5333                // Also add browsers (all of them or only the default one)
5334                if (DEBUG_DOMAIN_VERIFICATION) {
5335                    Slog.v(TAG, "   ...including browsers in candidate set");
5336                }
5337                if ((matchFlags & MATCH_ALL) != 0) {
5338                    result.addAll(matchAllList);
5339                } else {
5340                    // Browser/generic handling case.  If there's a default browser, go straight
5341                    // to that (but only if there is no other higher-priority match).
5342                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5343                    int maxMatchPrio = 0;
5344                    ResolveInfo defaultBrowserMatch = null;
5345                    final int numCandidates = matchAllList.size();
5346                    for (int n = 0; n < numCandidates; n++) {
5347                        ResolveInfo info = matchAllList.get(n);
5348                        // track the highest overall match priority...
5349                        if (info.priority > maxMatchPrio) {
5350                            maxMatchPrio = info.priority;
5351                        }
5352                        // ...and the highest-priority default browser match
5353                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5354                            if (defaultBrowserMatch == null
5355                                    || (defaultBrowserMatch.priority < info.priority)) {
5356                                if (debug) {
5357                                    Slog.v(TAG, "Considering default browser match " + info);
5358                                }
5359                                defaultBrowserMatch = info;
5360                            }
5361                        }
5362                    }
5363                    if (defaultBrowserMatch != null
5364                            && defaultBrowserMatch.priority >= maxMatchPrio
5365                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5366                    {
5367                        if (debug) {
5368                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5369                        }
5370                        result.add(defaultBrowserMatch);
5371                    } else {
5372                        result.addAll(matchAllList);
5373                    }
5374                }
5375
5376                // If there is nothing selected, add all candidates and remove the ones that the user
5377                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5378                if (result.size() == 0) {
5379                    result.addAll(candidates);
5380                    result.removeAll(neverList);
5381                }
5382            }
5383        }
5384        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5385            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5386                    result.size());
5387            for (ResolveInfo info : result) {
5388                Slog.v(TAG, "  + " + info.activityInfo);
5389            }
5390        }
5391        return result;
5392    }
5393
5394    // Returns a packed value as a long:
5395    //
5396    // high 'int'-sized word: link status: undefined/ask/never/always.
5397    // low 'int'-sized word: relative priority among 'always' results.
5398    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5399        long result = ps.getDomainVerificationStatusForUser(userId);
5400        // if none available, get the master status
5401        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5402            if (ps.getIntentFilterVerificationInfo() != null) {
5403                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5404            }
5405        }
5406        return result;
5407    }
5408
5409    private ResolveInfo querySkipCurrentProfileIntents(
5410            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5411            int flags, int sourceUserId) {
5412        if (matchingFilters != null) {
5413            int size = matchingFilters.size();
5414            for (int i = 0; i < size; i ++) {
5415                CrossProfileIntentFilter filter = matchingFilters.get(i);
5416                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5417                    // Checking if there are activities in the target user that can handle the
5418                    // intent.
5419                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5420                            resolvedType, flags, sourceUserId);
5421                    if (resolveInfo != null) {
5422                        return resolveInfo;
5423                    }
5424                }
5425            }
5426        }
5427        return null;
5428    }
5429
5430    // Return matching ResolveInfo in target user if any.
5431    private ResolveInfo queryCrossProfileIntents(
5432            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5433            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5434        if (matchingFilters != null) {
5435            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5436            // match the same intent. For performance reasons, it is better not to
5437            // run queryIntent twice for the same userId
5438            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5439            int size = matchingFilters.size();
5440            for (int i = 0; i < size; i++) {
5441                CrossProfileIntentFilter filter = matchingFilters.get(i);
5442                int targetUserId = filter.getTargetUserId();
5443                boolean skipCurrentProfile =
5444                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5445                boolean skipCurrentProfileIfNoMatchFound =
5446                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5447                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5448                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5449                    // Checking if there are activities in the target user that can handle the
5450                    // intent.
5451                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5452                            resolvedType, flags, sourceUserId);
5453                    if (resolveInfo != null) return resolveInfo;
5454                    alreadyTriedUserIds.put(targetUserId, true);
5455                }
5456            }
5457        }
5458        return null;
5459    }
5460
5461    /**
5462     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5463     * will forward the intent to the filter's target user.
5464     * Otherwise, returns null.
5465     */
5466    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5467            String resolvedType, int flags, int sourceUserId) {
5468        int targetUserId = filter.getTargetUserId();
5469        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5470                resolvedType, flags, targetUserId);
5471        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5472            // If all the matches in the target profile are suspended, return null.
5473            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5474                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5475                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5476                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5477                            targetUserId);
5478                }
5479            }
5480        }
5481        return null;
5482    }
5483
5484    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5485            int sourceUserId, int targetUserId) {
5486        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5487        long ident = Binder.clearCallingIdentity();
5488        boolean targetIsProfile;
5489        try {
5490            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5491        } finally {
5492            Binder.restoreCallingIdentity(ident);
5493        }
5494        String className;
5495        if (targetIsProfile) {
5496            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5497        } else {
5498            className = FORWARD_INTENT_TO_PARENT;
5499        }
5500        ComponentName forwardingActivityComponentName = new ComponentName(
5501                mAndroidApplication.packageName, className);
5502        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5503                sourceUserId);
5504        if (!targetIsProfile) {
5505            forwardingActivityInfo.showUserIcon = targetUserId;
5506            forwardingResolveInfo.noResourceId = true;
5507        }
5508        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5509        forwardingResolveInfo.priority = 0;
5510        forwardingResolveInfo.preferredOrder = 0;
5511        forwardingResolveInfo.match = 0;
5512        forwardingResolveInfo.isDefault = true;
5513        forwardingResolveInfo.filter = filter;
5514        forwardingResolveInfo.targetUserId = targetUserId;
5515        return forwardingResolveInfo;
5516    }
5517
5518    @Override
5519    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5520            Intent[] specifics, String[] specificTypes, Intent intent,
5521            String resolvedType, int flags, int userId) {
5522        if (!sUserManager.exists(userId)) return Collections.emptyList();
5523        flags = updateFlagsForResolve(flags, userId, intent);
5524        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5525                false, "query intent activity options");
5526        final String resultsAction = intent.getAction();
5527
5528        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5529                | PackageManager.GET_RESOLVED_FILTER, userId);
5530
5531        if (DEBUG_INTENT_MATCHING) {
5532            Log.v(TAG, "Query " + intent + ": " + results);
5533        }
5534
5535        int specificsPos = 0;
5536        int N;
5537
5538        // todo: note that the algorithm used here is O(N^2).  This
5539        // isn't a problem in our current environment, but if we start running
5540        // into situations where we have more than 5 or 10 matches then this
5541        // should probably be changed to something smarter...
5542
5543        // First we go through and resolve each of the specific items
5544        // that were supplied, taking care of removing any corresponding
5545        // duplicate items in the generic resolve list.
5546        if (specifics != null) {
5547            for (int i=0; i<specifics.length; i++) {
5548                final Intent sintent = specifics[i];
5549                if (sintent == null) {
5550                    continue;
5551                }
5552
5553                if (DEBUG_INTENT_MATCHING) {
5554                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5555                }
5556
5557                String action = sintent.getAction();
5558                if (resultsAction != null && resultsAction.equals(action)) {
5559                    // If this action was explicitly requested, then don't
5560                    // remove things that have it.
5561                    action = null;
5562                }
5563
5564                ResolveInfo ri = null;
5565                ActivityInfo ai = null;
5566
5567                ComponentName comp = sintent.getComponent();
5568                if (comp == null) {
5569                    ri = resolveIntent(
5570                        sintent,
5571                        specificTypes != null ? specificTypes[i] : null,
5572                            flags, userId);
5573                    if (ri == null) {
5574                        continue;
5575                    }
5576                    if (ri == mResolveInfo) {
5577                        // ACK!  Must do something better with this.
5578                    }
5579                    ai = ri.activityInfo;
5580                    comp = new ComponentName(ai.applicationInfo.packageName,
5581                            ai.name);
5582                } else {
5583                    ai = getActivityInfo(comp, flags, userId);
5584                    if (ai == null) {
5585                        continue;
5586                    }
5587                }
5588
5589                // Look for any generic query activities that are duplicates
5590                // of this specific one, and remove them from the results.
5591                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5592                N = results.size();
5593                int j;
5594                for (j=specificsPos; j<N; j++) {
5595                    ResolveInfo sri = results.get(j);
5596                    if ((sri.activityInfo.name.equals(comp.getClassName())
5597                            && sri.activityInfo.applicationInfo.packageName.equals(
5598                                    comp.getPackageName()))
5599                        || (action != null && sri.filter.matchAction(action))) {
5600                        results.remove(j);
5601                        if (DEBUG_INTENT_MATCHING) Log.v(
5602                            TAG, "Removing duplicate item from " + j
5603                            + " due to specific " + specificsPos);
5604                        if (ri == null) {
5605                            ri = sri;
5606                        }
5607                        j--;
5608                        N--;
5609                    }
5610                }
5611
5612                // Add this specific item to its proper place.
5613                if (ri == null) {
5614                    ri = new ResolveInfo();
5615                    ri.activityInfo = ai;
5616                }
5617                results.add(specificsPos, ri);
5618                ri.specificIndex = i;
5619                specificsPos++;
5620            }
5621        }
5622
5623        // Now we go through the remaining generic results and remove any
5624        // duplicate actions that are found here.
5625        N = results.size();
5626        for (int i=specificsPos; i<N-1; i++) {
5627            final ResolveInfo rii = results.get(i);
5628            if (rii.filter == null) {
5629                continue;
5630            }
5631
5632            // Iterate over all of the actions of this result's intent
5633            // filter...  typically this should be just one.
5634            final Iterator<String> it = rii.filter.actionsIterator();
5635            if (it == null) {
5636                continue;
5637            }
5638            while (it.hasNext()) {
5639                final String action = it.next();
5640                if (resultsAction != null && resultsAction.equals(action)) {
5641                    // If this action was explicitly requested, then don't
5642                    // remove things that have it.
5643                    continue;
5644                }
5645                for (int j=i+1; j<N; j++) {
5646                    final ResolveInfo rij = results.get(j);
5647                    if (rij.filter != null && rij.filter.hasAction(action)) {
5648                        results.remove(j);
5649                        if (DEBUG_INTENT_MATCHING) Log.v(
5650                            TAG, "Removing duplicate item from " + j
5651                            + " due to action " + action + " at " + i);
5652                        j--;
5653                        N--;
5654                    }
5655                }
5656            }
5657
5658            // If the caller didn't request filter information, drop it now
5659            // so we don't have to marshall/unmarshall it.
5660            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5661                rii.filter = null;
5662            }
5663        }
5664
5665        // Filter out the caller activity if so requested.
5666        if (caller != null) {
5667            N = results.size();
5668            for (int i=0; i<N; i++) {
5669                ActivityInfo ainfo = results.get(i).activityInfo;
5670                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5671                        && caller.getClassName().equals(ainfo.name)) {
5672                    results.remove(i);
5673                    break;
5674                }
5675            }
5676        }
5677
5678        // If the caller didn't request filter information,
5679        // drop them now so we don't have to
5680        // marshall/unmarshall it.
5681        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5682            N = results.size();
5683            for (int i=0; i<N; i++) {
5684                results.get(i).filter = null;
5685            }
5686        }
5687
5688        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5689        return results;
5690    }
5691
5692    @Override
5693    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5694            int userId) {
5695        if (!sUserManager.exists(userId)) return Collections.emptyList();
5696        flags = updateFlagsForResolve(flags, userId, intent);
5697        ComponentName comp = intent.getComponent();
5698        if (comp == null) {
5699            if (intent.getSelector() != null) {
5700                intent = intent.getSelector();
5701                comp = intent.getComponent();
5702            }
5703        }
5704        if (comp != null) {
5705            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5706            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5707            if (ai != null) {
5708                ResolveInfo ri = new ResolveInfo();
5709                ri.activityInfo = ai;
5710                list.add(ri);
5711            }
5712            return list;
5713        }
5714
5715        // reader
5716        synchronized (mPackages) {
5717            String pkgName = intent.getPackage();
5718            if (pkgName == null) {
5719                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5720            }
5721            final PackageParser.Package pkg = mPackages.get(pkgName);
5722            if (pkg != null) {
5723                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5724                        userId);
5725            }
5726            return null;
5727        }
5728    }
5729
5730    @Override
5731    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5732        if (!sUserManager.exists(userId)) return null;
5733        flags = updateFlagsForResolve(flags, userId, intent);
5734        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5735        if (query != null) {
5736            if (query.size() >= 1) {
5737                // If there is more than one service with the same priority,
5738                // just arbitrarily pick the first one.
5739                return query.get(0);
5740            }
5741        }
5742        return null;
5743    }
5744
5745    @Override
5746    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5747            int userId) {
5748        if (!sUserManager.exists(userId)) return Collections.emptyList();
5749        flags = updateFlagsForResolve(flags, userId, intent);
5750        ComponentName comp = intent.getComponent();
5751        if (comp == null) {
5752            if (intent.getSelector() != null) {
5753                intent = intent.getSelector();
5754                comp = intent.getComponent();
5755            }
5756        }
5757        if (comp != null) {
5758            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5759            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5760            if (si != null) {
5761                final ResolveInfo ri = new ResolveInfo();
5762                ri.serviceInfo = si;
5763                list.add(ri);
5764            }
5765            return list;
5766        }
5767
5768        // reader
5769        synchronized (mPackages) {
5770            String pkgName = intent.getPackage();
5771            if (pkgName == null) {
5772                return mServices.queryIntent(intent, resolvedType, flags, userId);
5773            }
5774            final PackageParser.Package pkg = mPackages.get(pkgName);
5775            if (pkg != null) {
5776                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5777                        userId);
5778            }
5779            return null;
5780        }
5781    }
5782
5783    @Override
5784    public List<ResolveInfo> queryIntentContentProviders(
5785            Intent intent, String resolvedType, int flags, int userId) {
5786        if (!sUserManager.exists(userId)) return Collections.emptyList();
5787        flags = updateFlagsForResolve(flags, userId, intent);
5788        ComponentName comp = intent.getComponent();
5789        if (comp == null) {
5790            if (intent.getSelector() != null) {
5791                intent = intent.getSelector();
5792                comp = intent.getComponent();
5793            }
5794        }
5795        if (comp != null) {
5796            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5797            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5798            if (pi != null) {
5799                final ResolveInfo ri = new ResolveInfo();
5800                ri.providerInfo = pi;
5801                list.add(ri);
5802            }
5803            return list;
5804        }
5805
5806        // reader
5807        synchronized (mPackages) {
5808            String pkgName = intent.getPackage();
5809            if (pkgName == null) {
5810                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5811            }
5812            final PackageParser.Package pkg = mPackages.get(pkgName);
5813            if (pkg != null) {
5814                return mProviders.queryIntentForPackage(
5815                        intent, resolvedType, flags, pkg.providers, userId);
5816            }
5817            return null;
5818        }
5819    }
5820
5821    @Override
5822    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5823        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5824        flags = updateFlagsForPackage(flags, userId, null);
5825        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5826        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5827
5828        // writer
5829        synchronized (mPackages) {
5830            ArrayList<PackageInfo> list;
5831            if (listUninstalled) {
5832                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5833                for (PackageSetting ps : mSettings.mPackages.values()) {
5834                    PackageInfo pi;
5835                    if (ps.pkg != null) {
5836                        pi = generatePackageInfo(ps.pkg, flags, userId);
5837                    } else {
5838                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5839                    }
5840                    if (pi != null) {
5841                        list.add(pi);
5842                    }
5843                }
5844            } else {
5845                list = new ArrayList<PackageInfo>(mPackages.size());
5846                for (PackageParser.Package p : mPackages.values()) {
5847                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5848                    if (pi != null) {
5849                        list.add(pi);
5850                    }
5851                }
5852            }
5853
5854            return new ParceledListSlice<PackageInfo>(list);
5855        }
5856    }
5857
5858    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5859            String[] permissions, boolean[] tmp, int flags, int userId) {
5860        int numMatch = 0;
5861        final PermissionsState permissionsState = ps.getPermissionsState();
5862        for (int i=0; i<permissions.length; i++) {
5863            final String permission = permissions[i];
5864            if (permissionsState.hasPermission(permission, userId)) {
5865                tmp[i] = true;
5866                numMatch++;
5867            } else {
5868                tmp[i] = false;
5869            }
5870        }
5871        if (numMatch == 0) {
5872            return;
5873        }
5874        PackageInfo pi;
5875        if (ps.pkg != null) {
5876            pi = generatePackageInfo(ps.pkg, flags, userId);
5877        } else {
5878            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5879        }
5880        // The above might return null in cases of uninstalled apps or install-state
5881        // skew across users/profiles.
5882        if (pi != null) {
5883            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5884                if (numMatch == permissions.length) {
5885                    pi.requestedPermissions = permissions;
5886                } else {
5887                    pi.requestedPermissions = new String[numMatch];
5888                    numMatch = 0;
5889                    for (int i=0; i<permissions.length; i++) {
5890                        if (tmp[i]) {
5891                            pi.requestedPermissions[numMatch] = permissions[i];
5892                            numMatch++;
5893                        }
5894                    }
5895                }
5896            }
5897            list.add(pi);
5898        }
5899    }
5900
5901    @Override
5902    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5903            String[] permissions, int flags, int userId) {
5904        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5905        flags = updateFlagsForPackage(flags, userId, permissions);
5906        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5907
5908        // writer
5909        synchronized (mPackages) {
5910            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5911            boolean[] tmpBools = new boolean[permissions.length];
5912            if (listUninstalled) {
5913                for (PackageSetting ps : mSettings.mPackages.values()) {
5914                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5915                }
5916            } else {
5917                for (PackageParser.Package pkg : mPackages.values()) {
5918                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5919                    if (ps != null) {
5920                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5921                                userId);
5922                    }
5923                }
5924            }
5925
5926            return new ParceledListSlice<PackageInfo>(list);
5927        }
5928    }
5929
5930    @Override
5931    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5932        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5933        flags = updateFlagsForApplication(flags, userId, null);
5934        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5935
5936        // writer
5937        synchronized (mPackages) {
5938            ArrayList<ApplicationInfo> list;
5939            if (listUninstalled) {
5940                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5941                for (PackageSetting ps : mSettings.mPackages.values()) {
5942                    ApplicationInfo ai;
5943                    if (ps.pkg != null) {
5944                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5945                                ps.readUserState(userId), userId);
5946                    } else {
5947                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5948                    }
5949                    if (ai != null) {
5950                        list.add(ai);
5951                    }
5952                }
5953            } else {
5954                list = new ArrayList<ApplicationInfo>(mPackages.size());
5955                for (PackageParser.Package p : mPackages.values()) {
5956                    if (p.mExtras != null) {
5957                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5958                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5959                        if (ai != null) {
5960                            list.add(ai);
5961                        }
5962                    }
5963                }
5964            }
5965
5966            return new ParceledListSlice<ApplicationInfo>(list);
5967        }
5968    }
5969
5970    @Override
5971    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5972        if (DISABLE_EPHEMERAL_APPS) {
5973            return null;
5974        }
5975
5976        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5977                "getEphemeralApplications");
5978        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5979                "getEphemeralApplications");
5980        synchronized (mPackages) {
5981            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5982                    .getEphemeralApplicationsLPw(userId);
5983            if (ephemeralApps != null) {
5984                return new ParceledListSlice<>(ephemeralApps);
5985            }
5986        }
5987        return null;
5988    }
5989
5990    @Override
5991    public boolean isEphemeralApplication(String packageName, int userId) {
5992        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5993                "isEphemeral");
5994        if (DISABLE_EPHEMERAL_APPS) {
5995            return false;
5996        }
5997
5998        if (!isCallerSameApp(packageName)) {
5999            return false;
6000        }
6001        synchronized (mPackages) {
6002            PackageParser.Package pkg = mPackages.get(packageName);
6003            if (pkg != null) {
6004                return pkg.applicationInfo.isEphemeralApp();
6005            }
6006        }
6007        return false;
6008    }
6009
6010    @Override
6011    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6012        if (DISABLE_EPHEMERAL_APPS) {
6013            return null;
6014        }
6015
6016        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6017                "getCookie");
6018        if (!isCallerSameApp(packageName)) {
6019            return null;
6020        }
6021        synchronized (mPackages) {
6022            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6023                    packageName, userId);
6024        }
6025    }
6026
6027    @Override
6028    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6029        if (DISABLE_EPHEMERAL_APPS) {
6030            return true;
6031        }
6032
6033        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6034                "setCookie");
6035        if (!isCallerSameApp(packageName)) {
6036            return false;
6037        }
6038        synchronized (mPackages) {
6039            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6040                    packageName, cookie, userId);
6041        }
6042    }
6043
6044    @Override
6045    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6046        if (DISABLE_EPHEMERAL_APPS) {
6047            return null;
6048        }
6049
6050        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6051                "getEphemeralApplicationIcon");
6052        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
6053                "getEphemeralApplicationIcon");
6054        synchronized (mPackages) {
6055            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6056                    packageName, userId);
6057        }
6058    }
6059
6060    private boolean isCallerSameApp(String packageName) {
6061        PackageParser.Package pkg = mPackages.get(packageName);
6062        return pkg != null
6063                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6064    }
6065
6066    public List<ApplicationInfo> getPersistentApplications(int flags) {
6067        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6068
6069        // reader
6070        synchronized (mPackages) {
6071            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6072            final int userId = UserHandle.getCallingUserId();
6073            while (i.hasNext()) {
6074                final PackageParser.Package p = i.next();
6075                if (p.applicationInfo != null
6076                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
6077                        && (!mSafeMode || isSystemApp(p))) {
6078                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6079                    if (ps != null) {
6080                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6081                                ps.readUserState(userId), userId);
6082                        if (ai != null) {
6083                            finalList.add(ai);
6084                        }
6085                    }
6086                }
6087            }
6088        }
6089
6090        return finalList;
6091    }
6092
6093    @Override
6094    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6095        if (!sUserManager.exists(userId)) return null;
6096        flags = updateFlagsForComponent(flags, userId, name);
6097        // reader
6098        synchronized (mPackages) {
6099            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6100            PackageSetting ps = provider != null
6101                    ? mSettings.mPackages.get(provider.owner.packageName)
6102                    : null;
6103            return ps != null
6104                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6105                    ? PackageParser.generateProviderInfo(provider, flags,
6106                            ps.readUserState(userId), userId)
6107                    : null;
6108        }
6109    }
6110
6111    /**
6112     * @deprecated
6113     */
6114    @Deprecated
6115    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6116        // reader
6117        synchronized (mPackages) {
6118            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6119                    .entrySet().iterator();
6120            final int userId = UserHandle.getCallingUserId();
6121            while (i.hasNext()) {
6122                Map.Entry<String, PackageParser.Provider> entry = i.next();
6123                PackageParser.Provider p = entry.getValue();
6124                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6125
6126                if (ps != null && p.syncable
6127                        && (!mSafeMode || (p.info.applicationInfo.flags
6128                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6129                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6130                            ps.readUserState(userId), userId);
6131                    if (info != null) {
6132                        outNames.add(entry.getKey());
6133                        outInfo.add(info);
6134                    }
6135                }
6136            }
6137        }
6138    }
6139
6140    @Override
6141    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6142            int uid, int flags) {
6143        final int userId = processName != null ? UserHandle.getUserId(uid)
6144                : UserHandle.getCallingUserId();
6145        if (!sUserManager.exists(userId)) return null;
6146        flags = updateFlagsForComponent(flags, userId, processName);
6147
6148        ArrayList<ProviderInfo> finalList = null;
6149        // reader
6150        synchronized (mPackages) {
6151            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6152            while (i.hasNext()) {
6153                final PackageParser.Provider p = i.next();
6154                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6155                if (ps != null && p.info.authority != null
6156                        && (processName == null
6157                                || (p.info.processName.equals(processName)
6158                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6159                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6160                    if (finalList == null) {
6161                        finalList = new ArrayList<ProviderInfo>(3);
6162                    }
6163                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6164                            ps.readUserState(userId), userId);
6165                    if (info != null) {
6166                        finalList.add(info);
6167                    }
6168                }
6169            }
6170        }
6171
6172        if (finalList != null) {
6173            Collections.sort(finalList, mProviderInitOrderSorter);
6174            return new ParceledListSlice<ProviderInfo>(finalList);
6175        }
6176
6177        return null;
6178    }
6179
6180    @Override
6181    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6182        // reader
6183        synchronized (mPackages) {
6184            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6185            return PackageParser.generateInstrumentationInfo(i, flags);
6186        }
6187    }
6188
6189    @Override
6190    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6191            int flags) {
6192        ArrayList<InstrumentationInfo> finalList =
6193            new ArrayList<InstrumentationInfo>();
6194
6195        // reader
6196        synchronized (mPackages) {
6197            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6198            while (i.hasNext()) {
6199                final PackageParser.Instrumentation p = i.next();
6200                if (targetPackage == null
6201                        || targetPackage.equals(p.info.targetPackage)) {
6202                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6203                            flags);
6204                    if (ii != null) {
6205                        finalList.add(ii);
6206                    }
6207                }
6208            }
6209        }
6210
6211        return finalList;
6212    }
6213
6214    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6215        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6216        if (overlays == null) {
6217            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6218            return;
6219        }
6220        for (PackageParser.Package opkg : overlays.values()) {
6221            // Not much to do if idmap fails: we already logged the error
6222            // and we certainly don't want to abort installation of pkg simply
6223            // because an overlay didn't fit properly. For these reasons,
6224            // ignore the return value of createIdmapForPackagePairLI.
6225            createIdmapForPackagePairLI(pkg, opkg);
6226        }
6227    }
6228
6229    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6230            PackageParser.Package opkg) {
6231        if (!opkg.mTrustedOverlay) {
6232            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6233                    opkg.baseCodePath + ": overlay not trusted");
6234            return false;
6235        }
6236        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6237        if (overlaySet == null) {
6238            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6239                    opkg.baseCodePath + " but target package has no known overlays");
6240            return false;
6241        }
6242        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6243        // TODO: generate idmap for split APKs
6244        try {
6245            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6246        } catch (InstallerException e) {
6247            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6248                    + opkg.baseCodePath);
6249            return false;
6250        }
6251        PackageParser.Package[] overlayArray =
6252            overlaySet.values().toArray(new PackageParser.Package[0]);
6253        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6254            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6255                return p1.mOverlayPriority - p2.mOverlayPriority;
6256            }
6257        };
6258        Arrays.sort(overlayArray, cmp);
6259
6260        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6261        int i = 0;
6262        for (PackageParser.Package p : overlayArray) {
6263            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6264        }
6265        return true;
6266    }
6267
6268    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6269        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6270        try {
6271            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6272        } finally {
6273            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6274        }
6275    }
6276
6277    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6278        final File[] files = dir.listFiles();
6279        if (ArrayUtils.isEmpty(files)) {
6280            Log.d(TAG, "No files in app dir " + dir);
6281            return;
6282        }
6283
6284        if (DEBUG_PACKAGE_SCANNING) {
6285            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6286                    + " flags=0x" + Integer.toHexString(parseFlags));
6287        }
6288
6289        for (File file : files) {
6290            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6291                    && !PackageInstallerService.isStageName(file.getName());
6292            if (!isPackage) {
6293                // Ignore entries which are not packages
6294                continue;
6295            }
6296            try {
6297                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6298                        scanFlags, currentTime, null);
6299            } catch (PackageManagerException e) {
6300                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6301
6302                // Delete invalid userdata apps
6303                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6304                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6305                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6306                    removeCodePathLI(file);
6307                }
6308            }
6309        }
6310    }
6311
6312    private static File getSettingsProblemFile() {
6313        File dataDir = Environment.getDataDirectory();
6314        File systemDir = new File(dataDir, "system");
6315        File fname = new File(systemDir, "uiderrors.txt");
6316        return fname;
6317    }
6318
6319    static void reportSettingsProblem(int priority, String msg) {
6320        logCriticalInfo(priority, msg);
6321    }
6322
6323    static void logCriticalInfo(int priority, String msg) {
6324        Slog.println(priority, TAG, msg);
6325        EventLogTags.writePmCriticalInfo(msg);
6326        try {
6327            File fname = getSettingsProblemFile();
6328            FileOutputStream out = new FileOutputStream(fname, true);
6329            PrintWriter pw = new FastPrintWriter(out);
6330            SimpleDateFormat formatter = new SimpleDateFormat();
6331            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6332            pw.println(dateString + ": " + msg);
6333            pw.close();
6334            FileUtils.setPermissions(
6335                    fname.toString(),
6336                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6337                    -1, -1);
6338        } catch (java.io.IOException e) {
6339        }
6340    }
6341
6342    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6343            int parseFlags) throws PackageManagerException {
6344        if (ps != null
6345                && ps.codePath.equals(srcFile)
6346                && ps.timeStamp == srcFile.lastModified()
6347                && !isCompatSignatureUpdateNeeded(pkg)
6348                && !isRecoverSignatureUpdateNeeded(pkg)) {
6349            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6350            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6351            ArraySet<PublicKey> signingKs;
6352            synchronized (mPackages) {
6353                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6354            }
6355            if (ps.signatures.mSignatures != null
6356                    && ps.signatures.mSignatures.length != 0
6357                    && signingKs != null) {
6358                // Optimization: reuse the existing cached certificates
6359                // if the package appears to be unchanged.
6360                pkg.mSignatures = ps.signatures.mSignatures;
6361                pkg.mSigningKeys = signingKs;
6362                return;
6363            }
6364
6365            Slog.w(TAG, "PackageSetting for " + ps.name
6366                    + " is missing signatures.  Collecting certs again to recover them.");
6367        } else {
6368            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6369        }
6370
6371        try {
6372            PackageParser.collectCertificates(pkg, parseFlags);
6373        } catch (PackageParserException e) {
6374            throw PackageManagerException.from(e);
6375        }
6376    }
6377
6378    /**
6379     *  Traces a package scan.
6380     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6381     */
6382    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6383            long currentTime, UserHandle user) throws PackageManagerException {
6384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6385        try {
6386            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6387        } finally {
6388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6389        }
6390    }
6391
6392    /**
6393     *  Scans a package and returns the newly parsed package.
6394     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6395     */
6396    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6397            long currentTime, UserHandle user) throws PackageManagerException {
6398        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6399        parseFlags |= mDefParseFlags;
6400        PackageParser pp = new PackageParser();
6401        pp.setSeparateProcesses(mSeparateProcesses);
6402        pp.setOnlyCoreApps(mOnlyCore);
6403        pp.setDisplayMetrics(mMetrics);
6404
6405        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6406            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6407        }
6408
6409        final PackageParser.Package pkg;
6410        try {
6411            pkg = pp.parsePackage(scanFile, parseFlags);
6412        } catch (PackageParserException e) {
6413            throw PackageManagerException.from(e);
6414        }
6415
6416        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6417    }
6418
6419    /**
6420     *  Scans a package and returns the newly parsed package.
6421     *  @throws PackageManagerException on a parse error.
6422     */
6423    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6424            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6425            throws PackageManagerException {
6426        // If the package has children and this is the first dive in the function
6427        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6428        // packages (parent and children) would be successfully scanned before the
6429        // actual scan since scanning mutates internal state and we want to atomically
6430        // install the package and its children.
6431        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6432            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6433                scanFlags |= SCAN_CHECK_ONLY;
6434            }
6435        } else {
6436            scanFlags &= ~SCAN_CHECK_ONLY;
6437        }
6438
6439        // Scan the parent
6440        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6441                scanFlags, currentTime, user);
6442
6443        // Scan the children
6444        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6445        for (int i = 0; i < childCount; i++) {
6446            PackageParser.Package childPackage = pkg.childPackages.get(i);
6447            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6448                    currentTime, user);
6449        }
6450
6451
6452        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6453            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6454        }
6455
6456        return scannedPkg;
6457    }
6458
6459    /**
6460     *  Scans a package and returns the newly parsed package.
6461     *  @throws PackageManagerException on a parse error.
6462     */
6463    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6464            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6465            throws PackageManagerException {
6466        PackageSetting ps = null;
6467        PackageSetting updatedPkg;
6468        // reader
6469        synchronized (mPackages) {
6470            // Look to see if we already know about this package.
6471            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6472            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6473                // This package has been renamed to its original name.  Let's
6474                // use that.
6475                ps = mSettings.peekPackageLPr(oldName);
6476            }
6477            // If there was no original package, see one for the real package name.
6478            if (ps == null) {
6479                ps = mSettings.peekPackageLPr(pkg.packageName);
6480            }
6481            // Check to see if this package could be hiding/updating a system
6482            // package.  Must look for it either under the original or real
6483            // package name depending on our state.
6484            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6485            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6486
6487            // If this is a package we don't know about on the system partition, we
6488            // may need to remove disabled child packages on the system partition
6489            // or may need to not add child packages if the parent apk is updated
6490            // on the data partition and no longer defines this child package.
6491            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6492                // If this is a parent package for an updated system app and this system
6493                // app got an OTA update which no longer defines some of the child packages
6494                // we have to prune them from the disabled system packages.
6495                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6496                if (disabledPs != null) {
6497                    final int scannedChildCount = (pkg.childPackages != null)
6498                            ? pkg.childPackages.size() : 0;
6499                    final int disabledChildCount = disabledPs.childPackageNames != null
6500                            ? disabledPs.childPackageNames.size() : 0;
6501                    for (int i = 0; i < disabledChildCount; i++) {
6502                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6503                        boolean disabledPackageAvailable = false;
6504                        for (int j = 0; j < scannedChildCount; j++) {
6505                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6506                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6507                                disabledPackageAvailable = true;
6508                                break;
6509                            }
6510                         }
6511                         if (!disabledPackageAvailable) {
6512                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6513                         }
6514                    }
6515                }
6516            }
6517        }
6518
6519        boolean updatedPkgBetter = false;
6520        // First check if this is a system package that may involve an update
6521        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6522            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6523            // it needs to drop FLAG_PRIVILEGED.
6524            if (locationIsPrivileged(scanFile)) {
6525                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6526            } else {
6527                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6528            }
6529
6530            if (ps != null && !ps.codePath.equals(scanFile)) {
6531                // The path has changed from what was last scanned...  check the
6532                // version of the new path against what we have stored to determine
6533                // what to do.
6534                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6535                if (pkg.mVersionCode <= ps.versionCode) {
6536                    // The system package has been updated and the code path does not match
6537                    // Ignore entry. Skip it.
6538                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6539                            + " ignored: updated version " + ps.versionCode
6540                            + " better than this " + pkg.mVersionCode);
6541                    if (!updatedPkg.codePath.equals(scanFile)) {
6542                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6543                                + ps.name + " changing from " + updatedPkg.codePathString
6544                                + " to " + scanFile);
6545                        updatedPkg.codePath = scanFile;
6546                        updatedPkg.codePathString = scanFile.toString();
6547                        updatedPkg.resourcePath = scanFile;
6548                        updatedPkg.resourcePathString = scanFile.toString();
6549                    }
6550                    updatedPkg.pkg = pkg;
6551                    updatedPkg.versionCode = pkg.mVersionCode;
6552
6553                    // Update the disabled system child packages to point to the package too.
6554                    final int childCount = updatedPkg.childPackageNames != null
6555                            ? updatedPkg.childPackageNames.size() : 0;
6556                    for (int i = 0; i < childCount; i++) {
6557                        String childPackageName = updatedPkg.childPackageNames.get(i);
6558                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6559                                childPackageName);
6560                        if (updatedChildPkg != null) {
6561                            updatedChildPkg.pkg = pkg;
6562                            updatedChildPkg.versionCode = pkg.mVersionCode;
6563                        }
6564                    }
6565
6566                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6567                            + scanFile + " ignored: updated version " + ps.versionCode
6568                            + " better than this " + pkg.mVersionCode);
6569                } else {
6570                    // The current app on the system partition is better than
6571                    // what we have updated to on the data partition; switch
6572                    // back to the system partition version.
6573                    // At this point, its safely assumed that package installation for
6574                    // apps in system partition will go through. If not there won't be a working
6575                    // version of the app
6576                    // writer
6577                    synchronized (mPackages) {
6578                        // Just remove the loaded entries from package lists.
6579                        mPackages.remove(ps.name);
6580                    }
6581
6582                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6583                            + " reverting from " + ps.codePathString
6584                            + ": new version " + pkg.mVersionCode
6585                            + " better than installed " + ps.versionCode);
6586
6587                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6588                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6589                    synchronized (mInstallLock) {
6590                        args.cleanUpResourcesLI();
6591                    }
6592                    synchronized (mPackages) {
6593                        mSettings.enableSystemPackageLPw(ps.name);
6594                    }
6595                    updatedPkgBetter = true;
6596                }
6597            }
6598        }
6599
6600        if (updatedPkg != null) {
6601            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6602            // initially
6603            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6604
6605            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6606            // flag set initially
6607            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6608                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6609            }
6610        }
6611
6612        // Verify certificates against what was last scanned
6613        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6614
6615        /*
6616         * A new system app appeared, but we already had a non-system one of the
6617         * same name installed earlier.
6618         */
6619        boolean shouldHideSystemApp = false;
6620        if (updatedPkg == null && ps != null
6621                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6622            /*
6623             * Check to make sure the signatures match first. If they don't,
6624             * wipe the installed application and its data.
6625             */
6626            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6627                    != PackageManager.SIGNATURE_MATCH) {
6628                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6629                        + " signatures don't match existing userdata copy; removing");
6630                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6631                ps = null;
6632            } else {
6633                /*
6634                 * If the newly-added system app is an older version than the
6635                 * already installed version, hide it. It will be scanned later
6636                 * and re-added like an update.
6637                 */
6638                if (pkg.mVersionCode <= ps.versionCode) {
6639                    shouldHideSystemApp = true;
6640                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6641                            + " but new version " + pkg.mVersionCode + " better than installed "
6642                            + ps.versionCode + "; hiding system");
6643                } else {
6644                    /*
6645                     * The newly found system app is a newer version that the
6646                     * one previously installed. Simply remove the
6647                     * already-installed application and replace it with our own
6648                     * while keeping the application data.
6649                     */
6650                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6651                            + " reverting from " + ps.codePathString + ": new version "
6652                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6653                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6654                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6655                    synchronized (mInstallLock) {
6656                        args.cleanUpResourcesLI();
6657                    }
6658                }
6659            }
6660        }
6661
6662        // The apk is forward locked (not public) if its code and resources
6663        // are kept in different files. (except for app in either system or
6664        // vendor path).
6665        // TODO grab this value from PackageSettings
6666        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6667            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6668                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6669            }
6670        }
6671
6672        // TODO: extend to support forward-locked splits
6673        String resourcePath = null;
6674        String baseResourcePath = null;
6675        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6676            if (ps != null && ps.resourcePathString != null) {
6677                resourcePath = ps.resourcePathString;
6678                baseResourcePath = ps.resourcePathString;
6679            } else {
6680                // Should not happen at all. Just log an error.
6681                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6682            }
6683        } else {
6684            resourcePath = pkg.codePath;
6685            baseResourcePath = pkg.baseCodePath;
6686        }
6687
6688        // Set application objects path explicitly.
6689        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6690        pkg.setApplicationInfoCodePath(pkg.codePath);
6691        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6692        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6693        pkg.setApplicationInfoResourcePath(resourcePath);
6694        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6695        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6696
6697        // Note that we invoke the following method only if we are about to unpack an application
6698        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6699                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6700
6701        /*
6702         * If the system app should be overridden by a previously installed
6703         * data, hide the system app now and let the /data/app scan pick it up
6704         * again.
6705         */
6706        if (shouldHideSystemApp) {
6707            synchronized (mPackages) {
6708                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6709            }
6710        }
6711
6712        return scannedPkg;
6713    }
6714
6715    private static String fixProcessName(String defProcessName,
6716            String processName, int uid) {
6717        if (processName == null) {
6718            return defProcessName;
6719        }
6720        return processName;
6721    }
6722
6723    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6724            throws PackageManagerException {
6725        if (pkgSetting.signatures.mSignatures != null) {
6726            // Already existing package. Make sure signatures match
6727            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6728                    == PackageManager.SIGNATURE_MATCH;
6729            if (!match) {
6730                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6731                        == PackageManager.SIGNATURE_MATCH;
6732            }
6733            if (!match) {
6734                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6735                        == PackageManager.SIGNATURE_MATCH;
6736            }
6737            if (!match) {
6738                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6739                        + pkg.packageName + " signatures do not match the "
6740                        + "previously installed version; ignoring!");
6741            }
6742        }
6743
6744        // Check for shared user signatures
6745        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6746            // Already existing package. Make sure signatures match
6747            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6748                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6749            if (!match) {
6750                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6751                        == PackageManager.SIGNATURE_MATCH;
6752            }
6753            if (!match) {
6754                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6755                        == PackageManager.SIGNATURE_MATCH;
6756            }
6757            if (!match) {
6758                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6759                        "Package " + pkg.packageName
6760                        + " has no signatures that match those in shared user "
6761                        + pkgSetting.sharedUser.name + "; ignoring!");
6762            }
6763        }
6764    }
6765
6766    /**
6767     * Enforces that only the system UID or root's UID can call a method exposed
6768     * via Binder.
6769     *
6770     * @param message used as message if SecurityException is thrown
6771     * @throws SecurityException if the caller is not system or root
6772     */
6773    private static final void enforceSystemOrRoot(String message) {
6774        final int uid = Binder.getCallingUid();
6775        if (uid != Process.SYSTEM_UID && uid != 0) {
6776            throw new SecurityException(message);
6777        }
6778    }
6779
6780    @Override
6781    public void performFstrimIfNeeded() {
6782        enforceSystemOrRoot("Only the system can request fstrim");
6783
6784        // Before everything else, see whether we need to fstrim.
6785        try {
6786            IMountService ms = PackageHelper.getMountService();
6787            if (ms != null) {
6788                final boolean isUpgrade = isUpgrade();
6789                boolean doTrim = isUpgrade;
6790                if (doTrim) {
6791                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6792                } else {
6793                    final long interval = android.provider.Settings.Global.getLong(
6794                            mContext.getContentResolver(),
6795                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6796                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6797                    if (interval > 0) {
6798                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6799                        if (timeSinceLast > interval) {
6800                            doTrim = true;
6801                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6802                                    + "; running immediately");
6803                        }
6804                    }
6805                }
6806                if (doTrim) {
6807                    if (!isFirstBoot()) {
6808                        try {
6809                            ActivityManagerNative.getDefault().showBootMessage(
6810                                    mContext.getResources().getString(
6811                                            R.string.android_upgrading_fstrim), true);
6812                        } catch (RemoteException e) {
6813                        }
6814                    }
6815                    ms.runMaintenance();
6816                }
6817            } else {
6818                Slog.e(TAG, "Mount service unavailable!");
6819            }
6820        } catch (RemoteException e) {
6821            // Can't happen; MountService is local
6822        }
6823    }
6824
6825    @Override
6826    public void extractPackagesIfNeeded() {
6827        enforceSystemOrRoot("Only the system can request package extraction");
6828
6829        // Extract pacakges only if profile-guided compilation is enabled because
6830        // otherwise BackgroundDexOptService will not dexopt them later.
6831        if (mUseJitProfiles) {
6832            List<PackageParser.Package> pkgs;
6833            synchronized (mPackages) {
6834                pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6835            }
6836            for (PackageParser.Package pkg : pkgs) {
6837                if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6838                    performDexOpt(pkg.packageName, null /* instructionSet */,
6839                             false /* useProfiles */, true /* extractOnly */, false /* force */);
6840                }
6841            }
6842        }
6843    }
6844
6845    @Override
6846    public void notifyPackageUse(String packageName) {
6847        synchronized (mPackages) {
6848            PackageParser.Package p = mPackages.get(packageName);
6849            if (p == null) {
6850                return;
6851            }
6852            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6853        }
6854    }
6855
6856    // TODO: this is not used nor needed. Delete it.
6857    @Override
6858    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6859        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6860                false /* extractOnly */, false /* force */);
6861    }
6862
6863    @Override
6864    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6865            boolean extractOnly, boolean force) {
6866        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6867    }
6868
6869    private boolean performDexOptTraced(String packageName, String instructionSet,
6870                boolean useProfiles, boolean extractOnly, boolean force) {
6871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6872        try {
6873            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6874                    force);
6875        } finally {
6876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6877        }
6878    }
6879
6880    private boolean performDexOptInternal(String packageName, String instructionSet,
6881                boolean useProfiles, boolean extractOnly, boolean force) {
6882        PackageParser.Package p;
6883        final String targetInstructionSet;
6884        synchronized (mPackages) {
6885            p = mPackages.get(packageName);
6886            if (p == null) {
6887                return false;
6888            }
6889            mPackageUsage.write(false);
6890
6891            targetInstructionSet = instructionSet != null ? instructionSet :
6892                    getPrimaryInstructionSet(p.applicationInfo);
6893            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6894                // Skip only if we do not use profiles since they might trigger a recompilation.
6895                return false;
6896            }
6897        }
6898        long callingId = Binder.clearCallingIdentity();
6899        try {
6900            synchronized (mInstallLock) {
6901                final String[] instructionSets = new String[] { targetInstructionSet };
6902                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6903                        useProfiles, extractOnly, force);
6904                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6905            }
6906        } finally {
6907            Binder.restoreCallingIdentity(callingId);
6908        }
6909    }
6910
6911    public ArraySet<String> getOptimizablePackages() {
6912        ArraySet<String> pkgs = new ArraySet<String>();
6913        synchronized (mPackages) {
6914            for (PackageParser.Package p : mPackages.values()) {
6915                if (PackageDexOptimizer.canOptimizePackage(p)) {
6916                    pkgs.add(p.packageName);
6917                }
6918            }
6919        }
6920        return pkgs;
6921    }
6922
6923    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6924            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6925        // Select the dex optimizer based on the force parameter.
6926        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6927        //       allocate an object here.
6928        PackageDexOptimizer pdo = force
6929                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6930                : mPackageDexOptimizer;
6931
6932        // Optimize all dependencies first. Note: we ignore the return value and march on
6933        // on errors.
6934        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6935        if (!deps.isEmpty()) {
6936            for (PackageParser.Package depPackage : deps) {
6937                // TODO: Analyze and investigate if we (should) profile libraries.
6938                // Currently this will do a full compilation of the library.
6939                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6940                        false /* extractOnly */);
6941            }
6942        }
6943
6944        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6945    }
6946
6947    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6948        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6949            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6950            Set<String> collectedNames = new HashSet<>();
6951            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6952
6953            retValue.remove(p);
6954
6955            return retValue;
6956        } else {
6957            return Collections.emptyList();
6958        }
6959    }
6960
6961    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6962            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6963        if (!collectedNames.contains(p.packageName)) {
6964            collectedNames.add(p.packageName);
6965            collected.add(p);
6966
6967            if (p.usesLibraries != null) {
6968                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6969            }
6970            if (p.usesOptionalLibraries != null) {
6971                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6972                        collectedNames);
6973            }
6974        }
6975    }
6976
6977    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6978            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6979        for (String libName : libs) {
6980            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6981            if (libPkg != null) {
6982                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6983            }
6984        }
6985    }
6986
6987    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6988        synchronized (mPackages) {
6989            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6990            if (lib != null && lib.apk != null) {
6991                return mPackages.get(lib.apk);
6992            }
6993        }
6994        return null;
6995    }
6996
6997    public void shutdown() {
6998        mPackageUsage.write(true);
6999    }
7000
7001    @Override
7002    public void forceDexOpt(String packageName) {
7003        enforceSystemOrRoot("forceDexOpt");
7004
7005        PackageParser.Package pkg;
7006        synchronized (mPackages) {
7007            pkg = mPackages.get(packageName);
7008            if (pkg == null) {
7009                throw new IllegalArgumentException("Unknown package: " + packageName);
7010            }
7011        }
7012
7013        synchronized (mInstallLock) {
7014            final String[] instructionSets = new String[] {
7015                    getPrimaryInstructionSet(pkg.applicationInfo) };
7016
7017            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7018
7019            // Whoever is calling forceDexOpt wants a fully compiled package.
7020            // Don't use profiles since that may cause compilation to be skipped.
7021            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7022                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7023
7024            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7025            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7026                throw new IllegalStateException("Failed to dexopt: " + res);
7027            }
7028        }
7029    }
7030
7031    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7032        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7033            Slog.w(TAG, "Unable to update from " + oldPkg.name
7034                    + " to " + newPkg.packageName
7035                    + ": old package not in system partition");
7036            return false;
7037        } else if (mPackages.get(oldPkg.name) != null) {
7038            Slog.w(TAG, "Unable to update from " + oldPkg.name
7039                    + " to " + newPkg.packageName
7040                    + ": old package still exists");
7041            return false;
7042        }
7043        return true;
7044    }
7045
7046    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7047        // TODO: triage flags as part of 26466827
7048        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7049
7050        boolean res = true;
7051        final int[] users = sUserManager.getUserIds();
7052        for (int user : users) {
7053            try {
7054                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7055            } catch (InstallerException e) {
7056                Slog.w(TAG, "Failed to delete data directory", e);
7057                res = false;
7058            }
7059        }
7060        return res;
7061    }
7062
7063    void removeCodePathLI(File codePath) {
7064        if (codePath.isDirectory()) {
7065            try {
7066                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7067            } catch (InstallerException e) {
7068                Slog.w(TAG, "Failed to remove code path", e);
7069            }
7070        } else {
7071            codePath.delete();
7072        }
7073    }
7074
7075    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7076        try {
7077            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7078        } catch (InstallerException e) {
7079            Slog.w(TAG, "Failed to destroy app data", e);
7080        }
7081    }
7082
7083    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7084            int appId, String seinfo) {
7085        try {
7086            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7087        } catch (InstallerException e) {
7088            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7089        }
7090    }
7091
7092    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7093        final PackageParser.Package pkg;
7094        synchronized (mPackages) {
7095            pkg = mPackages.get(packageName);
7096        }
7097        if (pkg == null) {
7098            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7099            return;
7100        }
7101        deleteCodeCacheDirsLI(pkg);
7102    }
7103
7104    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7105        // TODO: triage flags as part of 26466827
7106        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7107
7108        int[] users = sUserManager.getUserIds();
7109        int res = 0;
7110        for (int user : users) {
7111            // Remove the parent code cache
7112            try {
7113                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7114                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7115            } catch (InstallerException e) {
7116                Slog.w(TAG, "Failed to delete code cache directory", e);
7117            }
7118            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7119            for (int i = 0; i < childCount; i++) {
7120                PackageParser.Package childPkg = pkg.childPackages.get(i);
7121                // Remove the child code cache
7122                try {
7123                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7124                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7125                } catch (InstallerException e) {
7126                    Slog.w(TAG, "Failed to delete code cache directory", e);
7127                }
7128            }
7129        }
7130    }
7131
7132    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7133            long lastUpdateTime) {
7134        // Set parent install/update time
7135        PackageSetting ps = (PackageSetting) pkg.mExtras;
7136        if (ps != null) {
7137            ps.firstInstallTime = firstInstallTime;
7138            ps.lastUpdateTime = lastUpdateTime;
7139        }
7140        // Set children install/update time
7141        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7142        for (int i = 0; i < childCount; i++) {
7143            PackageParser.Package childPkg = pkg.childPackages.get(i);
7144            ps = (PackageSetting) childPkg.mExtras;
7145            if (ps != null) {
7146                ps.firstInstallTime = firstInstallTime;
7147                ps.lastUpdateTime = lastUpdateTime;
7148            }
7149        }
7150    }
7151
7152    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7153            PackageParser.Package changingLib) {
7154        if (file.path != null) {
7155            usesLibraryFiles.add(file.path);
7156            return;
7157        }
7158        PackageParser.Package p = mPackages.get(file.apk);
7159        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7160            // If we are doing this while in the middle of updating a library apk,
7161            // then we need to make sure to use that new apk for determining the
7162            // dependencies here.  (We haven't yet finished committing the new apk
7163            // to the package manager state.)
7164            if (p == null || p.packageName.equals(changingLib.packageName)) {
7165                p = changingLib;
7166            }
7167        }
7168        if (p != null) {
7169            usesLibraryFiles.addAll(p.getAllCodePaths());
7170        }
7171    }
7172
7173    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7174            PackageParser.Package changingLib) throws PackageManagerException {
7175        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7176            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7177            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7178            for (int i=0; i<N; i++) {
7179                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7180                if (file == null) {
7181                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7182                            "Package " + pkg.packageName + " requires unavailable shared library "
7183                            + pkg.usesLibraries.get(i) + "; failing!");
7184                }
7185                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7186            }
7187            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7188            for (int i=0; i<N; i++) {
7189                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7190                if (file == null) {
7191                    Slog.w(TAG, "Package " + pkg.packageName
7192                            + " desires unavailable shared library "
7193                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7194                } else {
7195                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7196                }
7197            }
7198            N = usesLibraryFiles.size();
7199            if (N > 0) {
7200                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7201            } else {
7202                pkg.usesLibraryFiles = null;
7203            }
7204        }
7205    }
7206
7207    private static boolean hasString(List<String> list, List<String> which) {
7208        if (list == null) {
7209            return false;
7210        }
7211        for (int i=list.size()-1; i>=0; i--) {
7212            for (int j=which.size()-1; j>=0; j--) {
7213                if (which.get(j).equals(list.get(i))) {
7214                    return true;
7215                }
7216            }
7217        }
7218        return false;
7219    }
7220
7221    private void updateAllSharedLibrariesLPw() {
7222        for (PackageParser.Package pkg : mPackages.values()) {
7223            try {
7224                updateSharedLibrariesLPw(pkg, null);
7225            } catch (PackageManagerException e) {
7226                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7227            }
7228        }
7229    }
7230
7231    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7232            PackageParser.Package changingPkg) {
7233        ArrayList<PackageParser.Package> res = null;
7234        for (PackageParser.Package pkg : mPackages.values()) {
7235            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7236                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7237                if (res == null) {
7238                    res = new ArrayList<PackageParser.Package>();
7239                }
7240                res.add(pkg);
7241                try {
7242                    updateSharedLibrariesLPw(pkg, changingPkg);
7243                } catch (PackageManagerException e) {
7244                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7245                }
7246            }
7247        }
7248        return res;
7249    }
7250
7251    /**
7252     * Derive the value of the {@code cpuAbiOverride} based on the provided
7253     * value and an optional stored value from the package settings.
7254     */
7255    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7256        String cpuAbiOverride = null;
7257
7258        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7259            cpuAbiOverride = null;
7260        } else if (abiOverride != null) {
7261            cpuAbiOverride = abiOverride;
7262        } else if (settings != null) {
7263            cpuAbiOverride = settings.cpuAbiOverrideString;
7264        }
7265
7266        return cpuAbiOverride;
7267    }
7268
7269    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7270            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7271        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7272        // If the package has children and this is the first dive in the function
7273        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7274        // whether all packages (parent and children) would be successfully scanned
7275        // before the actual scan since scanning mutates internal state and we want
7276        // to atomically install the package and its children.
7277        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7278            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7279                scanFlags |= SCAN_CHECK_ONLY;
7280            }
7281        } else {
7282            scanFlags &= ~SCAN_CHECK_ONLY;
7283        }
7284
7285        final PackageParser.Package scannedPkg;
7286        try {
7287            // Scan the parent
7288            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7289            // Scan the children
7290            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7291            for (int i = 0; i < childCount; i++) {
7292                PackageParser.Package childPkg = pkg.childPackages.get(i);
7293                scanPackageLI(childPkg, parseFlags,
7294                        scanFlags, currentTime, user);
7295            }
7296        } finally {
7297            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7298        }
7299
7300        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7301            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7302        }
7303
7304        return scannedPkg;
7305    }
7306
7307    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7308            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7309        boolean success = false;
7310        try {
7311            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7312                    currentTime, user);
7313            success = true;
7314            return res;
7315        } finally {
7316            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7317                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7318            }
7319        }
7320    }
7321
7322    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7323            int scanFlags, long currentTime, UserHandle user)
7324            throws PackageManagerException {
7325        final File scanFile = new File(pkg.codePath);
7326        if (pkg.applicationInfo.getCodePath() == null ||
7327                pkg.applicationInfo.getResourcePath() == null) {
7328            // Bail out. The resource and code paths haven't been set.
7329            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7330                    "Code and resource paths haven't been set correctly");
7331        }
7332
7333        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7334            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7335        } else {
7336            // Only allow system apps to be flagged as core apps.
7337            pkg.coreApp = false;
7338        }
7339
7340        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7341            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7342        }
7343
7344        if (mCustomResolverComponentName != null &&
7345                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7346            setUpCustomResolverActivity(pkg);
7347        }
7348
7349        if (pkg.packageName.equals("android")) {
7350            synchronized (mPackages) {
7351                if (mAndroidApplication != null) {
7352                    Slog.w(TAG, "*************************************************");
7353                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7354                    Slog.w(TAG, " file=" + scanFile);
7355                    Slog.w(TAG, "*************************************************");
7356                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7357                            "Core android package being redefined.  Skipping.");
7358                }
7359
7360                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7361                    // Set up information for our fall-back user intent resolution activity.
7362                    mPlatformPackage = pkg;
7363                    pkg.mVersionCode = mSdkVersion;
7364                    mAndroidApplication = pkg.applicationInfo;
7365
7366                    if (!mResolverReplaced) {
7367                        mResolveActivity.applicationInfo = mAndroidApplication;
7368                        mResolveActivity.name = ResolverActivity.class.getName();
7369                        mResolveActivity.packageName = mAndroidApplication.packageName;
7370                        mResolveActivity.processName = "system:ui";
7371                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7372                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7373                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7374                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7375                        mResolveActivity.exported = true;
7376                        mResolveActivity.enabled = true;
7377                        mResolveInfo.activityInfo = mResolveActivity;
7378                        mResolveInfo.priority = 0;
7379                        mResolveInfo.preferredOrder = 0;
7380                        mResolveInfo.match = 0;
7381                        mResolveComponentName = new ComponentName(
7382                                mAndroidApplication.packageName, mResolveActivity.name);
7383                    }
7384                }
7385            }
7386        }
7387
7388        if (DEBUG_PACKAGE_SCANNING) {
7389            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7390                Log.d(TAG, "Scanning package " + pkg.packageName);
7391        }
7392
7393        synchronized (mPackages) {
7394            if (mPackages.containsKey(pkg.packageName)
7395                    || mSharedLibraries.containsKey(pkg.packageName)) {
7396                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7397                        "Application package " + pkg.packageName
7398                                + " already installed.  Skipping duplicate.");
7399            }
7400
7401            // If we're only installing presumed-existing packages, require that the
7402            // scanned APK is both already known and at the path previously established
7403            // for it.  Previously unknown packages we pick up normally, but if we have an
7404            // a priori expectation about this package's install presence, enforce it.
7405            // With a singular exception for new system packages. When an OTA contains
7406            // a new system package, we allow the codepath to change from a system location
7407            // to the user-installed location. If we don't allow this change, any newer,
7408            // user-installed version of the application will be ignored.
7409            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7410                if (mExpectingBetter.containsKey(pkg.packageName)) {
7411                    logCriticalInfo(Log.WARN,
7412                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7413                } else {
7414                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7415                    if (known != null) {
7416                        if (DEBUG_PACKAGE_SCANNING) {
7417                            Log.d(TAG, "Examining " + pkg.codePath
7418                                    + " and requiring known paths " + known.codePathString
7419                                    + " & " + known.resourcePathString);
7420                        }
7421                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7422                                || !pkg.applicationInfo.getResourcePath().equals(
7423                                known.resourcePathString)) {
7424                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7425                                    "Application package " + pkg.packageName
7426                                            + " found at " + pkg.applicationInfo.getCodePath()
7427                                            + " but expected at " + known.codePathString
7428                                            + "; ignoring.");
7429                        }
7430                    }
7431                }
7432            }
7433        }
7434
7435        // Initialize package source and resource directories
7436        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7437        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7438
7439        SharedUserSetting suid = null;
7440        PackageSetting pkgSetting = null;
7441
7442        if (!isSystemApp(pkg)) {
7443            // Only system apps can use these features.
7444            pkg.mOriginalPackages = null;
7445            pkg.mRealPackage = null;
7446            pkg.mAdoptPermissions = null;
7447        }
7448
7449        // Getting the package setting may have a side-effect, so if we
7450        // are only checking if scan would succeed, stash a copy of the
7451        // old setting to restore at the end.
7452        PackageSetting nonMutatedPs = null;
7453
7454        // writer
7455        synchronized (mPackages) {
7456            if (pkg.mSharedUserId != null) {
7457                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7458                if (suid == null) {
7459                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7460                            "Creating application package " + pkg.packageName
7461                            + " for shared user failed");
7462                }
7463                if (DEBUG_PACKAGE_SCANNING) {
7464                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7465                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7466                                + "): packages=" + suid.packages);
7467                }
7468            }
7469
7470            // Check if we are renaming from an original package name.
7471            PackageSetting origPackage = null;
7472            String realName = null;
7473            if (pkg.mOriginalPackages != null) {
7474                // This package may need to be renamed to a previously
7475                // installed name.  Let's check on that...
7476                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7477                if (pkg.mOriginalPackages.contains(renamed)) {
7478                    // This package had originally been installed as the
7479                    // original name, and we have already taken care of
7480                    // transitioning to the new one.  Just update the new
7481                    // one to continue using the old name.
7482                    realName = pkg.mRealPackage;
7483                    if (!pkg.packageName.equals(renamed)) {
7484                        // Callers into this function may have already taken
7485                        // care of renaming the package; only do it here if
7486                        // it is not already done.
7487                        pkg.setPackageName(renamed);
7488                    }
7489
7490                } else {
7491                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7492                        if ((origPackage = mSettings.peekPackageLPr(
7493                                pkg.mOriginalPackages.get(i))) != null) {
7494                            // We do have the package already installed under its
7495                            // original name...  should we use it?
7496                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7497                                // New package is not compatible with original.
7498                                origPackage = null;
7499                                continue;
7500                            } else if (origPackage.sharedUser != null) {
7501                                // Make sure uid is compatible between packages.
7502                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7503                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7504                                            + " to " + pkg.packageName + ": old uid "
7505                                            + origPackage.sharedUser.name
7506                                            + " differs from " + pkg.mSharedUserId);
7507                                    origPackage = null;
7508                                    continue;
7509                                }
7510                            } else {
7511                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7512                                        + pkg.packageName + " to old name " + origPackage.name);
7513                            }
7514                            break;
7515                        }
7516                    }
7517                }
7518            }
7519
7520            if (mTransferedPackages.contains(pkg.packageName)) {
7521                Slog.w(TAG, "Package " + pkg.packageName
7522                        + " was transferred to another, but its .apk remains");
7523            }
7524
7525            // See comments in nonMutatedPs declaration
7526            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7527                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7528                if (foundPs != null) {
7529                    nonMutatedPs = new PackageSetting(foundPs);
7530                }
7531            }
7532
7533            // Just create the setting, don't add it yet. For already existing packages
7534            // the PkgSetting exists already and doesn't have to be created.
7535            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7536                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7537                    pkg.applicationInfo.primaryCpuAbi,
7538                    pkg.applicationInfo.secondaryCpuAbi,
7539                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7540                    user, false);
7541            if (pkgSetting == null) {
7542                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7543                        "Creating application package " + pkg.packageName + " failed");
7544            }
7545
7546            if (pkgSetting.origPackage != null) {
7547                // If we are first transitioning from an original package,
7548                // fix up the new package's name now.  We need to do this after
7549                // looking up the package under its new name, so getPackageLP
7550                // can take care of fiddling things correctly.
7551                pkg.setPackageName(origPackage.name);
7552
7553                // File a report about this.
7554                String msg = "New package " + pkgSetting.realName
7555                        + " renamed to replace old package " + pkgSetting.name;
7556                reportSettingsProblem(Log.WARN, msg);
7557
7558                // Make a note of it.
7559                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7560                    mTransferedPackages.add(origPackage.name);
7561                }
7562
7563                // No longer need to retain this.
7564                pkgSetting.origPackage = null;
7565            }
7566
7567            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7568                // Make a note of it.
7569                mTransferedPackages.add(pkg.packageName);
7570            }
7571
7572            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7573                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7574            }
7575
7576            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7577                // Check all shared libraries and map to their actual file path.
7578                // We only do this here for apps not on a system dir, because those
7579                // are the only ones that can fail an install due to this.  We
7580                // will take care of the system apps by updating all of their
7581                // library paths after the scan is done.
7582                updateSharedLibrariesLPw(pkg, null);
7583            }
7584
7585            if (mFoundPolicyFile) {
7586                SELinuxMMAC.assignSeinfoValue(pkg);
7587            }
7588
7589            pkg.applicationInfo.uid = pkgSetting.appId;
7590            pkg.mExtras = pkgSetting;
7591            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7592                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7593                    // We just determined the app is signed correctly, so bring
7594                    // over the latest parsed certs.
7595                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7596                } else {
7597                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7598                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7599                                "Package " + pkg.packageName + " upgrade keys do not match the "
7600                                + "previously installed version");
7601                    } else {
7602                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7603                        String msg = "System package " + pkg.packageName
7604                            + " signature changed; retaining data.";
7605                        reportSettingsProblem(Log.WARN, msg);
7606                    }
7607                }
7608            } else {
7609                try {
7610                    verifySignaturesLP(pkgSetting, pkg);
7611                    // We just determined the app is signed correctly, so bring
7612                    // over the latest parsed certs.
7613                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7614                } catch (PackageManagerException e) {
7615                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7616                        throw e;
7617                    }
7618                    // The signature has changed, but this package is in the system
7619                    // image...  let's recover!
7620                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7621                    // However...  if this package is part of a shared user, but it
7622                    // doesn't match the signature of the shared user, let's fail.
7623                    // What this means is that you can't change the signatures
7624                    // associated with an overall shared user, which doesn't seem all
7625                    // that unreasonable.
7626                    if (pkgSetting.sharedUser != null) {
7627                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7628                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7629                            throw new PackageManagerException(
7630                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7631                                            "Signature mismatch for shared user: "
7632                                            + pkgSetting.sharedUser);
7633                        }
7634                    }
7635                    // File a report about this.
7636                    String msg = "System package " + pkg.packageName
7637                        + " signature changed; retaining data.";
7638                    reportSettingsProblem(Log.WARN, msg);
7639                }
7640            }
7641            // Verify that this new package doesn't have any content providers
7642            // that conflict with existing packages.  Only do this if the
7643            // package isn't already installed, since we don't want to break
7644            // things that are installed.
7645            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7646                final int N = pkg.providers.size();
7647                int i;
7648                for (i=0; i<N; i++) {
7649                    PackageParser.Provider p = pkg.providers.get(i);
7650                    if (p.info.authority != null) {
7651                        String names[] = p.info.authority.split(";");
7652                        for (int j = 0; j < names.length; j++) {
7653                            if (mProvidersByAuthority.containsKey(names[j])) {
7654                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7655                                final String otherPackageName =
7656                                        ((other != null && other.getComponentName() != null) ?
7657                                                other.getComponentName().getPackageName() : "?");
7658                                throw new PackageManagerException(
7659                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7660                                                "Can't install because provider name " + names[j]
7661                                                + " (in package " + pkg.applicationInfo.packageName
7662                                                + ") is already used by " + otherPackageName);
7663                            }
7664                        }
7665                    }
7666                }
7667            }
7668
7669            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7670                // This package wants to adopt ownership of permissions from
7671                // another package.
7672                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7673                    final String origName = pkg.mAdoptPermissions.get(i);
7674                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7675                    if (orig != null) {
7676                        if (verifyPackageUpdateLPr(orig, pkg)) {
7677                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7678                                    + pkg.packageName);
7679                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7680                        }
7681                    }
7682                }
7683            }
7684        }
7685
7686        final String pkgName = pkg.packageName;
7687
7688        final long scanFileTime = scanFile.lastModified();
7689        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7690        pkg.applicationInfo.processName = fixProcessName(
7691                pkg.applicationInfo.packageName,
7692                pkg.applicationInfo.processName,
7693                pkg.applicationInfo.uid);
7694
7695        if (pkg != mPlatformPackage) {
7696            // Get all of our default paths setup
7697            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7698        }
7699
7700        final String path = scanFile.getPath();
7701        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7702
7703        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7704            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7705
7706            // Some system apps still use directory structure for native libraries
7707            // in which case we might end up not detecting abi solely based on apk
7708            // structure. Try to detect abi based on directory structure.
7709            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7710                    pkg.applicationInfo.primaryCpuAbi == null) {
7711                setBundledAppAbisAndRoots(pkg, pkgSetting);
7712                setNativeLibraryPaths(pkg);
7713            }
7714
7715        } else {
7716            if ((scanFlags & SCAN_MOVE) != 0) {
7717                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7718                // but we already have this packages package info in the PackageSetting. We just
7719                // use that and derive the native library path based on the new codepath.
7720                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7721                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7722            }
7723
7724            // Set native library paths again. For moves, the path will be updated based on the
7725            // ABIs we've determined above. For non-moves, the path will be updated based on the
7726            // ABIs we determined during compilation, but the path will depend on the final
7727            // package path (after the rename away from the stage path).
7728            setNativeLibraryPaths(pkg);
7729        }
7730
7731        // This is a special case for the "system" package, where the ABI is
7732        // dictated by the zygote configuration (and init.rc). We should keep track
7733        // of this ABI so that we can deal with "normal" applications that run under
7734        // the same UID correctly.
7735        if (mPlatformPackage == pkg) {
7736            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7737                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7738        }
7739
7740        // If there's a mismatch between the abi-override in the package setting
7741        // and the abiOverride specified for the install. Warn about this because we
7742        // would've already compiled the app without taking the package setting into
7743        // account.
7744        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7745            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7746                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7747                        " for package " + pkg.packageName);
7748            }
7749        }
7750
7751        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7752        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7753        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7754
7755        // Copy the derived override back to the parsed package, so that we can
7756        // update the package settings accordingly.
7757        pkg.cpuAbiOverride = cpuAbiOverride;
7758
7759        if (DEBUG_ABI_SELECTION) {
7760            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7761                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7762                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7763        }
7764
7765        // Push the derived path down into PackageSettings so we know what to
7766        // clean up at uninstall time.
7767        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7768
7769        if (DEBUG_ABI_SELECTION) {
7770            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7771                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7772                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7773        }
7774
7775        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7776            // We don't do this here during boot because we can do it all
7777            // at once after scanning all existing packages.
7778            //
7779            // We also do this *before* we perform dexopt on this package, so that
7780            // we can avoid redundant dexopts, and also to make sure we've got the
7781            // code and package path correct.
7782            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7783                    pkg, true /* boot complete */);
7784        }
7785
7786        if (mFactoryTest && pkg.requestedPermissions.contains(
7787                android.Manifest.permission.FACTORY_TEST)) {
7788            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7789        }
7790
7791        ArrayList<PackageParser.Package> clientLibPkgs = null;
7792
7793        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7794            if (nonMutatedPs != null) {
7795                synchronized (mPackages) {
7796                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7797                }
7798            }
7799            return pkg;
7800        }
7801
7802        // Only privileged apps and updated privileged apps can add child packages.
7803        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7804            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7805                throw new PackageManagerException("Only privileged apps and updated "
7806                        + "privileged apps can add child packages. Ignoring package "
7807                        + pkg.packageName);
7808            }
7809            final int childCount = pkg.childPackages.size();
7810            for (int i = 0; i < childCount; i++) {
7811                PackageParser.Package childPkg = pkg.childPackages.get(i);
7812                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7813                        childPkg.packageName)) {
7814                    throw new PackageManagerException("Cannot override a child package of "
7815                            + "another disabled system app. Ignoring package " + pkg.packageName);
7816                }
7817            }
7818        }
7819
7820        // writer
7821        synchronized (mPackages) {
7822            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7823                // Only system apps can add new shared libraries.
7824                if (pkg.libraryNames != null) {
7825                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7826                        String name = pkg.libraryNames.get(i);
7827                        boolean allowed = false;
7828                        if (pkg.isUpdatedSystemApp()) {
7829                            // New library entries can only be added through the
7830                            // system image.  This is important to get rid of a lot
7831                            // of nasty edge cases: for example if we allowed a non-
7832                            // system update of the app to add a library, then uninstalling
7833                            // the update would make the library go away, and assumptions
7834                            // we made such as through app install filtering would now
7835                            // have allowed apps on the device which aren't compatible
7836                            // with it.  Better to just have the restriction here, be
7837                            // conservative, and create many fewer cases that can negatively
7838                            // impact the user experience.
7839                            final PackageSetting sysPs = mSettings
7840                                    .getDisabledSystemPkgLPr(pkg.packageName);
7841                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7842                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7843                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7844                                        allowed = true;
7845                                        break;
7846                                    }
7847                                }
7848                            }
7849                        } else {
7850                            allowed = true;
7851                        }
7852                        if (allowed) {
7853                            if (!mSharedLibraries.containsKey(name)) {
7854                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7855                            } else if (!name.equals(pkg.packageName)) {
7856                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7857                                        + name + " already exists; skipping");
7858                            }
7859                        } else {
7860                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7861                                    + name + " that is not declared on system image; skipping");
7862                        }
7863                    }
7864                    if ((scanFlags & SCAN_BOOTING) == 0) {
7865                        // If we are not booting, we need to update any applications
7866                        // that are clients of our shared library.  If we are booting,
7867                        // this will all be done once the scan is complete.
7868                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7869                    }
7870                }
7871            }
7872        }
7873
7874        // Request the ActivityManager to kill the process(only for existing packages)
7875        // so that we do not end up in a confused state while the user is still using the older
7876        // version of the application while the new one gets installed.
7877        if ((scanFlags & SCAN_REPLACING) != 0) {
7878            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7879
7880            killApplication(pkg.applicationInfo.packageName,
7881                        pkg.applicationInfo.uid, "replace pkg");
7882
7883            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7884        }
7885
7886        // Also need to kill any apps that are dependent on the library.
7887        if (clientLibPkgs != null) {
7888            for (int i=0; i<clientLibPkgs.size(); i++) {
7889                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7890                killApplication(clientPkg.applicationInfo.packageName,
7891                        clientPkg.applicationInfo.uid, "update lib");
7892            }
7893        }
7894
7895        // Make sure we're not adding any bogus keyset info
7896        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7897        ksms.assertScannedPackageValid(pkg);
7898
7899        // writer
7900        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7901
7902        boolean createIdmapFailed = false;
7903        synchronized (mPackages) {
7904            // We don't expect installation to fail beyond this point
7905
7906            // Add the new setting to mSettings
7907            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7908            // Add the new setting to mPackages
7909            mPackages.put(pkg.applicationInfo.packageName, pkg);
7910            // Make sure we don't accidentally delete its data.
7911            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7912            while (iter.hasNext()) {
7913                PackageCleanItem item = iter.next();
7914                if (pkgName.equals(item.packageName)) {
7915                    iter.remove();
7916                }
7917            }
7918
7919            // Take care of first install / last update times.
7920            if (currentTime != 0) {
7921                if (pkgSetting.firstInstallTime == 0) {
7922                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7923                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7924                    pkgSetting.lastUpdateTime = currentTime;
7925                }
7926            } else if (pkgSetting.firstInstallTime == 0) {
7927                // We need *something*.  Take time time stamp of the file.
7928                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7929            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7930                if (scanFileTime != pkgSetting.timeStamp) {
7931                    // A package on the system image has changed; consider this
7932                    // to be an update.
7933                    pkgSetting.lastUpdateTime = scanFileTime;
7934                }
7935            }
7936
7937            // Add the package's KeySets to the global KeySetManagerService
7938            ksms.addScannedPackageLPw(pkg);
7939
7940            int N = pkg.providers.size();
7941            StringBuilder r = null;
7942            int i;
7943            for (i=0; i<N; i++) {
7944                PackageParser.Provider p = pkg.providers.get(i);
7945                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7946                        p.info.processName, pkg.applicationInfo.uid);
7947                mProviders.addProvider(p);
7948                p.syncable = p.info.isSyncable;
7949                if (p.info.authority != null) {
7950                    String names[] = p.info.authority.split(";");
7951                    p.info.authority = null;
7952                    for (int j = 0; j < names.length; j++) {
7953                        if (j == 1 && p.syncable) {
7954                            // We only want the first authority for a provider to possibly be
7955                            // syncable, so if we already added this provider using a different
7956                            // authority clear the syncable flag. We copy the provider before
7957                            // changing it because the mProviders object contains a reference
7958                            // to a provider that we don't want to change.
7959                            // Only do this for the second authority since the resulting provider
7960                            // object can be the same for all future authorities for this provider.
7961                            p = new PackageParser.Provider(p);
7962                            p.syncable = false;
7963                        }
7964                        if (!mProvidersByAuthority.containsKey(names[j])) {
7965                            mProvidersByAuthority.put(names[j], p);
7966                            if (p.info.authority == null) {
7967                                p.info.authority = names[j];
7968                            } else {
7969                                p.info.authority = p.info.authority + ";" + names[j];
7970                            }
7971                            if (DEBUG_PACKAGE_SCANNING) {
7972                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7973                                    Log.d(TAG, "Registered content provider: " + names[j]
7974                                            + ", className = " + p.info.name + ", isSyncable = "
7975                                            + p.info.isSyncable);
7976                            }
7977                        } else {
7978                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7979                            Slog.w(TAG, "Skipping provider name " + names[j] +
7980                                    " (in package " + pkg.applicationInfo.packageName +
7981                                    "): name already used by "
7982                                    + ((other != null && other.getComponentName() != null)
7983                                            ? other.getComponentName().getPackageName() : "?"));
7984                        }
7985                    }
7986                }
7987                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7988                    if (r == null) {
7989                        r = new StringBuilder(256);
7990                    } else {
7991                        r.append(' ');
7992                    }
7993                    r.append(p.info.name);
7994                }
7995            }
7996            if (r != null) {
7997                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7998            }
7999
8000            N = pkg.services.size();
8001            r = null;
8002            for (i=0; i<N; i++) {
8003                PackageParser.Service s = pkg.services.get(i);
8004                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8005                        s.info.processName, pkg.applicationInfo.uid);
8006                mServices.addService(s);
8007                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8008                    if (r == null) {
8009                        r = new StringBuilder(256);
8010                    } else {
8011                        r.append(' ');
8012                    }
8013                    r.append(s.info.name);
8014                }
8015            }
8016            if (r != null) {
8017                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8018            }
8019
8020            N = pkg.receivers.size();
8021            r = null;
8022            for (i=0; i<N; i++) {
8023                PackageParser.Activity a = pkg.receivers.get(i);
8024                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8025                        a.info.processName, pkg.applicationInfo.uid);
8026                mReceivers.addActivity(a, "receiver");
8027                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8028                    if (r == null) {
8029                        r = new StringBuilder(256);
8030                    } else {
8031                        r.append(' ');
8032                    }
8033                    r.append(a.info.name);
8034                }
8035            }
8036            if (r != null) {
8037                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8038            }
8039
8040            N = pkg.activities.size();
8041            r = null;
8042            for (i=0; i<N; i++) {
8043                PackageParser.Activity a = pkg.activities.get(i);
8044                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8045                        a.info.processName, pkg.applicationInfo.uid);
8046                mActivities.addActivity(a, "activity");
8047                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8048                    if (r == null) {
8049                        r = new StringBuilder(256);
8050                    } else {
8051                        r.append(' ');
8052                    }
8053                    r.append(a.info.name);
8054                }
8055            }
8056            if (r != null) {
8057                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8058            }
8059
8060            N = pkg.permissionGroups.size();
8061            r = null;
8062            for (i=0; i<N; i++) {
8063                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8064                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8065                if (cur == null) {
8066                    mPermissionGroups.put(pg.info.name, pg);
8067                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8068                        if (r == null) {
8069                            r = new StringBuilder(256);
8070                        } else {
8071                            r.append(' ');
8072                        }
8073                        r.append(pg.info.name);
8074                    }
8075                } else {
8076                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8077                            + pg.info.packageName + " ignored: original from "
8078                            + cur.info.packageName);
8079                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8080                        if (r == null) {
8081                            r = new StringBuilder(256);
8082                        } else {
8083                            r.append(' ');
8084                        }
8085                        r.append("DUP:");
8086                        r.append(pg.info.name);
8087                    }
8088                }
8089            }
8090            if (r != null) {
8091                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8092            }
8093
8094            N = pkg.permissions.size();
8095            r = null;
8096            for (i=0; i<N; i++) {
8097                PackageParser.Permission p = pkg.permissions.get(i);
8098
8099                // Assume by default that we did not install this permission into the system.
8100                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8101
8102                // Now that permission groups have a special meaning, we ignore permission
8103                // groups for legacy apps to prevent unexpected behavior. In particular,
8104                // permissions for one app being granted to someone just becase they happen
8105                // to be in a group defined by another app (before this had no implications).
8106                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8107                    p.group = mPermissionGroups.get(p.info.group);
8108                    // Warn for a permission in an unknown group.
8109                    if (p.info.group != null && p.group == null) {
8110                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8111                                + p.info.packageName + " in an unknown group " + p.info.group);
8112                    }
8113                }
8114
8115                ArrayMap<String, BasePermission> permissionMap =
8116                        p.tree ? mSettings.mPermissionTrees
8117                                : mSettings.mPermissions;
8118                BasePermission bp = permissionMap.get(p.info.name);
8119
8120                // Allow system apps to redefine non-system permissions
8121                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8122                    final boolean currentOwnerIsSystem = (bp.perm != null
8123                            && isSystemApp(bp.perm.owner));
8124                    if (isSystemApp(p.owner)) {
8125                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8126                            // It's a built-in permission and no owner, take ownership now
8127                            bp.packageSetting = pkgSetting;
8128                            bp.perm = p;
8129                            bp.uid = pkg.applicationInfo.uid;
8130                            bp.sourcePackage = p.info.packageName;
8131                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8132                        } else if (!currentOwnerIsSystem) {
8133                            String msg = "New decl " + p.owner + " of permission  "
8134                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8135                            reportSettingsProblem(Log.WARN, msg);
8136                            bp = null;
8137                        }
8138                    }
8139                }
8140
8141                if (bp == null) {
8142                    bp = new BasePermission(p.info.name, p.info.packageName,
8143                            BasePermission.TYPE_NORMAL);
8144                    permissionMap.put(p.info.name, bp);
8145                }
8146
8147                if (bp.perm == null) {
8148                    if (bp.sourcePackage == null
8149                            || bp.sourcePackage.equals(p.info.packageName)) {
8150                        BasePermission tree = findPermissionTreeLP(p.info.name);
8151                        if (tree == null
8152                                || tree.sourcePackage.equals(p.info.packageName)) {
8153                            bp.packageSetting = pkgSetting;
8154                            bp.perm = p;
8155                            bp.uid = pkg.applicationInfo.uid;
8156                            bp.sourcePackage = p.info.packageName;
8157                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8158                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8159                                if (r == null) {
8160                                    r = new StringBuilder(256);
8161                                } else {
8162                                    r.append(' ');
8163                                }
8164                                r.append(p.info.name);
8165                            }
8166                        } else {
8167                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8168                                    + p.info.packageName + " ignored: base tree "
8169                                    + tree.name + " is from package "
8170                                    + tree.sourcePackage);
8171                        }
8172                    } else {
8173                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8174                                + p.info.packageName + " ignored: original from "
8175                                + bp.sourcePackage);
8176                    }
8177                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8178                    if (r == null) {
8179                        r = new StringBuilder(256);
8180                    } else {
8181                        r.append(' ');
8182                    }
8183                    r.append("DUP:");
8184                    r.append(p.info.name);
8185                }
8186                if (bp.perm == p) {
8187                    bp.protectionLevel = p.info.protectionLevel;
8188                }
8189            }
8190
8191            if (r != null) {
8192                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8193            }
8194
8195            N = pkg.instrumentation.size();
8196            r = null;
8197            for (i=0; i<N; i++) {
8198                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8199                a.info.packageName = pkg.applicationInfo.packageName;
8200                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8201                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8202                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8203                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8204                a.info.dataDir = pkg.applicationInfo.dataDir;
8205                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
8206                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
8207
8208                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8209                // need other information about the application, like the ABI and what not ?
8210                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8211                mInstrumentation.put(a.getComponentName(), a);
8212                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8213                    if (r == null) {
8214                        r = new StringBuilder(256);
8215                    } else {
8216                        r.append(' ');
8217                    }
8218                    r.append(a.info.name);
8219                }
8220            }
8221            if (r != null) {
8222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8223            }
8224
8225            if (pkg.protectedBroadcasts != null) {
8226                N = pkg.protectedBroadcasts.size();
8227                for (i=0; i<N; i++) {
8228                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8229                }
8230            }
8231
8232            pkgSetting.setTimeStamp(scanFileTime);
8233
8234            // Create idmap files for pairs of (packages, overlay packages).
8235            // Note: "android", ie framework-res.apk, is handled by native layers.
8236            if (pkg.mOverlayTarget != null) {
8237                // This is an overlay package.
8238                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8239                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8240                        mOverlays.put(pkg.mOverlayTarget,
8241                                new ArrayMap<String, PackageParser.Package>());
8242                    }
8243                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8244                    map.put(pkg.packageName, pkg);
8245                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8246                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8247                        createIdmapFailed = true;
8248                    }
8249                }
8250            } else if (mOverlays.containsKey(pkg.packageName) &&
8251                    !pkg.packageName.equals("android")) {
8252                // This is a regular package, with one or more known overlay packages.
8253                createIdmapsForPackageLI(pkg);
8254            }
8255        }
8256
8257        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8258
8259        if (createIdmapFailed) {
8260            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8261                    "scanPackageLI failed to createIdmap");
8262        }
8263        return pkg;
8264    }
8265
8266    /**
8267     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8268     * is derived purely on the basis of the contents of {@code scanFile} and
8269     * {@code cpuAbiOverride}.
8270     *
8271     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8272     */
8273    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8274                                 String cpuAbiOverride, boolean extractLibs)
8275            throws PackageManagerException {
8276        // TODO: We can probably be smarter about this stuff. For installed apps,
8277        // we can calculate this information at install time once and for all. For
8278        // system apps, we can probably assume that this information doesn't change
8279        // after the first boot scan. As things stand, we do lots of unnecessary work.
8280
8281        // Give ourselves some initial paths; we'll come back for another
8282        // pass once we've determined ABI below.
8283        setNativeLibraryPaths(pkg);
8284
8285        // We would never need to extract libs for forward-locked and external packages,
8286        // since the container service will do it for us. We shouldn't attempt to
8287        // extract libs from system app when it was not updated.
8288        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8289                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8290            extractLibs = false;
8291        }
8292
8293        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8294        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8295
8296        NativeLibraryHelper.Handle handle = null;
8297        try {
8298            handle = NativeLibraryHelper.Handle.create(pkg);
8299            // TODO(multiArch): This can be null for apps that didn't go through the
8300            // usual installation process. We can calculate it again, like we
8301            // do during install time.
8302            //
8303            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8304            // unnecessary.
8305            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8306
8307            // Null out the abis so that they can be recalculated.
8308            pkg.applicationInfo.primaryCpuAbi = null;
8309            pkg.applicationInfo.secondaryCpuAbi = null;
8310            if (isMultiArch(pkg.applicationInfo)) {
8311                // Warn if we've set an abiOverride for multi-lib packages..
8312                // By definition, we need to copy both 32 and 64 bit libraries for
8313                // such packages.
8314                if (pkg.cpuAbiOverride != null
8315                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8316                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8317                }
8318
8319                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8320                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8321                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8322                    if (extractLibs) {
8323                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8324                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8325                                useIsaSpecificSubdirs);
8326                    } else {
8327                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8328                    }
8329                }
8330
8331                maybeThrowExceptionForMultiArchCopy(
8332                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8333
8334                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8335                    if (extractLibs) {
8336                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8337                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8338                                useIsaSpecificSubdirs);
8339                    } else {
8340                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8341                    }
8342                }
8343
8344                maybeThrowExceptionForMultiArchCopy(
8345                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8346
8347                if (abi64 >= 0) {
8348                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8349                }
8350
8351                if (abi32 >= 0) {
8352                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8353                    if (abi64 >= 0) {
8354                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8355                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8356                            pkg.applicationInfo.primaryCpuAbi = abi;
8357                        } else {
8358                            pkg.applicationInfo.secondaryCpuAbi = abi;
8359                        }
8360                    } else {
8361                        pkg.applicationInfo.primaryCpuAbi = abi;
8362                    }
8363                }
8364
8365            } else {
8366                String[] abiList = (cpuAbiOverride != null) ?
8367                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8368
8369                // Enable gross and lame hacks for apps that are built with old
8370                // SDK tools. We must scan their APKs for renderscript bitcode and
8371                // not launch them if it's present. Don't bother checking on devices
8372                // that don't have 64 bit support.
8373                boolean needsRenderScriptOverride = false;
8374                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8375                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8376                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8377                    needsRenderScriptOverride = true;
8378                }
8379
8380                final int copyRet;
8381                if (extractLibs) {
8382                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8383                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8384                } else {
8385                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8386                }
8387
8388                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8389                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8390                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8391                }
8392
8393                if (copyRet >= 0) {
8394                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8395                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8396                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8397                } else if (needsRenderScriptOverride) {
8398                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8399                }
8400            }
8401        } catch (IOException ioe) {
8402            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8403        } finally {
8404            IoUtils.closeQuietly(handle);
8405        }
8406
8407        // Now that we've calculated the ABIs and determined if it's an internal app,
8408        // we will go ahead and populate the nativeLibraryPath.
8409        setNativeLibraryPaths(pkg);
8410    }
8411
8412    /**
8413     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8414     * i.e, so that all packages can be run inside a single process if required.
8415     *
8416     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8417     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8418     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8419     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8420     * updating a package that belongs to a shared user.
8421     *
8422     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8423     * adds unnecessary complexity.
8424     */
8425    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8426            PackageParser.Package scannedPackage, boolean bootComplete) {
8427        String requiredInstructionSet = null;
8428        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8429            requiredInstructionSet = VMRuntime.getInstructionSet(
8430                     scannedPackage.applicationInfo.primaryCpuAbi);
8431        }
8432
8433        PackageSetting requirer = null;
8434        for (PackageSetting ps : packagesForUser) {
8435            // If packagesForUser contains scannedPackage, we skip it. This will happen
8436            // when scannedPackage is an update of an existing package. Without this check,
8437            // we will never be able to change the ABI of any package belonging to a shared
8438            // user, even if it's compatible with other packages.
8439            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8440                if (ps.primaryCpuAbiString == null) {
8441                    continue;
8442                }
8443
8444                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8445                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8446                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8447                    // this but there's not much we can do.
8448                    String errorMessage = "Instruction set mismatch, "
8449                            + ((requirer == null) ? "[caller]" : requirer)
8450                            + " requires " + requiredInstructionSet + " whereas " + ps
8451                            + " requires " + instructionSet;
8452                    Slog.w(TAG, errorMessage);
8453                }
8454
8455                if (requiredInstructionSet == null) {
8456                    requiredInstructionSet = instructionSet;
8457                    requirer = ps;
8458                }
8459            }
8460        }
8461
8462        if (requiredInstructionSet != null) {
8463            String adjustedAbi;
8464            if (requirer != null) {
8465                // requirer != null implies that either scannedPackage was null or that scannedPackage
8466                // did not require an ABI, in which case we have to adjust scannedPackage to match
8467                // the ABI of the set (which is the same as requirer's ABI)
8468                adjustedAbi = requirer.primaryCpuAbiString;
8469                if (scannedPackage != null) {
8470                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8471                }
8472            } else {
8473                // requirer == null implies that we're updating all ABIs in the set to
8474                // match scannedPackage.
8475                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8476            }
8477
8478            for (PackageSetting ps : packagesForUser) {
8479                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8480                    if (ps.primaryCpuAbiString != null) {
8481                        continue;
8482                    }
8483
8484                    ps.primaryCpuAbiString = adjustedAbi;
8485                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8486                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8487                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8488                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8489                                + " (requirer="
8490                                + (requirer == null ? "null" : requirer.pkg.packageName)
8491                                + ", scannedPackage="
8492                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8493                                + ")");
8494                        try {
8495                            mInstaller.rmdex(ps.codePathString,
8496                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8497                        } catch (InstallerException ignored) {
8498                        }
8499                    }
8500                }
8501            }
8502        }
8503    }
8504
8505    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8506        synchronized (mPackages) {
8507            mResolverReplaced = true;
8508            // Set up information for custom user intent resolution activity.
8509            mResolveActivity.applicationInfo = pkg.applicationInfo;
8510            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8511            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8512            mResolveActivity.processName = pkg.applicationInfo.packageName;
8513            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8514            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8515                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8516            mResolveActivity.theme = 0;
8517            mResolveActivity.exported = true;
8518            mResolveActivity.enabled = true;
8519            mResolveInfo.activityInfo = mResolveActivity;
8520            mResolveInfo.priority = 0;
8521            mResolveInfo.preferredOrder = 0;
8522            mResolveInfo.match = 0;
8523            mResolveComponentName = mCustomResolverComponentName;
8524            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8525                    mResolveComponentName);
8526        }
8527    }
8528
8529    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8530        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8531
8532        // Set up information for ephemeral installer activity
8533        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8534        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8535        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8536        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8537        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8538        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8539                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8540        mEphemeralInstallerActivity.theme = 0;
8541        mEphemeralInstallerActivity.exported = true;
8542        mEphemeralInstallerActivity.enabled = true;
8543        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8544        mEphemeralInstallerInfo.priority = 0;
8545        mEphemeralInstallerInfo.preferredOrder = 0;
8546        mEphemeralInstallerInfo.match = 0;
8547
8548        if (DEBUG_EPHEMERAL) {
8549            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8550        }
8551    }
8552
8553    private static String calculateBundledApkRoot(final String codePathString) {
8554        final File codePath = new File(codePathString);
8555        final File codeRoot;
8556        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8557            codeRoot = Environment.getRootDirectory();
8558        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8559            codeRoot = Environment.getOemDirectory();
8560        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8561            codeRoot = Environment.getVendorDirectory();
8562        } else {
8563            // Unrecognized code path; take its top real segment as the apk root:
8564            // e.g. /something/app/blah.apk => /something
8565            try {
8566                File f = codePath.getCanonicalFile();
8567                File parent = f.getParentFile();    // non-null because codePath is a file
8568                File tmp;
8569                while ((tmp = parent.getParentFile()) != null) {
8570                    f = parent;
8571                    parent = tmp;
8572                }
8573                codeRoot = f;
8574                Slog.w(TAG, "Unrecognized code path "
8575                        + codePath + " - using " + codeRoot);
8576            } catch (IOException e) {
8577                // Can't canonicalize the code path -- shenanigans?
8578                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8579                return Environment.getRootDirectory().getPath();
8580            }
8581        }
8582        return codeRoot.getPath();
8583    }
8584
8585    /**
8586     * Derive and set the location of native libraries for the given package,
8587     * which varies depending on where and how the package was installed.
8588     */
8589    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8590        final ApplicationInfo info = pkg.applicationInfo;
8591        final String codePath = pkg.codePath;
8592        final File codeFile = new File(codePath);
8593        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8594        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8595
8596        info.nativeLibraryRootDir = null;
8597        info.nativeLibraryRootRequiresIsa = false;
8598        info.nativeLibraryDir = null;
8599        info.secondaryNativeLibraryDir = null;
8600
8601        if (isApkFile(codeFile)) {
8602            // Monolithic install
8603            if (bundledApp) {
8604                // If "/system/lib64/apkname" exists, assume that is the per-package
8605                // native library directory to use; otherwise use "/system/lib/apkname".
8606                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8607                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8608                        getPrimaryInstructionSet(info));
8609
8610                // This is a bundled system app so choose the path based on the ABI.
8611                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8612                // is just the default path.
8613                final String apkName = deriveCodePathName(codePath);
8614                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8615                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8616                        apkName).getAbsolutePath();
8617
8618                if (info.secondaryCpuAbi != null) {
8619                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8620                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8621                            secondaryLibDir, apkName).getAbsolutePath();
8622                }
8623            } else if (asecApp) {
8624                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8625                        .getAbsolutePath();
8626            } else {
8627                final String apkName = deriveCodePathName(codePath);
8628                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8629                        .getAbsolutePath();
8630            }
8631
8632            info.nativeLibraryRootRequiresIsa = false;
8633            info.nativeLibraryDir = info.nativeLibraryRootDir;
8634        } else {
8635            // Cluster install
8636            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8637            info.nativeLibraryRootRequiresIsa = true;
8638
8639            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8640                    getPrimaryInstructionSet(info)).getAbsolutePath();
8641
8642            if (info.secondaryCpuAbi != null) {
8643                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8644                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8645            }
8646        }
8647    }
8648
8649    /**
8650     * Calculate the abis and roots for a bundled app. These can uniquely
8651     * be determined from the contents of the system partition, i.e whether
8652     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8653     * of this information, and instead assume that the system was built
8654     * sensibly.
8655     */
8656    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8657                                           PackageSetting pkgSetting) {
8658        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8659
8660        // If "/system/lib64/apkname" exists, assume that is the per-package
8661        // native library directory to use; otherwise use "/system/lib/apkname".
8662        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8663        setBundledAppAbi(pkg, apkRoot, apkName);
8664        // pkgSetting might be null during rescan following uninstall of updates
8665        // to a bundled app, so accommodate that possibility.  The settings in
8666        // that case will be established later from the parsed package.
8667        //
8668        // If the settings aren't null, sync them up with what we've just derived.
8669        // note that apkRoot isn't stored in the package settings.
8670        if (pkgSetting != null) {
8671            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8672            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8673        }
8674    }
8675
8676    /**
8677     * Deduces the ABI of a bundled app and sets the relevant fields on the
8678     * parsed pkg object.
8679     *
8680     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8681     *        under which system libraries are installed.
8682     * @param apkName the name of the installed package.
8683     */
8684    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8685        final File codeFile = new File(pkg.codePath);
8686
8687        final boolean has64BitLibs;
8688        final boolean has32BitLibs;
8689        if (isApkFile(codeFile)) {
8690            // Monolithic install
8691            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8692            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8693        } else {
8694            // Cluster install
8695            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8696            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8697                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8698                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8699                has64BitLibs = (new File(rootDir, isa)).exists();
8700            } else {
8701                has64BitLibs = false;
8702            }
8703            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8704                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8705                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8706                has32BitLibs = (new File(rootDir, isa)).exists();
8707            } else {
8708                has32BitLibs = false;
8709            }
8710        }
8711
8712        if (has64BitLibs && !has32BitLibs) {
8713            // The package has 64 bit libs, but not 32 bit libs. Its primary
8714            // ABI should be 64 bit. We can safely assume here that the bundled
8715            // native libraries correspond to the most preferred ABI in the list.
8716
8717            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8718            pkg.applicationInfo.secondaryCpuAbi = null;
8719        } else if (has32BitLibs && !has64BitLibs) {
8720            // The package has 32 bit libs but not 64 bit libs. Its primary
8721            // ABI should be 32 bit.
8722
8723            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8724            pkg.applicationInfo.secondaryCpuAbi = null;
8725        } else if (has32BitLibs && has64BitLibs) {
8726            // The application has both 64 and 32 bit bundled libraries. We check
8727            // here that the app declares multiArch support, and warn if it doesn't.
8728            //
8729            // We will be lenient here and record both ABIs. The primary will be the
8730            // ABI that's higher on the list, i.e, a device that's configured to prefer
8731            // 64 bit apps will see a 64 bit primary ABI,
8732
8733            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8734                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8735            }
8736
8737            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8738                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8739                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8740            } else {
8741                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8742                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8743            }
8744        } else {
8745            pkg.applicationInfo.primaryCpuAbi = null;
8746            pkg.applicationInfo.secondaryCpuAbi = null;
8747        }
8748    }
8749
8750    private void killPackage(PackageParser.Package pkg, String reason) {
8751        // Kill the parent package
8752        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8753        // Kill the child packages
8754        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8755        for (int i = 0; i < childCount; i++) {
8756            PackageParser.Package childPkg = pkg.childPackages.get(i);
8757            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8758        }
8759    }
8760
8761    private void killApplication(String pkgName, int appId, String reason) {
8762        // Request the ActivityManager to kill the process(only for existing packages)
8763        // so that we do not end up in a confused state while the user is still using the older
8764        // version of the application while the new one gets installed.
8765        IActivityManager am = ActivityManagerNative.getDefault();
8766        if (am != null) {
8767            try {
8768                am.killApplicationWithAppId(pkgName, appId, reason);
8769            } catch (RemoteException e) {
8770            }
8771        }
8772    }
8773
8774    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8775        // Remove the parent package setting
8776        PackageSetting ps = (PackageSetting) pkg.mExtras;
8777        if (ps != null) {
8778            removePackageLI(ps, chatty);
8779        }
8780        // Remove the child package setting
8781        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8782        for (int i = 0; i < childCount; i++) {
8783            PackageParser.Package childPkg = pkg.childPackages.get(i);
8784            ps = (PackageSetting) childPkg.mExtras;
8785            if (ps != null) {
8786                removePackageLI(ps, chatty);
8787            }
8788        }
8789    }
8790
8791    void removePackageLI(PackageSetting ps, boolean chatty) {
8792        if (DEBUG_INSTALL) {
8793            if (chatty)
8794                Log.d(TAG, "Removing package " + ps.name);
8795        }
8796
8797        // writer
8798        synchronized (mPackages) {
8799            mPackages.remove(ps.name);
8800            final PackageParser.Package pkg = ps.pkg;
8801            if (pkg != null) {
8802                cleanPackageDataStructuresLILPw(pkg, chatty);
8803            }
8804        }
8805    }
8806
8807    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8808        if (DEBUG_INSTALL) {
8809            if (chatty)
8810                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8811        }
8812
8813        // writer
8814        synchronized (mPackages) {
8815            // Remove the parent package
8816            mPackages.remove(pkg.applicationInfo.packageName);
8817            cleanPackageDataStructuresLILPw(pkg, chatty);
8818
8819            // Remove the child packages
8820            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8821            for (int i = 0; i < childCount; i++) {
8822                PackageParser.Package childPkg = pkg.childPackages.get(i);
8823                mPackages.remove(childPkg.applicationInfo.packageName);
8824                cleanPackageDataStructuresLILPw(childPkg, chatty);
8825            }
8826        }
8827    }
8828
8829    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8830        int N = pkg.providers.size();
8831        StringBuilder r = null;
8832        int i;
8833        for (i=0; i<N; i++) {
8834            PackageParser.Provider p = pkg.providers.get(i);
8835            mProviders.removeProvider(p);
8836            if (p.info.authority == null) {
8837
8838                /* There was another ContentProvider with this authority when
8839                 * this app was installed so this authority is null,
8840                 * Ignore it as we don't have to unregister the provider.
8841                 */
8842                continue;
8843            }
8844            String names[] = p.info.authority.split(";");
8845            for (int j = 0; j < names.length; j++) {
8846                if (mProvidersByAuthority.get(names[j]) == p) {
8847                    mProvidersByAuthority.remove(names[j]);
8848                    if (DEBUG_REMOVE) {
8849                        if (chatty)
8850                            Log.d(TAG, "Unregistered content provider: " + names[j]
8851                                    + ", className = " + p.info.name + ", isSyncable = "
8852                                    + p.info.isSyncable);
8853                    }
8854                }
8855            }
8856            if (DEBUG_REMOVE && chatty) {
8857                if (r == null) {
8858                    r = new StringBuilder(256);
8859                } else {
8860                    r.append(' ');
8861                }
8862                r.append(p.info.name);
8863            }
8864        }
8865        if (r != null) {
8866            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8867        }
8868
8869        N = pkg.services.size();
8870        r = null;
8871        for (i=0; i<N; i++) {
8872            PackageParser.Service s = pkg.services.get(i);
8873            mServices.removeService(s);
8874            if (chatty) {
8875                if (r == null) {
8876                    r = new StringBuilder(256);
8877                } else {
8878                    r.append(' ');
8879                }
8880                r.append(s.info.name);
8881            }
8882        }
8883        if (r != null) {
8884            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8885        }
8886
8887        N = pkg.receivers.size();
8888        r = null;
8889        for (i=0; i<N; i++) {
8890            PackageParser.Activity a = pkg.receivers.get(i);
8891            mReceivers.removeActivity(a, "receiver");
8892            if (DEBUG_REMOVE && chatty) {
8893                if (r == null) {
8894                    r = new StringBuilder(256);
8895                } else {
8896                    r.append(' ');
8897                }
8898                r.append(a.info.name);
8899            }
8900        }
8901        if (r != null) {
8902            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8903        }
8904
8905        N = pkg.activities.size();
8906        r = null;
8907        for (i=0; i<N; i++) {
8908            PackageParser.Activity a = pkg.activities.get(i);
8909            mActivities.removeActivity(a, "activity");
8910            if (DEBUG_REMOVE && chatty) {
8911                if (r == null) {
8912                    r = new StringBuilder(256);
8913                } else {
8914                    r.append(' ');
8915                }
8916                r.append(a.info.name);
8917            }
8918        }
8919        if (r != null) {
8920            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8921        }
8922
8923        N = pkg.permissions.size();
8924        r = null;
8925        for (i=0; i<N; i++) {
8926            PackageParser.Permission p = pkg.permissions.get(i);
8927            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8928            if (bp == null) {
8929                bp = mSettings.mPermissionTrees.get(p.info.name);
8930            }
8931            if (bp != null && bp.perm == p) {
8932                bp.perm = null;
8933                if (DEBUG_REMOVE && chatty) {
8934                    if (r == null) {
8935                        r = new StringBuilder(256);
8936                    } else {
8937                        r.append(' ');
8938                    }
8939                    r.append(p.info.name);
8940                }
8941            }
8942            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8943                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8944                if (appOpPkgs != null) {
8945                    appOpPkgs.remove(pkg.packageName);
8946                }
8947            }
8948        }
8949        if (r != null) {
8950            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8951        }
8952
8953        N = pkg.requestedPermissions.size();
8954        r = null;
8955        for (i=0; i<N; i++) {
8956            String perm = pkg.requestedPermissions.get(i);
8957            BasePermission bp = mSettings.mPermissions.get(perm);
8958            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8959                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8960                if (appOpPkgs != null) {
8961                    appOpPkgs.remove(pkg.packageName);
8962                    if (appOpPkgs.isEmpty()) {
8963                        mAppOpPermissionPackages.remove(perm);
8964                    }
8965                }
8966            }
8967        }
8968        if (r != null) {
8969            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8970        }
8971
8972        N = pkg.instrumentation.size();
8973        r = null;
8974        for (i=0; i<N; i++) {
8975            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8976            mInstrumentation.remove(a.getComponentName());
8977            if (DEBUG_REMOVE && chatty) {
8978                if (r == null) {
8979                    r = new StringBuilder(256);
8980                } else {
8981                    r.append(' ');
8982                }
8983                r.append(a.info.name);
8984            }
8985        }
8986        if (r != null) {
8987            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8988        }
8989
8990        r = null;
8991        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8992            // Only system apps can hold shared libraries.
8993            if (pkg.libraryNames != null) {
8994                for (i=0; i<pkg.libraryNames.size(); i++) {
8995                    String name = pkg.libraryNames.get(i);
8996                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8997                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8998                        mSharedLibraries.remove(name);
8999                        if (DEBUG_REMOVE && chatty) {
9000                            if (r == null) {
9001                                r = new StringBuilder(256);
9002                            } else {
9003                                r.append(' ');
9004                            }
9005                            r.append(name);
9006                        }
9007                    }
9008                }
9009            }
9010        }
9011        if (r != null) {
9012            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9013        }
9014    }
9015
9016    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9017        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9018            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9019                return true;
9020            }
9021        }
9022        return false;
9023    }
9024
9025    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9026    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9027    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9028
9029    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9030        // Update the parent permissions
9031        updatePermissionsLPw(pkg.packageName, pkg, flags);
9032        // Update the child permissions
9033        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9034        for (int i = 0; i < childCount; i++) {
9035            PackageParser.Package childPkg = pkg.childPackages.get(i);
9036            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9037        }
9038    }
9039
9040    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9041            int flags) {
9042        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9043        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9044    }
9045
9046    private void updatePermissionsLPw(String changingPkg,
9047            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9048        // Make sure there are no dangling permission trees.
9049        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9050        while (it.hasNext()) {
9051            final BasePermission bp = it.next();
9052            if (bp.packageSetting == null) {
9053                // We may not yet have parsed the package, so just see if
9054                // we still know about its settings.
9055                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9056            }
9057            if (bp.packageSetting == null) {
9058                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9059                        + " from package " + bp.sourcePackage);
9060                it.remove();
9061            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9062                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9063                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9064                            + " from package " + bp.sourcePackage);
9065                    flags |= UPDATE_PERMISSIONS_ALL;
9066                    it.remove();
9067                }
9068            }
9069        }
9070
9071        // Make sure all dynamic permissions have been assigned to a package,
9072        // and make sure there are no dangling permissions.
9073        it = mSettings.mPermissions.values().iterator();
9074        while (it.hasNext()) {
9075            final BasePermission bp = it.next();
9076            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9077                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9078                        + bp.name + " pkg=" + bp.sourcePackage
9079                        + " info=" + bp.pendingInfo);
9080                if (bp.packageSetting == null && bp.pendingInfo != null) {
9081                    final BasePermission tree = findPermissionTreeLP(bp.name);
9082                    if (tree != null && tree.perm != null) {
9083                        bp.packageSetting = tree.packageSetting;
9084                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9085                                new PermissionInfo(bp.pendingInfo));
9086                        bp.perm.info.packageName = tree.perm.info.packageName;
9087                        bp.perm.info.name = bp.name;
9088                        bp.uid = tree.uid;
9089                    }
9090                }
9091            }
9092            if (bp.packageSetting == null) {
9093                // We may not yet have parsed the package, so just see if
9094                // we still know about its settings.
9095                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9096            }
9097            if (bp.packageSetting == null) {
9098                Slog.w(TAG, "Removing dangling permission: " + bp.name
9099                        + " from package " + bp.sourcePackage);
9100                it.remove();
9101            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9102                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9103                    Slog.i(TAG, "Removing old permission: " + bp.name
9104                            + " from package " + bp.sourcePackage);
9105                    flags |= UPDATE_PERMISSIONS_ALL;
9106                    it.remove();
9107                }
9108            }
9109        }
9110
9111        // Now update the permissions for all packages, in particular
9112        // replace the granted permissions of the system packages.
9113        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9114            for (PackageParser.Package pkg : mPackages.values()) {
9115                if (pkg != pkgInfo) {
9116                    // Only replace for packages on requested volume
9117                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9118                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9119                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9120                    grantPermissionsLPw(pkg, replace, changingPkg);
9121                }
9122            }
9123        }
9124
9125        if (pkgInfo != null) {
9126            // Only replace for packages on requested volume
9127            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9128            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9129                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9130            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9131        }
9132    }
9133
9134    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9135            String packageOfInterest) {
9136        // IMPORTANT: There are two types of permissions: install and runtime.
9137        // Install time permissions are granted when the app is installed to
9138        // all device users and users added in the future. Runtime permissions
9139        // are granted at runtime explicitly to specific users. Normal and signature
9140        // protected permissions are install time permissions. Dangerous permissions
9141        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9142        // otherwise they are runtime permissions. This function does not manage
9143        // runtime permissions except for the case an app targeting Lollipop MR1
9144        // being upgraded to target a newer SDK, in which case dangerous permissions
9145        // are transformed from install time to runtime ones.
9146
9147        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9148        if (ps == null) {
9149            return;
9150        }
9151
9152        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9153
9154        PermissionsState permissionsState = ps.getPermissionsState();
9155        PermissionsState origPermissions = permissionsState;
9156
9157        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9158
9159        boolean runtimePermissionsRevoked = false;
9160        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9161
9162        boolean changedInstallPermission = false;
9163
9164        if (replace) {
9165            ps.installPermissionsFixed = false;
9166            if (!ps.isSharedUser()) {
9167                origPermissions = new PermissionsState(permissionsState);
9168                permissionsState.reset();
9169            } else {
9170                // We need to know only about runtime permission changes since the
9171                // calling code always writes the install permissions state but
9172                // the runtime ones are written only if changed. The only cases of
9173                // changed runtime permissions here are promotion of an install to
9174                // runtime and revocation of a runtime from a shared user.
9175                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9176                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9177                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9178                    runtimePermissionsRevoked = true;
9179                }
9180            }
9181        }
9182
9183        permissionsState.setGlobalGids(mGlobalGids);
9184
9185        final int N = pkg.requestedPermissions.size();
9186        for (int i=0; i<N; i++) {
9187            final String name = pkg.requestedPermissions.get(i);
9188            final BasePermission bp = mSettings.mPermissions.get(name);
9189
9190            if (DEBUG_INSTALL) {
9191                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9192            }
9193
9194            if (bp == null || bp.packageSetting == null) {
9195                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9196                    Slog.w(TAG, "Unknown permission " + name
9197                            + " in package " + pkg.packageName);
9198                }
9199                continue;
9200            }
9201
9202            final String perm = bp.name;
9203            boolean allowedSig = false;
9204            int grant = GRANT_DENIED;
9205
9206            // Keep track of app op permissions.
9207            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9208                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9209                if (pkgs == null) {
9210                    pkgs = new ArraySet<>();
9211                    mAppOpPermissionPackages.put(bp.name, pkgs);
9212                }
9213                pkgs.add(pkg.packageName);
9214            }
9215
9216            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9217            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9218                    >= Build.VERSION_CODES.M;
9219            switch (level) {
9220                case PermissionInfo.PROTECTION_NORMAL: {
9221                    // For all apps normal permissions are install time ones.
9222                    grant = GRANT_INSTALL;
9223                } break;
9224
9225                case PermissionInfo.PROTECTION_DANGEROUS: {
9226                    // If a permission review is required for legacy apps we represent
9227                    // their permissions as always granted runtime ones since we need
9228                    // to keep the review required permission flag per user while an
9229                    // install permission's state is shared across all users.
9230                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9231                        // For legacy apps dangerous permissions are install time ones.
9232                        grant = GRANT_INSTALL;
9233                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9234                        // For legacy apps that became modern, install becomes runtime.
9235                        grant = GRANT_UPGRADE;
9236                    } else if (mPromoteSystemApps
9237                            && isSystemApp(ps)
9238                            && mExistingSystemPackages.contains(ps.name)) {
9239                        // For legacy system apps, install becomes runtime.
9240                        // We cannot check hasInstallPermission() for system apps since those
9241                        // permissions were granted implicitly and not persisted pre-M.
9242                        grant = GRANT_UPGRADE;
9243                    } else {
9244                        // For modern apps keep runtime permissions unchanged.
9245                        grant = GRANT_RUNTIME;
9246                    }
9247                } break;
9248
9249                case PermissionInfo.PROTECTION_SIGNATURE: {
9250                    // For all apps signature permissions are install time ones.
9251                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9252                    if (allowedSig) {
9253                        grant = GRANT_INSTALL;
9254                    }
9255                } break;
9256            }
9257
9258            if (DEBUG_INSTALL) {
9259                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9260            }
9261
9262            if (grant != GRANT_DENIED) {
9263                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9264                    // If this is an existing, non-system package, then
9265                    // we can't add any new permissions to it.
9266                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9267                        // Except...  if this is a permission that was added
9268                        // to the platform (note: need to only do this when
9269                        // updating the platform).
9270                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9271                            grant = GRANT_DENIED;
9272                        }
9273                    }
9274                }
9275
9276                switch (grant) {
9277                    case GRANT_INSTALL: {
9278                        // Revoke this as runtime permission to handle the case of
9279                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9280                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9281                            if (origPermissions.getRuntimePermissionState(
9282                                    bp.name, userId) != null) {
9283                                // Revoke the runtime permission and clear the flags.
9284                                origPermissions.revokeRuntimePermission(bp, userId);
9285                                origPermissions.updatePermissionFlags(bp, userId,
9286                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9287                                // If we revoked a permission permission, we have to write.
9288                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9289                                        changedRuntimePermissionUserIds, userId);
9290                            }
9291                        }
9292                        // Grant an install permission.
9293                        if (permissionsState.grantInstallPermission(bp) !=
9294                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9295                            changedInstallPermission = true;
9296                        }
9297                    } break;
9298
9299                    case GRANT_RUNTIME: {
9300                        // Grant previously granted runtime permissions.
9301                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9302                            PermissionState permissionState = origPermissions
9303                                    .getRuntimePermissionState(bp.name, userId);
9304                            int flags = permissionState != null
9305                                    ? permissionState.getFlags() : 0;
9306                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9307                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9308                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9309                                    // If we cannot put the permission as it was, we have to write.
9310                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9311                                            changedRuntimePermissionUserIds, userId);
9312                                }
9313                                // If the app supports runtime permissions no need for a review.
9314                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9315                                        && appSupportsRuntimePermissions
9316                                        && (flags & PackageManager
9317                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9318                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9319                                    // Since we changed the flags, we have to write.
9320                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9321                                            changedRuntimePermissionUserIds, userId);
9322                                }
9323                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9324                                    && !appSupportsRuntimePermissions) {
9325                                // For legacy apps that need a permission review, every new
9326                                // runtime permission is granted but it is pending a review.
9327                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9328                                    permissionsState.grantRuntimePermission(bp, userId);
9329                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9330                                    // We changed the permission and flags, hence have to write.
9331                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9332                                            changedRuntimePermissionUserIds, userId);
9333                                }
9334                            }
9335                            // Propagate the permission flags.
9336                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9337                        }
9338                    } break;
9339
9340                    case GRANT_UPGRADE: {
9341                        // Grant runtime permissions for a previously held install permission.
9342                        PermissionState permissionState = origPermissions
9343                                .getInstallPermissionState(bp.name);
9344                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9345
9346                        if (origPermissions.revokeInstallPermission(bp)
9347                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9348                            // We will be transferring the permission flags, so clear them.
9349                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9350                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9351                            changedInstallPermission = true;
9352                        }
9353
9354                        // If the permission is not to be promoted to runtime we ignore it and
9355                        // also its other flags as they are not applicable to install permissions.
9356                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9357                            for (int userId : currentUserIds) {
9358                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9359                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9360                                    // Transfer the permission flags.
9361                                    permissionsState.updatePermissionFlags(bp, userId,
9362                                            flags, flags);
9363                                    // If we granted the permission, we have to write.
9364                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9365                                            changedRuntimePermissionUserIds, userId);
9366                                }
9367                            }
9368                        }
9369                    } break;
9370
9371                    default: {
9372                        if (packageOfInterest == null
9373                                || packageOfInterest.equals(pkg.packageName)) {
9374                            Slog.w(TAG, "Not granting permission " + perm
9375                                    + " to package " + pkg.packageName
9376                                    + " because it was previously installed without");
9377                        }
9378                    } break;
9379                }
9380            } else {
9381                if (permissionsState.revokeInstallPermission(bp) !=
9382                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9383                    // Also drop the permission flags.
9384                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9385                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9386                    changedInstallPermission = true;
9387                    Slog.i(TAG, "Un-granting permission " + perm
9388                            + " from package " + pkg.packageName
9389                            + " (protectionLevel=" + bp.protectionLevel
9390                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9391                            + ")");
9392                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9393                    // Don't print warning for app op permissions, since it is fine for them
9394                    // not to be granted, there is a UI for the user to decide.
9395                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9396                        Slog.w(TAG, "Not granting permission " + perm
9397                                + " to package " + pkg.packageName
9398                                + " (protectionLevel=" + bp.protectionLevel
9399                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9400                                + ")");
9401                    }
9402                }
9403            }
9404        }
9405
9406        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9407                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9408            // This is the first that we have heard about this package, so the
9409            // permissions we have now selected are fixed until explicitly
9410            // changed.
9411            ps.installPermissionsFixed = true;
9412        }
9413
9414        // Persist the runtime permissions state for users with changes. If permissions
9415        // were revoked because no app in the shared user declares them we have to
9416        // write synchronously to avoid losing runtime permissions state.
9417        for (int userId : changedRuntimePermissionUserIds) {
9418            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9419        }
9420
9421        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9422    }
9423
9424    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9425        boolean allowed = false;
9426        final int NP = PackageParser.NEW_PERMISSIONS.length;
9427        for (int ip=0; ip<NP; ip++) {
9428            final PackageParser.NewPermissionInfo npi
9429                    = PackageParser.NEW_PERMISSIONS[ip];
9430            if (npi.name.equals(perm)
9431                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9432                allowed = true;
9433                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9434                        + pkg.packageName);
9435                break;
9436            }
9437        }
9438        return allowed;
9439    }
9440
9441    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9442            BasePermission bp, PermissionsState origPermissions) {
9443        boolean allowed;
9444        allowed = (compareSignatures(
9445                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9446                        == PackageManager.SIGNATURE_MATCH)
9447                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9448                        == PackageManager.SIGNATURE_MATCH);
9449        if (!allowed && (bp.protectionLevel
9450                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9451            if (isSystemApp(pkg)) {
9452                // For updated system applications, a system permission
9453                // is granted only if it had been defined by the original application.
9454                if (pkg.isUpdatedSystemApp()) {
9455                    final PackageSetting sysPs = mSettings
9456                            .getDisabledSystemPkgLPr(pkg.packageName);
9457                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9458                        // If the original was granted this permission, we take
9459                        // that grant decision as read and propagate it to the
9460                        // update.
9461                        if (sysPs.isPrivileged()) {
9462                            allowed = true;
9463                        }
9464                    } else {
9465                        // The system apk may have been updated with an older
9466                        // version of the one on the data partition, but which
9467                        // granted a new system permission that it didn't have
9468                        // before.  In this case we do want to allow the app to
9469                        // now get the new permission if the ancestral apk is
9470                        // privileged to get it.
9471                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9472                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9473                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9474                                    allowed = true;
9475                                    break;
9476                                }
9477                            }
9478                        }
9479                        // Also if a privileged parent package on the system image or any of
9480                        // its children requested a privileged permission, the updated child
9481                        // packages can also get the permission.
9482                        if (pkg.parentPackage != null) {
9483                            final PackageSetting disabledSysParentPs = mSettings
9484                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9485                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9486                                    && disabledSysParentPs.isPrivileged()) {
9487                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9488                                    allowed = true;
9489                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9490                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9491                                    for (int i = 0; i < count; i++) {
9492                                        PackageParser.Package disabledSysChildPkg =
9493                                                disabledSysParentPs.pkg.childPackages.get(i);
9494                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9495                                                perm)) {
9496                                            allowed = true;
9497                                            break;
9498                                        }
9499                                    }
9500                                }
9501                            }
9502                        }
9503                    }
9504                } else {
9505                    allowed = isPrivilegedApp(pkg);
9506                }
9507            }
9508        }
9509        if (!allowed) {
9510            if (!allowed && (bp.protectionLevel
9511                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9512                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9513                // If this was a previously normal/dangerous permission that got moved
9514                // to a system permission as part of the runtime permission redesign, then
9515                // we still want to blindly grant it to old apps.
9516                allowed = true;
9517            }
9518            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9519                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9520                // If this permission is to be granted to the system installer and
9521                // this app is an installer, then it gets the permission.
9522                allowed = true;
9523            }
9524            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9525                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9526                // If this permission is to be granted to the system verifier and
9527                // this app is a verifier, then it gets the permission.
9528                allowed = true;
9529            }
9530            if (!allowed && (bp.protectionLevel
9531                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9532                    && isSystemApp(pkg)) {
9533                // Any pre-installed system app is allowed to get this permission.
9534                allowed = true;
9535            }
9536            if (!allowed && (bp.protectionLevel
9537                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9538                // For development permissions, a development permission
9539                // is granted only if it was already granted.
9540                allowed = origPermissions.hasInstallPermission(perm);
9541            }
9542        }
9543        return allowed;
9544    }
9545
9546    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9547        final int permCount = pkg.requestedPermissions.size();
9548        for (int j = 0; j < permCount; j++) {
9549            String requestedPermission = pkg.requestedPermissions.get(j);
9550            if (permission.equals(requestedPermission)) {
9551                return true;
9552            }
9553        }
9554        return false;
9555    }
9556
9557    final class ActivityIntentResolver
9558            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9559        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9560                boolean defaultOnly, int userId) {
9561            if (!sUserManager.exists(userId)) return null;
9562            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9563            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9564        }
9565
9566        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9567                int userId) {
9568            if (!sUserManager.exists(userId)) return null;
9569            mFlags = flags;
9570            return super.queryIntent(intent, resolvedType,
9571                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9572        }
9573
9574        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9575                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9576            if (!sUserManager.exists(userId)) return null;
9577            if (packageActivities == null) {
9578                return null;
9579            }
9580            mFlags = flags;
9581            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9582            final int N = packageActivities.size();
9583            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9584                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9585
9586            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9587            for (int i = 0; i < N; ++i) {
9588                intentFilters = packageActivities.get(i).intents;
9589                if (intentFilters != null && intentFilters.size() > 0) {
9590                    PackageParser.ActivityIntentInfo[] array =
9591                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9592                    intentFilters.toArray(array);
9593                    listCut.add(array);
9594                }
9595            }
9596            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9597        }
9598
9599        public final void addActivity(PackageParser.Activity a, String type) {
9600            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9601            mActivities.put(a.getComponentName(), a);
9602            if (DEBUG_SHOW_INFO)
9603                Log.v(
9604                TAG, "  " + type + " " +
9605                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9606            if (DEBUG_SHOW_INFO)
9607                Log.v(TAG, "    Class=" + a.info.name);
9608            final int NI = a.intents.size();
9609            for (int j=0; j<NI; j++) {
9610                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9611                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9612                    intent.setPriority(0);
9613                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9614                            + a.className + " with priority > 0, forcing to 0");
9615                }
9616                if (DEBUG_SHOW_INFO) {
9617                    Log.v(TAG, "    IntentFilter:");
9618                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9619                }
9620                if (!intent.debugCheck()) {
9621                    Log.w(TAG, "==> For Activity " + a.info.name);
9622                }
9623                addFilter(intent);
9624            }
9625        }
9626
9627        public final void removeActivity(PackageParser.Activity a, String type) {
9628            mActivities.remove(a.getComponentName());
9629            if (DEBUG_SHOW_INFO) {
9630                Log.v(TAG, "  " + type + " "
9631                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9632                                : a.info.name) + ":");
9633                Log.v(TAG, "    Class=" + a.info.name);
9634            }
9635            final int NI = a.intents.size();
9636            for (int j=0; j<NI; j++) {
9637                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9638                if (DEBUG_SHOW_INFO) {
9639                    Log.v(TAG, "    IntentFilter:");
9640                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9641                }
9642                removeFilter(intent);
9643            }
9644        }
9645
9646        @Override
9647        protected boolean allowFilterResult(
9648                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9649            ActivityInfo filterAi = filter.activity.info;
9650            for (int i=dest.size()-1; i>=0; i--) {
9651                ActivityInfo destAi = dest.get(i).activityInfo;
9652                if (destAi.name == filterAi.name
9653                        && destAi.packageName == filterAi.packageName) {
9654                    return false;
9655                }
9656            }
9657            return true;
9658        }
9659
9660        @Override
9661        protected ActivityIntentInfo[] newArray(int size) {
9662            return new ActivityIntentInfo[size];
9663        }
9664
9665        @Override
9666        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9667            if (!sUserManager.exists(userId)) return true;
9668            PackageParser.Package p = filter.activity.owner;
9669            if (p != null) {
9670                PackageSetting ps = (PackageSetting)p.mExtras;
9671                if (ps != null) {
9672                    // System apps are never considered stopped for purposes of
9673                    // filtering, because there may be no way for the user to
9674                    // actually re-launch them.
9675                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9676                            && ps.getStopped(userId);
9677                }
9678            }
9679            return false;
9680        }
9681
9682        @Override
9683        protected boolean isPackageForFilter(String packageName,
9684                PackageParser.ActivityIntentInfo info) {
9685            return packageName.equals(info.activity.owner.packageName);
9686        }
9687
9688        @Override
9689        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9690                int match, int userId) {
9691            if (!sUserManager.exists(userId)) return null;
9692            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9693                return null;
9694            }
9695            final PackageParser.Activity activity = info.activity;
9696            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9697            if (ps == null) {
9698                return null;
9699            }
9700            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9701                    ps.readUserState(userId), userId);
9702            if (ai == null) {
9703                return null;
9704            }
9705            final ResolveInfo res = new ResolveInfo();
9706            res.activityInfo = ai;
9707            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9708                res.filter = info;
9709            }
9710            if (info != null) {
9711                res.handleAllWebDataURI = info.handleAllWebDataURI();
9712            }
9713            res.priority = info.getPriority();
9714            res.preferredOrder = activity.owner.mPreferredOrder;
9715            //System.out.println("Result: " + res.activityInfo.className +
9716            //                   " = " + res.priority);
9717            res.match = match;
9718            res.isDefault = info.hasDefault;
9719            res.labelRes = info.labelRes;
9720            res.nonLocalizedLabel = info.nonLocalizedLabel;
9721            if (userNeedsBadging(userId)) {
9722                res.noResourceId = true;
9723            } else {
9724                res.icon = info.icon;
9725            }
9726            res.iconResourceId = info.icon;
9727            res.system = res.activityInfo.applicationInfo.isSystemApp();
9728            return res;
9729        }
9730
9731        @Override
9732        protected void sortResults(List<ResolveInfo> results) {
9733            Collections.sort(results, mResolvePrioritySorter);
9734        }
9735
9736        @Override
9737        protected void dumpFilter(PrintWriter out, String prefix,
9738                PackageParser.ActivityIntentInfo filter) {
9739            out.print(prefix); out.print(
9740                    Integer.toHexString(System.identityHashCode(filter.activity)));
9741                    out.print(' ');
9742                    filter.activity.printComponentShortName(out);
9743                    out.print(" filter ");
9744                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9745        }
9746
9747        @Override
9748        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9749            return filter.activity;
9750        }
9751
9752        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9753            PackageParser.Activity activity = (PackageParser.Activity)label;
9754            out.print(prefix); out.print(
9755                    Integer.toHexString(System.identityHashCode(activity)));
9756                    out.print(' ');
9757                    activity.printComponentShortName(out);
9758            if (count > 1) {
9759                out.print(" ("); out.print(count); out.print(" filters)");
9760            }
9761            out.println();
9762        }
9763
9764//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9765//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9766//            final List<ResolveInfo> retList = Lists.newArrayList();
9767//            while (i.hasNext()) {
9768//                final ResolveInfo resolveInfo = i.next();
9769//                if (isEnabledLP(resolveInfo.activityInfo)) {
9770//                    retList.add(resolveInfo);
9771//                }
9772//            }
9773//            return retList;
9774//        }
9775
9776        // Keys are String (activity class name), values are Activity.
9777        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9778                = new ArrayMap<ComponentName, PackageParser.Activity>();
9779        private int mFlags;
9780    }
9781
9782    private final class ServiceIntentResolver
9783            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9784        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9785                boolean defaultOnly, int userId) {
9786            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9787            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9788        }
9789
9790        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9791                int userId) {
9792            if (!sUserManager.exists(userId)) return null;
9793            mFlags = flags;
9794            return super.queryIntent(intent, resolvedType,
9795                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9796        }
9797
9798        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9799                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9800            if (!sUserManager.exists(userId)) return null;
9801            if (packageServices == null) {
9802                return null;
9803            }
9804            mFlags = flags;
9805            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9806            final int N = packageServices.size();
9807            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9808                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9809
9810            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9811            for (int i = 0; i < N; ++i) {
9812                intentFilters = packageServices.get(i).intents;
9813                if (intentFilters != null && intentFilters.size() > 0) {
9814                    PackageParser.ServiceIntentInfo[] array =
9815                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9816                    intentFilters.toArray(array);
9817                    listCut.add(array);
9818                }
9819            }
9820            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9821        }
9822
9823        public final void addService(PackageParser.Service s) {
9824            mServices.put(s.getComponentName(), s);
9825            if (DEBUG_SHOW_INFO) {
9826                Log.v(TAG, "  "
9827                        + (s.info.nonLocalizedLabel != null
9828                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9829                Log.v(TAG, "    Class=" + s.info.name);
9830            }
9831            final int NI = s.intents.size();
9832            int j;
9833            for (j=0; j<NI; j++) {
9834                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9835                if (DEBUG_SHOW_INFO) {
9836                    Log.v(TAG, "    IntentFilter:");
9837                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9838                }
9839                if (!intent.debugCheck()) {
9840                    Log.w(TAG, "==> For Service " + s.info.name);
9841                }
9842                addFilter(intent);
9843            }
9844        }
9845
9846        public final void removeService(PackageParser.Service s) {
9847            mServices.remove(s.getComponentName());
9848            if (DEBUG_SHOW_INFO) {
9849                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9850                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9851                Log.v(TAG, "    Class=" + s.info.name);
9852            }
9853            final int NI = s.intents.size();
9854            int j;
9855            for (j=0; j<NI; j++) {
9856                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9857                if (DEBUG_SHOW_INFO) {
9858                    Log.v(TAG, "    IntentFilter:");
9859                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9860                }
9861                removeFilter(intent);
9862            }
9863        }
9864
9865        @Override
9866        protected boolean allowFilterResult(
9867                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9868            ServiceInfo filterSi = filter.service.info;
9869            for (int i=dest.size()-1; i>=0; i--) {
9870                ServiceInfo destAi = dest.get(i).serviceInfo;
9871                if (destAi.name == filterSi.name
9872                        && destAi.packageName == filterSi.packageName) {
9873                    return false;
9874                }
9875            }
9876            return true;
9877        }
9878
9879        @Override
9880        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9881            return new PackageParser.ServiceIntentInfo[size];
9882        }
9883
9884        @Override
9885        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9886            if (!sUserManager.exists(userId)) return true;
9887            PackageParser.Package p = filter.service.owner;
9888            if (p != null) {
9889                PackageSetting ps = (PackageSetting)p.mExtras;
9890                if (ps != null) {
9891                    // System apps are never considered stopped for purposes of
9892                    // filtering, because there may be no way for the user to
9893                    // actually re-launch them.
9894                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9895                            && ps.getStopped(userId);
9896                }
9897            }
9898            return false;
9899        }
9900
9901        @Override
9902        protected boolean isPackageForFilter(String packageName,
9903                PackageParser.ServiceIntentInfo info) {
9904            return packageName.equals(info.service.owner.packageName);
9905        }
9906
9907        @Override
9908        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9909                int match, int userId) {
9910            if (!sUserManager.exists(userId)) return null;
9911            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9912            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9913                return null;
9914            }
9915            final PackageParser.Service service = info.service;
9916            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9917            if (ps == null) {
9918                return null;
9919            }
9920            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9921                    ps.readUserState(userId), userId);
9922            if (si == null) {
9923                return null;
9924            }
9925            final ResolveInfo res = new ResolveInfo();
9926            res.serviceInfo = si;
9927            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9928                res.filter = filter;
9929            }
9930            res.priority = info.getPriority();
9931            res.preferredOrder = service.owner.mPreferredOrder;
9932            res.match = match;
9933            res.isDefault = info.hasDefault;
9934            res.labelRes = info.labelRes;
9935            res.nonLocalizedLabel = info.nonLocalizedLabel;
9936            res.icon = info.icon;
9937            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9938            return res;
9939        }
9940
9941        @Override
9942        protected void sortResults(List<ResolveInfo> results) {
9943            Collections.sort(results, mResolvePrioritySorter);
9944        }
9945
9946        @Override
9947        protected void dumpFilter(PrintWriter out, String prefix,
9948                PackageParser.ServiceIntentInfo filter) {
9949            out.print(prefix); out.print(
9950                    Integer.toHexString(System.identityHashCode(filter.service)));
9951                    out.print(' ');
9952                    filter.service.printComponentShortName(out);
9953                    out.print(" filter ");
9954                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9955        }
9956
9957        @Override
9958        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9959            return filter.service;
9960        }
9961
9962        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9963            PackageParser.Service service = (PackageParser.Service)label;
9964            out.print(prefix); out.print(
9965                    Integer.toHexString(System.identityHashCode(service)));
9966                    out.print(' ');
9967                    service.printComponentShortName(out);
9968            if (count > 1) {
9969                out.print(" ("); out.print(count); out.print(" filters)");
9970            }
9971            out.println();
9972        }
9973
9974//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9975//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9976//            final List<ResolveInfo> retList = Lists.newArrayList();
9977//            while (i.hasNext()) {
9978//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9979//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9980//                    retList.add(resolveInfo);
9981//                }
9982//            }
9983//            return retList;
9984//        }
9985
9986        // Keys are String (activity class name), values are Activity.
9987        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9988                = new ArrayMap<ComponentName, PackageParser.Service>();
9989        private int mFlags;
9990    };
9991
9992    private final class ProviderIntentResolver
9993            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9994        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9995                boolean defaultOnly, int userId) {
9996            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9997            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9998        }
9999
10000        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10001                int userId) {
10002            if (!sUserManager.exists(userId))
10003                return null;
10004            mFlags = flags;
10005            return super.queryIntent(intent, resolvedType,
10006                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10007        }
10008
10009        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10010                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10011            if (!sUserManager.exists(userId))
10012                return null;
10013            if (packageProviders == null) {
10014                return null;
10015            }
10016            mFlags = flags;
10017            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10018            final int N = packageProviders.size();
10019            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10020                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10021
10022            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10023            for (int i = 0; i < N; ++i) {
10024                intentFilters = packageProviders.get(i).intents;
10025                if (intentFilters != null && intentFilters.size() > 0) {
10026                    PackageParser.ProviderIntentInfo[] array =
10027                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10028                    intentFilters.toArray(array);
10029                    listCut.add(array);
10030                }
10031            }
10032            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10033        }
10034
10035        public final void addProvider(PackageParser.Provider p) {
10036            if (mProviders.containsKey(p.getComponentName())) {
10037                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10038                return;
10039            }
10040
10041            mProviders.put(p.getComponentName(), p);
10042            if (DEBUG_SHOW_INFO) {
10043                Log.v(TAG, "  "
10044                        + (p.info.nonLocalizedLabel != null
10045                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10046                Log.v(TAG, "    Class=" + p.info.name);
10047            }
10048            final int NI = p.intents.size();
10049            int j;
10050            for (j = 0; j < NI; j++) {
10051                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10052                if (DEBUG_SHOW_INFO) {
10053                    Log.v(TAG, "    IntentFilter:");
10054                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10055                }
10056                if (!intent.debugCheck()) {
10057                    Log.w(TAG, "==> For Provider " + p.info.name);
10058                }
10059                addFilter(intent);
10060            }
10061        }
10062
10063        public final void removeProvider(PackageParser.Provider p) {
10064            mProviders.remove(p.getComponentName());
10065            if (DEBUG_SHOW_INFO) {
10066                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10067                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10068                Log.v(TAG, "    Class=" + p.info.name);
10069            }
10070            final int NI = p.intents.size();
10071            int j;
10072            for (j = 0; j < NI; j++) {
10073                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10074                if (DEBUG_SHOW_INFO) {
10075                    Log.v(TAG, "    IntentFilter:");
10076                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10077                }
10078                removeFilter(intent);
10079            }
10080        }
10081
10082        @Override
10083        protected boolean allowFilterResult(
10084                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10085            ProviderInfo filterPi = filter.provider.info;
10086            for (int i = dest.size() - 1; i >= 0; i--) {
10087                ProviderInfo destPi = dest.get(i).providerInfo;
10088                if (destPi.name == filterPi.name
10089                        && destPi.packageName == filterPi.packageName) {
10090                    return false;
10091                }
10092            }
10093            return true;
10094        }
10095
10096        @Override
10097        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10098            return new PackageParser.ProviderIntentInfo[size];
10099        }
10100
10101        @Override
10102        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10103            if (!sUserManager.exists(userId))
10104                return true;
10105            PackageParser.Package p = filter.provider.owner;
10106            if (p != null) {
10107                PackageSetting ps = (PackageSetting) p.mExtras;
10108                if (ps != null) {
10109                    // System apps are never considered stopped for purposes of
10110                    // filtering, because there may be no way for the user to
10111                    // actually re-launch them.
10112                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10113                            && ps.getStopped(userId);
10114                }
10115            }
10116            return false;
10117        }
10118
10119        @Override
10120        protected boolean isPackageForFilter(String packageName,
10121                PackageParser.ProviderIntentInfo info) {
10122            return packageName.equals(info.provider.owner.packageName);
10123        }
10124
10125        @Override
10126        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10127                int match, int userId) {
10128            if (!sUserManager.exists(userId))
10129                return null;
10130            final PackageParser.ProviderIntentInfo info = filter;
10131            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10132                return null;
10133            }
10134            final PackageParser.Provider provider = info.provider;
10135            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10136            if (ps == null) {
10137                return null;
10138            }
10139            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10140                    ps.readUserState(userId), userId);
10141            if (pi == null) {
10142                return null;
10143            }
10144            final ResolveInfo res = new ResolveInfo();
10145            res.providerInfo = pi;
10146            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10147                res.filter = filter;
10148            }
10149            res.priority = info.getPriority();
10150            res.preferredOrder = provider.owner.mPreferredOrder;
10151            res.match = match;
10152            res.isDefault = info.hasDefault;
10153            res.labelRes = info.labelRes;
10154            res.nonLocalizedLabel = info.nonLocalizedLabel;
10155            res.icon = info.icon;
10156            res.system = res.providerInfo.applicationInfo.isSystemApp();
10157            return res;
10158        }
10159
10160        @Override
10161        protected void sortResults(List<ResolveInfo> results) {
10162            Collections.sort(results, mResolvePrioritySorter);
10163        }
10164
10165        @Override
10166        protected void dumpFilter(PrintWriter out, String prefix,
10167                PackageParser.ProviderIntentInfo filter) {
10168            out.print(prefix);
10169            out.print(
10170                    Integer.toHexString(System.identityHashCode(filter.provider)));
10171            out.print(' ');
10172            filter.provider.printComponentShortName(out);
10173            out.print(" filter ");
10174            out.println(Integer.toHexString(System.identityHashCode(filter)));
10175        }
10176
10177        @Override
10178        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10179            return filter.provider;
10180        }
10181
10182        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10183            PackageParser.Provider provider = (PackageParser.Provider)label;
10184            out.print(prefix); out.print(
10185                    Integer.toHexString(System.identityHashCode(provider)));
10186                    out.print(' ');
10187                    provider.printComponentShortName(out);
10188            if (count > 1) {
10189                out.print(" ("); out.print(count); out.print(" filters)");
10190            }
10191            out.println();
10192        }
10193
10194        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10195                = new ArrayMap<ComponentName, PackageParser.Provider>();
10196        private int mFlags;
10197    }
10198
10199    private static final class EphemeralIntentResolver
10200            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10201        @Override
10202        protected EphemeralResolveIntentInfo[] newArray(int size) {
10203            return new EphemeralResolveIntentInfo[size];
10204        }
10205
10206        @Override
10207        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10208            return true;
10209        }
10210
10211        @Override
10212        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10213                int userId) {
10214            if (!sUserManager.exists(userId)) {
10215                return null;
10216            }
10217            return info.getEphemeralResolveInfo();
10218        }
10219    }
10220
10221    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10222            new Comparator<ResolveInfo>() {
10223        public int compare(ResolveInfo r1, ResolveInfo r2) {
10224            int v1 = r1.priority;
10225            int v2 = r2.priority;
10226            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10227            if (v1 != v2) {
10228                return (v1 > v2) ? -1 : 1;
10229            }
10230            v1 = r1.preferredOrder;
10231            v2 = r2.preferredOrder;
10232            if (v1 != v2) {
10233                return (v1 > v2) ? -1 : 1;
10234            }
10235            if (r1.isDefault != r2.isDefault) {
10236                return r1.isDefault ? -1 : 1;
10237            }
10238            v1 = r1.match;
10239            v2 = r2.match;
10240            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10241            if (v1 != v2) {
10242                return (v1 > v2) ? -1 : 1;
10243            }
10244            if (r1.system != r2.system) {
10245                return r1.system ? -1 : 1;
10246            }
10247            if (r1.activityInfo != null) {
10248                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10249            }
10250            if (r1.serviceInfo != null) {
10251                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10252            }
10253            if (r1.providerInfo != null) {
10254                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10255            }
10256            return 0;
10257        }
10258    };
10259
10260    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10261            new Comparator<ProviderInfo>() {
10262        public int compare(ProviderInfo p1, ProviderInfo p2) {
10263            final int v1 = p1.initOrder;
10264            final int v2 = p2.initOrder;
10265            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10266        }
10267    };
10268
10269    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10270            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10271            final int[] userIds) {
10272        mHandler.post(new Runnable() {
10273            @Override
10274            public void run() {
10275                try {
10276                    final IActivityManager am = ActivityManagerNative.getDefault();
10277                    if (am == null) return;
10278                    final int[] resolvedUserIds;
10279                    if (userIds == null) {
10280                        resolvedUserIds = am.getRunningUserIds();
10281                    } else {
10282                        resolvedUserIds = userIds;
10283                    }
10284                    for (int id : resolvedUserIds) {
10285                        final Intent intent = new Intent(action,
10286                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10287                        if (extras != null) {
10288                            intent.putExtras(extras);
10289                        }
10290                        if (targetPkg != null) {
10291                            intent.setPackage(targetPkg);
10292                        }
10293                        // Modify the UID when posting to other users
10294                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10295                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10296                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10297                            intent.putExtra(Intent.EXTRA_UID, uid);
10298                        }
10299                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10300                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10301                        if (DEBUG_BROADCASTS) {
10302                            RuntimeException here = new RuntimeException("here");
10303                            here.fillInStackTrace();
10304                            Slog.d(TAG, "Sending to user " + id + ": "
10305                                    + intent.toShortString(false, true, false, false)
10306                                    + " " + intent.getExtras(), here);
10307                        }
10308                        am.broadcastIntent(null, intent, null, finishedReceiver,
10309                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10310                                null, finishedReceiver != null, false, id);
10311                    }
10312                } catch (RemoteException ex) {
10313                }
10314            }
10315        });
10316    }
10317
10318    /**
10319     * Check if the external storage media is available. This is true if there
10320     * is a mounted external storage medium or if the external storage is
10321     * emulated.
10322     */
10323    private boolean isExternalMediaAvailable() {
10324        return mMediaMounted || Environment.isExternalStorageEmulated();
10325    }
10326
10327    @Override
10328    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10329        // writer
10330        synchronized (mPackages) {
10331            if (!isExternalMediaAvailable()) {
10332                // If the external storage is no longer mounted at this point,
10333                // the caller may not have been able to delete all of this
10334                // packages files and can not delete any more.  Bail.
10335                return null;
10336            }
10337            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10338            if (lastPackage != null) {
10339                pkgs.remove(lastPackage);
10340            }
10341            if (pkgs.size() > 0) {
10342                return pkgs.get(0);
10343            }
10344        }
10345        return null;
10346    }
10347
10348    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10349        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10350                userId, andCode ? 1 : 0, packageName);
10351        if (mSystemReady) {
10352            msg.sendToTarget();
10353        } else {
10354            if (mPostSystemReadyMessages == null) {
10355                mPostSystemReadyMessages = new ArrayList<>();
10356            }
10357            mPostSystemReadyMessages.add(msg);
10358        }
10359    }
10360
10361    void startCleaningPackages() {
10362        // reader
10363        synchronized (mPackages) {
10364            if (!isExternalMediaAvailable()) {
10365                return;
10366            }
10367            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10368                return;
10369            }
10370        }
10371        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10372        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10373        IActivityManager am = ActivityManagerNative.getDefault();
10374        if (am != null) {
10375            try {
10376                am.startService(null, intent, null, mContext.getOpPackageName(),
10377                        UserHandle.USER_SYSTEM);
10378            } catch (RemoteException e) {
10379            }
10380        }
10381    }
10382
10383    @Override
10384    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10385            int installFlags, String installerPackageName, VerificationParams verificationParams,
10386            String packageAbiOverride) {
10387        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10388                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10389    }
10390
10391    @Override
10392    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10393            int installFlags, String installerPackageName, VerificationParams verificationParams,
10394            String packageAbiOverride, int userId) {
10395        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10396
10397        final int callingUid = Binder.getCallingUid();
10398        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10399
10400        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10401            try {
10402                if (observer != null) {
10403                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10404                }
10405            } catch (RemoteException re) {
10406            }
10407            return;
10408        }
10409
10410        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10411            installFlags |= PackageManager.INSTALL_FROM_ADB;
10412
10413        } else {
10414            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10415            // about installerPackageName.
10416
10417            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10418            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10419        }
10420
10421        UserHandle user;
10422        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10423            user = UserHandle.ALL;
10424        } else {
10425            user = new UserHandle(userId);
10426        }
10427
10428        // Only system components can circumvent runtime permissions when installing.
10429        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10430                && mContext.checkCallingOrSelfPermission(Manifest.permission
10431                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10432            throw new SecurityException("You need the "
10433                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10434                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10435        }
10436
10437        verificationParams.setInstallerUid(callingUid);
10438
10439        final File originFile = new File(originPath);
10440        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10441
10442        final Message msg = mHandler.obtainMessage(INIT_COPY);
10443        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10444                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10445        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10446        msg.obj = params;
10447
10448        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10449                System.identityHashCode(msg.obj));
10450        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10451                System.identityHashCode(msg.obj));
10452
10453        mHandler.sendMessage(msg);
10454    }
10455
10456    void installStage(String packageName, File stagedDir, String stagedCid,
10457            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10458            String installerPackageName, int installerUid, UserHandle user) {
10459        if (DEBUG_EPHEMERAL) {
10460            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10461                Slog.d(TAG, "Ephemeral install of " + packageName);
10462            }
10463        }
10464        final VerificationParams verifParams = new VerificationParams(
10465                null, sessionParams.originatingUri, sessionParams.referrerUri,
10466                sessionParams.originatingUid);
10467        verifParams.setInstallerUid(installerUid);
10468
10469        final OriginInfo origin;
10470        if (stagedDir != null) {
10471            origin = OriginInfo.fromStagedFile(stagedDir);
10472        } else {
10473            origin = OriginInfo.fromStagedContainer(stagedCid);
10474        }
10475
10476        final Message msg = mHandler.obtainMessage(INIT_COPY);
10477        final InstallParams params = new InstallParams(origin, null, observer,
10478                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10479                verifParams, user, sessionParams.abiOverride,
10480                sessionParams.grantedRuntimePermissions);
10481        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10482        msg.obj = params;
10483
10484        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10485                System.identityHashCode(msg.obj));
10486        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10487                System.identityHashCode(msg.obj));
10488
10489        mHandler.sendMessage(msg);
10490    }
10491
10492    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10493            int userId) {
10494        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10495        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10496    }
10497
10498    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10499            int appId, int userId) {
10500        Bundle extras = new Bundle(1);
10501        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10502
10503        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10504                packageName, extras, 0, null, null, new int[] {userId});
10505        try {
10506            IActivityManager am = ActivityManagerNative.getDefault();
10507            if (isSystem && am.isUserRunning(userId, 0)) {
10508                // The just-installed/enabled app is bundled on the system, so presumed
10509                // to be able to run automatically without needing an explicit launch.
10510                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10511                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10512                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10513                        .setPackage(packageName);
10514                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10515                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10516            }
10517        } catch (RemoteException e) {
10518            // shouldn't happen
10519            Slog.w(TAG, "Unable to bootstrap installed package", e);
10520        }
10521    }
10522
10523    @Override
10524    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10525            int userId) {
10526        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10527        PackageSetting pkgSetting;
10528        final int uid = Binder.getCallingUid();
10529        enforceCrossUserPermission(uid, userId, true, true,
10530                "setApplicationHiddenSetting for user " + userId);
10531
10532        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10533            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10534            return false;
10535        }
10536
10537        long callingId = Binder.clearCallingIdentity();
10538        try {
10539            boolean sendAdded = false;
10540            boolean sendRemoved = false;
10541            // writer
10542            synchronized (mPackages) {
10543                pkgSetting = mSettings.mPackages.get(packageName);
10544                if (pkgSetting == null) {
10545                    return false;
10546                }
10547                if (pkgSetting.getHidden(userId) != hidden) {
10548                    pkgSetting.setHidden(hidden, userId);
10549                    mSettings.writePackageRestrictionsLPr(userId);
10550                    if (hidden) {
10551                        sendRemoved = true;
10552                    } else {
10553                        sendAdded = true;
10554                    }
10555                }
10556            }
10557            if (sendAdded) {
10558                sendPackageAddedForUser(packageName, pkgSetting, userId);
10559                return true;
10560            }
10561            if (sendRemoved) {
10562                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10563                        "hiding pkg");
10564                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10565                return true;
10566            }
10567        } finally {
10568            Binder.restoreCallingIdentity(callingId);
10569        }
10570        return false;
10571    }
10572
10573    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10574            int userId) {
10575        final PackageRemovedInfo info = new PackageRemovedInfo();
10576        info.removedPackage = packageName;
10577        info.removedUsers = new int[] {userId};
10578        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10579        info.sendPackageRemovedBroadcasts();
10580    }
10581
10582    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10583        if (pkgList.length > 0) {
10584            Bundle extras = new Bundle(1);
10585            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10586
10587            sendPackageBroadcast(
10588                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10589                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10590                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10591                    new int[] {userId});
10592        }
10593    }
10594
10595    /**
10596     * Returns true if application is not found or there was an error. Otherwise it returns
10597     * the hidden state of the package for the given user.
10598     */
10599    @Override
10600    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10601        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10602        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10603                false, "getApplicationHidden for user " + userId);
10604        PackageSetting pkgSetting;
10605        long callingId = Binder.clearCallingIdentity();
10606        try {
10607            // writer
10608            synchronized (mPackages) {
10609                pkgSetting = mSettings.mPackages.get(packageName);
10610                if (pkgSetting == null) {
10611                    return true;
10612                }
10613                return pkgSetting.getHidden(userId);
10614            }
10615        } finally {
10616            Binder.restoreCallingIdentity(callingId);
10617        }
10618    }
10619
10620    /**
10621     * @hide
10622     */
10623    @Override
10624    public int installExistingPackageAsUser(String packageName, int userId) {
10625        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10626                null);
10627        PackageSetting pkgSetting;
10628        final int uid = Binder.getCallingUid();
10629        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10630                + userId);
10631        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10632            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10633        }
10634
10635        long callingId = Binder.clearCallingIdentity();
10636        try {
10637            boolean installed = false;
10638
10639            // writer
10640            synchronized (mPackages) {
10641                pkgSetting = mSettings.mPackages.get(packageName);
10642                if (pkgSetting == null) {
10643                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10644                }
10645                if (!pkgSetting.getInstalled(userId)) {
10646                    pkgSetting.setInstalled(true, userId);
10647                    pkgSetting.setHidden(false, userId);
10648                    mSettings.writePackageRestrictionsLPr(userId);
10649                    if (pkgSetting.pkg != null) {
10650                        prepareAppDataAfterInstall(pkgSetting.pkg);
10651                    }
10652                    installed = true;
10653                }
10654            }
10655
10656            if (installed) {
10657                sendPackageAddedForUser(packageName, pkgSetting, userId);
10658            }
10659        } finally {
10660            Binder.restoreCallingIdentity(callingId);
10661        }
10662
10663        return PackageManager.INSTALL_SUCCEEDED;
10664    }
10665
10666    boolean isUserRestricted(int userId, String restrictionKey) {
10667        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10668        if (restrictions.getBoolean(restrictionKey, false)) {
10669            Log.w(TAG, "User is restricted: " + restrictionKey);
10670            return true;
10671        }
10672        return false;
10673    }
10674
10675    @Override
10676    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10677        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10678        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10679                "setPackageSuspended for user " + userId);
10680
10681        // TODO: investigate and add more restrictions for suspending crucial packages.
10682        if (isPackageDeviceAdmin(packageName, userId)) {
10683            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10684                    + "\": has active device admin");
10685            return false;
10686        }
10687
10688        long callingId = Binder.clearCallingIdentity();
10689        try {
10690            boolean changed = false;
10691            boolean success = false;
10692            int appId = -1;
10693            synchronized (mPackages) {
10694                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10695                if (pkgSetting != null) {
10696                    if (pkgSetting.getSuspended(userId) != suspended) {
10697                        pkgSetting.setSuspended(suspended, userId);
10698                        mSettings.writePackageRestrictionsLPr(userId);
10699                        appId = pkgSetting.appId;
10700                        changed = true;
10701                    }
10702                    success = true;
10703                }
10704            }
10705
10706            if (changed) {
10707                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10708                if (suspended) {
10709                    killApplication(packageName, UserHandle.getUid(userId, appId),
10710                            "suspending package");
10711                }
10712            }
10713            return success;
10714        } finally {
10715            Binder.restoreCallingIdentity(callingId);
10716        }
10717    }
10718
10719    @Override
10720    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10721        mContext.enforceCallingOrSelfPermission(
10722                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10723                "Only package verification agents can verify applications");
10724
10725        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10726        final PackageVerificationResponse response = new PackageVerificationResponse(
10727                verificationCode, Binder.getCallingUid());
10728        msg.arg1 = id;
10729        msg.obj = response;
10730        mHandler.sendMessage(msg);
10731    }
10732
10733    @Override
10734    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10735            long millisecondsToDelay) {
10736        mContext.enforceCallingOrSelfPermission(
10737                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10738                "Only package verification agents can extend verification timeouts");
10739
10740        final PackageVerificationState state = mPendingVerification.get(id);
10741        final PackageVerificationResponse response = new PackageVerificationResponse(
10742                verificationCodeAtTimeout, Binder.getCallingUid());
10743
10744        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10745            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10746        }
10747        if (millisecondsToDelay < 0) {
10748            millisecondsToDelay = 0;
10749        }
10750        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10751                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10752            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10753        }
10754
10755        if ((state != null) && !state.timeoutExtended()) {
10756            state.extendTimeout();
10757
10758            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10759            msg.arg1 = id;
10760            msg.obj = response;
10761            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10762        }
10763    }
10764
10765    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10766            int verificationCode, UserHandle user) {
10767        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10768        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10769        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10770        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10771        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10772
10773        mContext.sendBroadcastAsUser(intent, user,
10774                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10775    }
10776
10777    private ComponentName matchComponentForVerifier(String packageName,
10778            List<ResolveInfo> receivers) {
10779        ActivityInfo targetReceiver = null;
10780
10781        final int NR = receivers.size();
10782        for (int i = 0; i < NR; i++) {
10783            final ResolveInfo info = receivers.get(i);
10784            if (info.activityInfo == null) {
10785                continue;
10786            }
10787
10788            if (packageName.equals(info.activityInfo.packageName)) {
10789                targetReceiver = info.activityInfo;
10790                break;
10791            }
10792        }
10793
10794        if (targetReceiver == null) {
10795            return null;
10796        }
10797
10798        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10799    }
10800
10801    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10802            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10803        if (pkgInfo.verifiers.length == 0) {
10804            return null;
10805        }
10806
10807        final int N = pkgInfo.verifiers.length;
10808        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10809        for (int i = 0; i < N; i++) {
10810            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10811
10812            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10813                    receivers);
10814            if (comp == null) {
10815                continue;
10816            }
10817
10818            final int verifierUid = getUidForVerifier(verifierInfo);
10819            if (verifierUid == -1) {
10820                continue;
10821            }
10822
10823            if (DEBUG_VERIFY) {
10824                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10825                        + " with the correct signature");
10826            }
10827            sufficientVerifiers.add(comp);
10828            verificationState.addSufficientVerifier(verifierUid);
10829        }
10830
10831        return sufficientVerifiers;
10832    }
10833
10834    private int getUidForVerifier(VerifierInfo verifierInfo) {
10835        synchronized (mPackages) {
10836            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10837            if (pkg == null) {
10838                return -1;
10839            } else if (pkg.mSignatures.length != 1) {
10840                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10841                        + " has more than one signature; ignoring");
10842                return -1;
10843            }
10844
10845            /*
10846             * If the public key of the package's signature does not match
10847             * our expected public key, then this is a different package and
10848             * we should skip.
10849             */
10850
10851            final byte[] expectedPublicKey;
10852            try {
10853                final Signature verifierSig = pkg.mSignatures[0];
10854                final PublicKey publicKey = verifierSig.getPublicKey();
10855                expectedPublicKey = publicKey.getEncoded();
10856            } catch (CertificateException e) {
10857                return -1;
10858            }
10859
10860            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10861
10862            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10863                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10864                        + " does not have the expected public key; ignoring");
10865                return -1;
10866            }
10867
10868            return pkg.applicationInfo.uid;
10869        }
10870    }
10871
10872    @Override
10873    public void finishPackageInstall(int token) {
10874        enforceSystemOrRoot("Only the system is allowed to finish installs");
10875
10876        if (DEBUG_INSTALL) {
10877            Slog.v(TAG, "BM finishing package install for " + token);
10878        }
10879        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10880
10881        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10882        mHandler.sendMessage(msg);
10883    }
10884
10885    /**
10886     * Get the verification agent timeout.
10887     *
10888     * @return verification timeout in milliseconds
10889     */
10890    private long getVerificationTimeout() {
10891        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10892                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10893                DEFAULT_VERIFICATION_TIMEOUT);
10894    }
10895
10896    /**
10897     * Get the default verification agent response code.
10898     *
10899     * @return default verification response code
10900     */
10901    private int getDefaultVerificationResponse() {
10902        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10903                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10904                DEFAULT_VERIFICATION_RESPONSE);
10905    }
10906
10907    /**
10908     * Check whether or not package verification has been enabled.
10909     *
10910     * @return true if verification should be performed
10911     */
10912    private boolean isVerificationEnabled(int userId, int installFlags) {
10913        if (!DEFAULT_VERIFY_ENABLE) {
10914            return false;
10915        }
10916        // Ephemeral apps don't get the full verification treatment
10917        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10918            if (DEBUG_EPHEMERAL) {
10919                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10920            }
10921            return false;
10922        }
10923
10924        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10925
10926        // Check if installing from ADB
10927        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10928            // Do not run verification in a test harness environment
10929            if (ActivityManager.isRunningInTestHarness()) {
10930                return false;
10931            }
10932            if (ensureVerifyAppsEnabled) {
10933                return true;
10934            }
10935            // Check if the developer does not want package verification for ADB installs
10936            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10937                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10938                return false;
10939            }
10940        }
10941
10942        if (ensureVerifyAppsEnabled) {
10943            return true;
10944        }
10945
10946        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10947                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10948    }
10949
10950    @Override
10951    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10952            throws RemoteException {
10953        mContext.enforceCallingOrSelfPermission(
10954                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10955                "Only intentfilter verification agents can verify applications");
10956
10957        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10958        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10959                Binder.getCallingUid(), verificationCode, failedDomains);
10960        msg.arg1 = id;
10961        msg.obj = response;
10962        mHandler.sendMessage(msg);
10963    }
10964
10965    @Override
10966    public int getIntentVerificationStatus(String packageName, int userId) {
10967        synchronized (mPackages) {
10968            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10969        }
10970    }
10971
10972    @Override
10973    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10974        mContext.enforceCallingOrSelfPermission(
10975                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10976
10977        boolean result = false;
10978        synchronized (mPackages) {
10979            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10980        }
10981        if (result) {
10982            scheduleWritePackageRestrictionsLocked(userId);
10983        }
10984        return result;
10985    }
10986
10987    @Override
10988    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10989        synchronized (mPackages) {
10990            return mSettings.getIntentFilterVerificationsLPr(packageName);
10991        }
10992    }
10993
10994    @Override
10995    public List<IntentFilter> getAllIntentFilters(String packageName) {
10996        if (TextUtils.isEmpty(packageName)) {
10997            return Collections.<IntentFilter>emptyList();
10998        }
10999        synchronized (mPackages) {
11000            PackageParser.Package pkg = mPackages.get(packageName);
11001            if (pkg == null || pkg.activities == null) {
11002                return Collections.<IntentFilter>emptyList();
11003            }
11004            final int count = pkg.activities.size();
11005            ArrayList<IntentFilter> result = new ArrayList<>();
11006            for (int n=0; n<count; n++) {
11007                PackageParser.Activity activity = pkg.activities.get(n);
11008                if (activity.intents != null && activity.intents.size() > 0) {
11009                    result.addAll(activity.intents);
11010                }
11011            }
11012            return result;
11013        }
11014    }
11015
11016    @Override
11017    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11018        mContext.enforceCallingOrSelfPermission(
11019                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11020
11021        synchronized (mPackages) {
11022            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11023            if (packageName != null) {
11024                result |= updateIntentVerificationStatus(packageName,
11025                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11026                        userId);
11027                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11028                        packageName, userId);
11029            }
11030            return result;
11031        }
11032    }
11033
11034    @Override
11035    public String getDefaultBrowserPackageName(int userId) {
11036        synchronized (mPackages) {
11037            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11038        }
11039    }
11040
11041    /**
11042     * Get the "allow unknown sources" setting.
11043     *
11044     * @return the current "allow unknown sources" setting
11045     */
11046    private int getUnknownSourcesSettings() {
11047        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11048                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11049                -1);
11050    }
11051
11052    @Override
11053    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11054        final int uid = Binder.getCallingUid();
11055        // writer
11056        synchronized (mPackages) {
11057            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11058            if (targetPackageSetting == null) {
11059                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11060            }
11061
11062            PackageSetting installerPackageSetting;
11063            if (installerPackageName != null) {
11064                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11065                if (installerPackageSetting == null) {
11066                    throw new IllegalArgumentException("Unknown installer package: "
11067                            + installerPackageName);
11068                }
11069            } else {
11070                installerPackageSetting = null;
11071            }
11072
11073            Signature[] callerSignature;
11074            Object obj = mSettings.getUserIdLPr(uid);
11075            if (obj != null) {
11076                if (obj instanceof SharedUserSetting) {
11077                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11078                } else if (obj instanceof PackageSetting) {
11079                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11080                } else {
11081                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11082                }
11083            } else {
11084                throw new SecurityException("Unknown calling UID: " + uid);
11085            }
11086
11087            // Verify: can't set installerPackageName to a package that is
11088            // not signed with the same cert as the caller.
11089            if (installerPackageSetting != null) {
11090                if (compareSignatures(callerSignature,
11091                        installerPackageSetting.signatures.mSignatures)
11092                        != PackageManager.SIGNATURE_MATCH) {
11093                    throw new SecurityException(
11094                            "Caller does not have same cert as new installer package "
11095                            + installerPackageName);
11096                }
11097            }
11098
11099            // Verify: if target already has an installer package, it must
11100            // be signed with the same cert as the caller.
11101            if (targetPackageSetting.installerPackageName != null) {
11102                PackageSetting setting = mSettings.mPackages.get(
11103                        targetPackageSetting.installerPackageName);
11104                // If the currently set package isn't valid, then it's always
11105                // okay to change it.
11106                if (setting != null) {
11107                    if (compareSignatures(callerSignature,
11108                            setting.signatures.mSignatures)
11109                            != PackageManager.SIGNATURE_MATCH) {
11110                        throw new SecurityException(
11111                                "Caller does not have same cert as old installer package "
11112                                + targetPackageSetting.installerPackageName);
11113                    }
11114                }
11115            }
11116
11117            // Okay!
11118            targetPackageSetting.installerPackageName = installerPackageName;
11119            scheduleWriteSettingsLocked();
11120        }
11121    }
11122
11123    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11124        // Queue up an async operation since the package installation may take a little while.
11125        mHandler.post(new Runnable() {
11126            public void run() {
11127                mHandler.removeCallbacks(this);
11128                 // Result object to be returned
11129                PackageInstalledInfo res = new PackageInstalledInfo();
11130                res.setReturnCode(currentStatus);
11131                res.uid = -1;
11132                res.pkg = null;
11133                res.removedInfo = null;
11134                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11135                    args.doPreInstall(res.returnCode);
11136                    synchronized (mInstallLock) {
11137                        installPackageTracedLI(args, res);
11138                    }
11139                    args.doPostInstall(res.returnCode, res.uid);
11140                }
11141
11142                // A restore should be performed at this point if (a) the install
11143                // succeeded, (b) the operation is not an update, and (c) the new
11144                // package has not opted out of backup participation.
11145                final boolean update = res.removedInfo != null
11146                        && res.removedInfo.removedPackage != null;
11147                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11148                boolean doRestore = !update
11149                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11150
11151                // Set up the post-install work request bookkeeping.  This will be used
11152                // and cleaned up by the post-install event handling regardless of whether
11153                // there's a restore pass performed.  Token values are >= 1.
11154                int token;
11155                if (mNextInstallToken < 0) mNextInstallToken = 1;
11156                token = mNextInstallToken++;
11157
11158                PostInstallData data = new PostInstallData(args, res);
11159                mRunningInstalls.put(token, data);
11160                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11161
11162                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11163                    // Pass responsibility to the Backup Manager.  It will perform a
11164                    // restore if appropriate, then pass responsibility back to the
11165                    // Package Manager to run the post-install observer callbacks
11166                    // and broadcasts.
11167                    IBackupManager bm = IBackupManager.Stub.asInterface(
11168                            ServiceManager.getService(Context.BACKUP_SERVICE));
11169                    if (bm != null) {
11170                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11171                                + " to BM for possible restore");
11172                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11173                        try {
11174                            // TODO: http://b/22388012
11175                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11176                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11177                            } else {
11178                                doRestore = false;
11179                            }
11180                        } catch (RemoteException e) {
11181                            // can't happen; the backup manager is local
11182                        } catch (Exception e) {
11183                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11184                            doRestore = false;
11185                        }
11186                    } else {
11187                        Slog.e(TAG, "Backup Manager not found!");
11188                        doRestore = false;
11189                    }
11190                }
11191
11192                if (!doRestore) {
11193                    // No restore possible, or the Backup Manager was mysteriously not
11194                    // available -- just fire the post-install work request directly.
11195                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11196
11197                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11198
11199                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11200                    mHandler.sendMessage(msg);
11201                }
11202            }
11203        });
11204    }
11205
11206    private abstract class HandlerParams {
11207        private static final int MAX_RETRIES = 4;
11208
11209        /**
11210         * Number of times startCopy() has been attempted and had a non-fatal
11211         * error.
11212         */
11213        private int mRetries = 0;
11214
11215        /** User handle for the user requesting the information or installation. */
11216        private final UserHandle mUser;
11217        String traceMethod;
11218        int traceCookie;
11219
11220        HandlerParams(UserHandle user) {
11221            mUser = user;
11222        }
11223
11224        UserHandle getUser() {
11225            return mUser;
11226        }
11227
11228        HandlerParams setTraceMethod(String traceMethod) {
11229            this.traceMethod = traceMethod;
11230            return this;
11231        }
11232
11233        HandlerParams setTraceCookie(int traceCookie) {
11234            this.traceCookie = traceCookie;
11235            return this;
11236        }
11237
11238        final boolean startCopy() {
11239            boolean res;
11240            try {
11241                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11242
11243                if (++mRetries > MAX_RETRIES) {
11244                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11245                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11246                    handleServiceError();
11247                    return false;
11248                } else {
11249                    handleStartCopy();
11250                    res = true;
11251                }
11252            } catch (RemoteException e) {
11253                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11254                mHandler.sendEmptyMessage(MCS_RECONNECT);
11255                res = false;
11256            }
11257            handleReturnCode();
11258            return res;
11259        }
11260
11261        final void serviceError() {
11262            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11263            handleServiceError();
11264            handleReturnCode();
11265        }
11266
11267        abstract void handleStartCopy() throws RemoteException;
11268        abstract void handleServiceError();
11269        abstract void handleReturnCode();
11270    }
11271
11272    class MeasureParams extends HandlerParams {
11273        private final PackageStats mStats;
11274        private boolean mSuccess;
11275
11276        private final IPackageStatsObserver mObserver;
11277
11278        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11279            super(new UserHandle(stats.userHandle));
11280            mObserver = observer;
11281            mStats = stats;
11282        }
11283
11284        @Override
11285        public String toString() {
11286            return "MeasureParams{"
11287                + Integer.toHexString(System.identityHashCode(this))
11288                + " " + mStats.packageName + "}";
11289        }
11290
11291        @Override
11292        void handleStartCopy() throws RemoteException {
11293            synchronized (mInstallLock) {
11294                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11295            }
11296
11297            if (mSuccess) {
11298                final boolean mounted;
11299                if (Environment.isExternalStorageEmulated()) {
11300                    mounted = true;
11301                } else {
11302                    final String status = Environment.getExternalStorageState();
11303                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11304                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11305                }
11306
11307                if (mounted) {
11308                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11309
11310                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11311                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11312
11313                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11314                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11315
11316                    // Always subtract cache size, since it's a subdirectory
11317                    mStats.externalDataSize -= mStats.externalCacheSize;
11318
11319                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11320                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11321
11322                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11323                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11324                }
11325            }
11326        }
11327
11328        @Override
11329        void handleReturnCode() {
11330            if (mObserver != null) {
11331                try {
11332                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11333                } catch (RemoteException e) {
11334                    Slog.i(TAG, "Observer no longer exists.");
11335                }
11336            }
11337        }
11338
11339        @Override
11340        void handleServiceError() {
11341            Slog.e(TAG, "Could not measure application " + mStats.packageName
11342                            + " external storage");
11343        }
11344    }
11345
11346    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11347            throws RemoteException {
11348        long result = 0;
11349        for (File path : paths) {
11350            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11351        }
11352        return result;
11353    }
11354
11355    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11356        for (File path : paths) {
11357            try {
11358                mcs.clearDirectory(path.getAbsolutePath());
11359            } catch (RemoteException e) {
11360            }
11361        }
11362    }
11363
11364    static class OriginInfo {
11365        /**
11366         * Location where install is coming from, before it has been
11367         * copied/renamed into place. This could be a single monolithic APK
11368         * file, or a cluster directory. This location may be untrusted.
11369         */
11370        final File file;
11371        final String cid;
11372
11373        /**
11374         * Flag indicating that {@link #file} or {@link #cid} has already been
11375         * staged, meaning downstream users don't need to defensively copy the
11376         * contents.
11377         */
11378        final boolean staged;
11379
11380        /**
11381         * Flag indicating that {@link #file} or {@link #cid} is an already
11382         * installed app that is being moved.
11383         */
11384        final boolean existing;
11385
11386        final String resolvedPath;
11387        final File resolvedFile;
11388
11389        static OriginInfo fromNothing() {
11390            return new OriginInfo(null, null, false, false);
11391        }
11392
11393        static OriginInfo fromUntrustedFile(File file) {
11394            return new OriginInfo(file, null, false, false);
11395        }
11396
11397        static OriginInfo fromExistingFile(File file) {
11398            return new OriginInfo(file, null, false, true);
11399        }
11400
11401        static OriginInfo fromStagedFile(File file) {
11402            return new OriginInfo(file, null, true, false);
11403        }
11404
11405        static OriginInfo fromStagedContainer(String cid) {
11406            return new OriginInfo(null, cid, true, false);
11407        }
11408
11409        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11410            this.file = file;
11411            this.cid = cid;
11412            this.staged = staged;
11413            this.existing = existing;
11414
11415            if (cid != null) {
11416                resolvedPath = PackageHelper.getSdDir(cid);
11417                resolvedFile = new File(resolvedPath);
11418            } else if (file != null) {
11419                resolvedPath = file.getAbsolutePath();
11420                resolvedFile = file;
11421            } else {
11422                resolvedPath = null;
11423                resolvedFile = null;
11424            }
11425        }
11426    }
11427
11428    static class MoveInfo {
11429        final int moveId;
11430        final String fromUuid;
11431        final String toUuid;
11432        final String packageName;
11433        final String dataAppName;
11434        final int appId;
11435        final String seinfo;
11436        final int targetSdkVersion;
11437
11438        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11439                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11440            this.moveId = moveId;
11441            this.fromUuid = fromUuid;
11442            this.toUuid = toUuid;
11443            this.packageName = packageName;
11444            this.dataAppName = dataAppName;
11445            this.appId = appId;
11446            this.seinfo = seinfo;
11447            this.targetSdkVersion = targetSdkVersion;
11448        }
11449    }
11450
11451    class InstallParams extends HandlerParams {
11452        final OriginInfo origin;
11453        final MoveInfo move;
11454        final IPackageInstallObserver2 observer;
11455        int installFlags;
11456        final String installerPackageName;
11457        final String volumeUuid;
11458        final VerificationParams verificationParams;
11459        private InstallArgs mArgs;
11460        private int mRet;
11461        final String packageAbiOverride;
11462        final String[] grantedRuntimePermissions;
11463
11464        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11465                int installFlags, String installerPackageName, String volumeUuid,
11466                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11467                String[] grantedPermissions) {
11468            super(user);
11469            this.origin = origin;
11470            this.move = move;
11471            this.observer = observer;
11472            this.installFlags = installFlags;
11473            this.installerPackageName = installerPackageName;
11474            this.volumeUuid = volumeUuid;
11475            this.verificationParams = verificationParams;
11476            this.packageAbiOverride = packageAbiOverride;
11477            this.grantedRuntimePermissions = grantedPermissions;
11478        }
11479
11480        @Override
11481        public String toString() {
11482            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11483                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11484        }
11485
11486        private int installLocationPolicy(PackageInfoLite pkgLite) {
11487            String packageName = pkgLite.packageName;
11488            int installLocation = pkgLite.installLocation;
11489            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11490            // reader
11491            synchronized (mPackages) {
11492                PackageParser.Package pkg = mPackages.get(packageName);
11493                if (pkg != null) {
11494                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11495                        // Check for downgrading.
11496                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11497                            try {
11498                                checkDowngrade(pkg, pkgLite);
11499                            } catch (PackageManagerException e) {
11500                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11501                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11502                            }
11503                        }
11504                        // Check for updated system application.
11505                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11506                            if (onSd) {
11507                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11508                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11509                            }
11510                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11511                        } else {
11512                            if (onSd) {
11513                                // Install flag overrides everything.
11514                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11515                            }
11516                            // If current upgrade specifies particular preference
11517                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11518                                // Application explicitly specified internal.
11519                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11520                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11521                                // App explictly prefers external. Let policy decide
11522                            } else {
11523                                // Prefer previous location
11524                                if (isExternal(pkg)) {
11525                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11526                                }
11527                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11528                            }
11529                        }
11530                    } else {
11531                        // Invalid install. Return error code
11532                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11533                    }
11534                }
11535            }
11536            // All the special cases have been taken care of.
11537            // Return result based on recommended install location.
11538            if (onSd) {
11539                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11540            }
11541            return pkgLite.recommendedInstallLocation;
11542        }
11543
11544        /*
11545         * Invoke remote method to get package information and install
11546         * location values. Override install location based on default
11547         * policy if needed and then create install arguments based
11548         * on the install location.
11549         */
11550        public void handleStartCopy() throws RemoteException {
11551            int ret = PackageManager.INSTALL_SUCCEEDED;
11552
11553            // If we're already staged, we've firmly committed to an install location
11554            if (origin.staged) {
11555                if (origin.file != null) {
11556                    installFlags |= PackageManager.INSTALL_INTERNAL;
11557                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11558                } else if (origin.cid != null) {
11559                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11560                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11561                } else {
11562                    throw new IllegalStateException("Invalid stage location");
11563                }
11564            }
11565
11566            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11567            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11568            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11569            PackageInfoLite pkgLite = null;
11570
11571            if (onInt && onSd) {
11572                // Check if both bits are set.
11573                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11574                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11575            } else if (onSd && ephemeral) {
11576                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11577                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11578            } else {
11579                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11580                        packageAbiOverride);
11581
11582                if (DEBUG_EPHEMERAL && ephemeral) {
11583                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11584                }
11585
11586                /*
11587                 * If we have too little free space, try to free cache
11588                 * before giving up.
11589                 */
11590                if (!origin.staged && pkgLite.recommendedInstallLocation
11591                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11592                    // TODO: focus freeing disk space on the target device
11593                    final StorageManager storage = StorageManager.from(mContext);
11594                    final long lowThreshold = storage.getStorageLowBytes(
11595                            Environment.getDataDirectory());
11596
11597                    final long sizeBytes = mContainerService.calculateInstalledSize(
11598                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11599
11600                    try {
11601                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11602                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11603                                installFlags, packageAbiOverride);
11604                    } catch (InstallerException e) {
11605                        Slog.w(TAG, "Failed to free cache", e);
11606                    }
11607
11608                    /*
11609                     * The cache free must have deleted the file we
11610                     * downloaded to install.
11611                     *
11612                     * TODO: fix the "freeCache" call to not delete
11613                     *       the file we care about.
11614                     */
11615                    if (pkgLite.recommendedInstallLocation
11616                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11617                        pkgLite.recommendedInstallLocation
11618                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11619                    }
11620                }
11621            }
11622
11623            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11624                int loc = pkgLite.recommendedInstallLocation;
11625                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11626                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11627                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11628                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11629                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11630                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11631                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11632                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11633                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11634                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11635                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11636                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11637                } else {
11638                    // Override with defaults if needed.
11639                    loc = installLocationPolicy(pkgLite);
11640                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11641                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11642                    } else if (!onSd && !onInt) {
11643                        // Override install location with flags
11644                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11645                            // Set the flag to install on external media.
11646                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11647                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11648                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11649                            if (DEBUG_EPHEMERAL) {
11650                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11651                            }
11652                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11653                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11654                                    |PackageManager.INSTALL_INTERNAL);
11655                        } else {
11656                            // Make sure the flag for installing on external
11657                            // media is unset
11658                            installFlags |= PackageManager.INSTALL_INTERNAL;
11659                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11660                        }
11661                    }
11662                }
11663            }
11664
11665            final InstallArgs args = createInstallArgs(this);
11666            mArgs = args;
11667
11668            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11669                // TODO: http://b/22976637
11670                // Apps installed for "all" users use the device owner to verify the app
11671                UserHandle verifierUser = getUser();
11672                if (verifierUser == UserHandle.ALL) {
11673                    verifierUser = UserHandle.SYSTEM;
11674                }
11675
11676                /*
11677                 * Determine if we have any installed package verifiers. If we
11678                 * do, then we'll defer to them to verify the packages.
11679                 */
11680                final int requiredUid = mRequiredVerifierPackage == null ? -1
11681                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11682                                verifierUser.getIdentifier());
11683                if (!origin.existing && requiredUid != -1
11684                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11685                    final Intent verification = new Intent(
11686                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11687                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11688                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11689                            PACKAGE_MIME_TYPE);
11690                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11691
11692                    // Query all live verifiers based on current user state
11693                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11694                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11695
11696                    if (DEBUG_VERIFY) {
11697                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11698                                + verification.toString() + " with " + pkgLite.verifiers.length
11699                                + " optional verifiers");
11700                    }
11701
11702                    final int verificationId = mPendingVerificationToken++;
11703
11704                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11705
11706                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11707                            installerPackageName);
11708
11709                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11710                            installFlags);
11711
11712                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11713                            pkgLite.packageName);
11714
11715                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11716                            pkgLite.versionCode);
11717
11718                    if (verificationParams != null) {
11719                        if (verificationParams.getVerificationURI() != null) {
11720                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11721                                 verificationParams.getVerificationURI());
11722                        }
11723                        if (verificationParams.getOriginatingURI() != null) {
11724                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11725                                  verificationParams.getOriginatingURI());
11726                        }
11727                        if (verificationParams.getReferrer() != null) {
11728                            verification.putExtra(Intent.EXTRA_REFERRER,
11729                                  verificationParams.getReferrer());
11730                        }
11731                        if (verificationParams.getOriginatingUid() >= 0) {
11732                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11733                                  verificationParams.getOriginatingUid());
11734                        }
11735                        if (verificationParams.getInstallerUid() >= 0) {
11736                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11737                                  verificationParams.getInstallerUid());
11738                        }
11739                    }
11740
11741                    final PackageVerificationState verificationState = new PackageVerificationState(
11742                            requiredUid, args);
11743
11744                    mPendingVerification.append(verificationId, verificationState);
11745
11746                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11747                            receivers, verificationState);
11748
11749                    /*
11750                     * If any sufficient verifiers were listed in the package
11751                     * manifest, attempt to ask them.
11752                     */
11753                    if (sufficientVerifiers != null) {
11754                        final int N = sufficientVerifiers.size();
11755                        if (N == 0) {
11756                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11757                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11758                        } else {
11759                            for (int i = 0; i < N; i++) {
11760                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11761
11762                                final Intent sufficientIntent = new Intent(verification);
11763                                sufficientIntent.setComponent(verifierComponent);
11764                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11765                            }
11766                        }
11767                    }
11768
11769                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11770                            mRequiredVerifierPackage, receivers);
11771                    if (ret == PackageManager.INSTALL_SUCCEEDED
11772                            && mRequiredVerifierPackage != null) {
11773                        Trace.asyncTraceBegin(
11774                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11775                        /*
11776                         * Send the intent to the required verification agent,
11777                         * but only start the verification timeout after the
11778                         * target BroadcastReceivers have run.
11779                         */
11780                        verification.setComponent(requiredVerifierComponent);
11781                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11782                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11783                                new BroadcastReceiver() {
11784                                    @Override
11785                                    public void onReceive(Context context, Intent intent) {
11786                                        final Message msg = mHandler
11787                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11788                                        msg.arg1 = verificationId;
11789                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11790                                    }
11791                                }, null, 0, null, null);
11792
11793                        /*
11794                         * We don't want the copy to proceed until verification
11795                         * succeeds, so null out this field.
11796                         */
11797                        mArgs = null;
11798                    }
11799                } else {
11800                    /*
11801                     * No package verification is enabled, so immediately start
11802                     * the remote call to initiate copy using temporary file.
11803                     */
11804                    ret = args.copyApk(mContainerService, true);
11805                }
11806            }
11807
11808            mRet = ret;
11809        }
11810
11811        @Override
11812        void handleReturnCode() {
11813            // If mArgs is null, then MCS couldn't be reached. When it
11814            // reconnects, it will try again to install. At that point, this
11815            // will succeed.
11816            if (mArgs != null) {
11817                processPendingInstall(mArgs, mRet);
11818            }
11819        }
11820
11821        @Override
11822        void handleServiceError() {
11823            mArgs = createInstallArgs(this);
11824            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11825        }
11826
11827        public boolean isForwardLocked() {
11828            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11829        }
11830    }
11831
11832    /**
11833     * Used during creation of InstallArgs
11834     *
11835     * @param installFlags package installation flags
11836     * @return true if should be installed on external storage
11837     */
11838    private static boolean installOnExternalAsec(int installFlags) {
11839        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11840            return false;
11841        }
11842        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11843            return true;
11844        }
11845        return false;
11846    }
11847
11848    /**
11849     * Used during creation of InstallArgs
11850     *
11851     * @param installFlags package installation flags
11852     * @return true if should be installed as forward locked
11853     */
11854    private static boolean installForwardLocked(int installFlags) {
11855        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11856    }
11857
11858    private InstallArgs createInstallArgs(InstallParams params) {
11859        if (params.move != null) {
11860            return new MoveInstallArgs(params);
11861        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11862            return new AsecInstallArgs(params);
11863        } else {
11864            return new FileInstallArgs(params);
11865        }
11866    }
11867
11868    /**
11869     * Create args that describe an existing installed package. Typically used
11870     * when cleaning up old installs, or used as a move source.
11871     */
11872    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11873            String resourcePath, String[] instructionSets) {
11874        final boolean isInAsec;
11875        if (installOnExternalAsec(installFlags)) {
11876            /* Apps on SD card are always in ASEC containers. */
11877            isInAsec = true;
11878        } else if (installForwardLocked(installFlags)
11879                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11880            /*
11881             * Forward-locked apps are only in ASEC containers if they're the
11882             * new style
11883             */
11884            isInAsec = true;
11885        } else {
11886            isInAsec = false;
11887        }
11888
11889        if (isInAsec) {
11890            return new AsecInstallArgs(codePath, instructionSets,
11891                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11892        } else {
11893            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11894        }
11895    }
11896
11897    static abstract class InstallArgs {
11898        /** @see InstallParams#origin */
11899        final OriginInfo origin;
11900        /** @see InstallParams#move */
11901        final MoveInfo move;
11902
11903        final IPackageInstallObserver2 observer;
11904        // Always refers to PackageManager flags only
11905        final int installFlags;
11906        final String installerPackageName;
11907        final String volumeUuid;
11908        final UserHandle user;
11909        final String abiOverride;
11910        final String[] installGrantPermissions;
11911        /** If non-null, drop an async trace when the install completes */
11912        final String traceMethod;
11913        final int traceCookie;
11914
11915        // The list of instruction sets supported by this app. This is currently
11916        // only used during the rmdex() phase to clean up resources. We can get rid of this
11917        // if we move dex files under the common app path.
11918        /* nullable */ String[] instructionSets;
11919
11920        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11921                int installFlags, String installerPackageName, String volumeUuid,
11922                UserHandle user, String[] instructionSets,
11923                String abiOverride, String[] installGrantPermissions,
11924                String traceMethod, int traceCookie) {
11925            this.origin = origin;
11926            this.move = move;
11927            this.installFlags = installFlags;
11928            this.observer = observer;
11929            this.installerPackageName = installerPackageName;
11930            this.volumeUuid = volumeUuid;
11931            this.user = user;
11932            this.instructionSets = instructionSets;
11933            this.abiOverride = abiOverride;
11934            this.installGrantPermissions = installGrantPermissions;
11935            this.traceMethod = traceMethod;
11936            this.traceCookie = traceCookie;
11937        }
11938
11939        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11940        abstract int doPreInstall(int status);
11941
11942        /**
11943         * Rename package into final resting place. All paths on the given
11944         * scanned package should be updated to reflect the rename.
11945         */
11946        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11947        abstract int doPostInstall(int status, int uid);
11948
11949        /** @see PackageSettingBase#codePathString */
11950        abstract String getCodePath();
11951        /** @see PackageSettingBase#resourcePathString */
11952        abstract String getResourcePath();
11953
11954        // Need installer lock especially for dex file removal.
11955        abstract void cleanUpResourcesLI();
11956        abstract boolean doPostDeleteLI(boolean delete);
11957
11958        /**
11959         * Called before the source arguments are copied. This is used mostly
11960         * for MoveParams when it needs to read the source file to put it in the
11961         * destination.
11962         */
11963        int doPreCopy() {
11964            return PackageManager.INSTALL_SUCCEEDED;
11965        }
11966
11967        /**
11968         * Called after the source arguments are copied. This is used mostly for
11969         * MoveParams when it needs to read the source file to put it in the
11970         * destination.
11971         *
11972         * @return
11973         */
11974        int doPostCopy(int uid) {
11975            return PackageManager.INSTALL_SUCCEEDED;
11976        }
11977
11978        protected boolean isFwdLocked() {
11979            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11980        }
11981
11982        protected boolean isExternalAsec() {
11983            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11984        }
11985
11986        protected boolean isEphemeral() {
11987            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11988        }
11989
11990        UserHandle getUser() {
11991            return user;
11992        }
11993    }
11994
11995    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11996        if (!allCodePaths.isEmpty()) {
11997            if (instructionSets == null) {
11998                throw new IllegalStateException("instructionSet == null");
11999            }
12000            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12001            for (String codePath : allCodePaths) {
12002                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12003                    try {
12004                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12005                    } catch (InstallerException ignored) {
12006                    }
12007                }
12008            }
12009        }
12010    }
12011
12012    /**
12013     * Logic to handle installation of non-ASEC applications, including copying
12014     * and renaming logic.
12015     */
12016    class FileInstallArgs extends InstallArgs {
12017        private File codeFile;
12018        private File resourceFile;
12019
12020        // Example topology:
12021        // /data/app/com.example/base.apk
12022        // /data/app/com.example/split_foo.apk
12023        // /data/app/com.example/lib/arm/libfoo.so
12024        // /data/app/com.example/lib/arm64/libfoo.so
12025        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12026
12027        /** New install */
12028        FileInstallArgs(InstallParams params) {
12029            super(params.origin, params.move, params.observer, params.installFlags,
12030                    params.installerPackageName, params.volumeUuid,
12031                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12032                    params.grantedRuntimePermissions,
12033                    params.traceMethod, params.traceCookie);
12034            if (isFwdLocked()) {
12035                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12036            }
12037        }
12038
12039        /** Existing install */
12040        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12041            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12042                    null, null, null, 0);
12043            this.codeFile = (codePath != null) ? new File(codePath) : null;
12044            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12045        }
12046
12047        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12048            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12049            try {
12050                return doCopyApk(imcs, temp);
12051            } finally {
12052                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12053            }
12054        }
12055
12056        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12057            if (origin.staged) {
12058                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12059                codeFile = origin.file;
12060                resourceFile = origin.file;
12061                return PackageManager.INSTALL_SUCCEEDED;
12062            }
12063
12064            try {
12065                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12066                final File tempDir =
12067                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12068                codeFile = tempDir;
12069                resourceFile = tempDir;
12070            } catch (IOException e) {
12071                Slog.w(TAG, "Failed to create copy file: " + e);
12072                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12073            }
12074
12075            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12076                @Override
12077                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12078                    if (!FileUtils.isValidExtFilename(name)) {
12079                        throw new IllegalArgumentException("Invalid filename: " + name);
12080                    }
12081                    try {
12082                        final File file = new File(codeFile, name);
12083                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12084                                O_RDWR | O_CREAT, 0644);
12085                        Os.chmod(file.getAbsolutePath(), 0644);
12086                        return new ParcelFileDescriptor(fd);
12087                    } catch (ErrnoException e) {
12088                        throw new RemoteException("Failed to open: " + e.getMessage());
12089                    }
12090                }
12091            };
12092
12093            int ret = PackageManager.INSTALL_SUCCEEDED;
12094            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12095            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12096                Slog.e(TAG, "Failed to copy package");
12097                return ret;
12098            }
12099
12100            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12101            NativeLibraryHelper.Handle handle = null;
12102            try {
12103                handle = NativeLibraryHelper.Handle.create(codeFile);
12104                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12105                        abiOverride);
12106            } catch (IOException e) {
12107                Slog.e(TAG, "Copying native libraries failed", e);
12108                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12109            } finally {
12110                IoUtils.closeQuietly(handle);
12111            }
12112
12113            return ret;
12114        }
12115
12116        int doPreInstall(int status) {
12117            if (status != PackageManager.INSTALL_SUCCEEDED) {
12118                cleanUp();
12119            }
12120            return status;
12121        }
12122
12123        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12124            if (status != PackageManager.INSTALL_SUCCEEDED) {
12125                cleanUp();
12126                return false;
12127            }
12128
12129            final File targetDir = codeFile.getParentFile();
12130            final File beforeCodeFile = codeFile;
12131            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12132
12133            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12134            try {
12135                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12136            } catch (ErrnoException e) {
12137                Slog.w(TAG, "Failed to rename", e);
12138                return false;
12139            }
12140
12141            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12142                Slog.w(TAG, "Failed to restorecon");
12143                return false;
12144            }
12145
12146            // Reflect the rename internally
12147            codeFile = afterCodeFile;
12148            resourceFile = afterCodeFile;
12149
12150            // Reflect the rename in scanned details
12151            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12152            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12153                    afterCodeFile, pkg.baseCodePath));
12154            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12155                    afterCodeFile, pkg.splitCodePaths));
12156
12157            // Reflect the rename in app info
12158            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12159            pkg.setApplicationInfoCodePath(pkg.codePath);
12160            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12161            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12162            pkg.setApplicationInfoResourcePath(pkg.codePath);
12163            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12164            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12165
12166            return true;
12167        }
12168
12169        int doPostInstall(int status, int uid) {
12170            if (status != PackageManager.INSTALL_SUCCEEDED) {
12171                cleanUp();
12172            }
12173            return status;
12174        }
12175
12176        @Override
12177        String getCodePath() {
12178            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12179        }
12180
12181        @Override
12182        String getResourcePath() {
12183            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12184        }
12185
12186        private boolean cleanUp() {
12187            if (codeFile == null || !codeFile.exists()) {
12188                return false;
12189            }
12190
12191            removeCodePathLI(codeFile);
12192
12193            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12194                resourceFile.delete();
12195            }
12196
12197            return true;
12198        }
12199
12200        void cleanUpResourcesLI() {
12201            // Try enumerating all code paths before deleting
12202            List<String> allCodePaths = Collections.EMPTY_LIST;
12203            if (codeFile != null && codeFile.exists()) {
12204                try {
12205                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12206                    allCodePaths = pkg.getAllCodePaths();
12207                } catch (PackageParserException e) {
12208                    // Ignored; we tried our best
12209                }
12210            }
12211
12212            cleanUp();
12213            removeDexFiles(allCodePaths, instructionSets);
12214        }
12215
12216        boolean doPostDeleteLI(boolean delete) {
12217            // XXX err, shouldn't we respect the delete flag?
12218            cleanUpResourcesLI();
12219            return true;
12220        }
12221    }
12222
12223    private boolean isAsecExternal(String cid) {
12224        final String asecPath = PackageHelper.getSdFilesystem(cid);
12225        return !asecPath.startsWith(mAsecInternalPath);
12226    }
12227
12228    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12229            PackageManagerException {
12230        if (copyRet < 0) {
12231            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12232                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12233                throw new PackageManagerException(copyRet, message);
12234            }
12235        }
12236    }
12237
12238    /**
12239     * Extract the MountService "container ID" from the full code path of an
12240     * .apk.
12241     */
12242    static String cidFromCodePath(String fullCodePath) {
12243        int eidx = fullCodePath.lastIndexOf("/");
12244        String subStr1 = fullCodePath.substring(0, eidx);
12245        int sidx = subStr1.lastIndexOf("/");
12246        return subStr1.substring(sidx+1, eidx);
12247    }
12248
12249    /**
12250     * Logic to handle installation of ASEC applications, including copying and
12251     * renaming logic.
12252     */
12253    class AsecInstallArgs extends InstallArgs {
12254        static final String RES_FILE_NAME = "pkg.apk";
12255        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12256
12257        String cid;
12258        String packagePath;
12259        String resourcePath;
12260
12261        /** New install */
12262        AsecInstallArgs(InstallParams params) {
12263            super(params.origin, params.move, params.observer, params.installFlags,
12264                    params.installerPackageName, params.volumeUuid,
12265                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12266                    params.grantedRuntimePermissions,
12267                    params.traceMethod, params.traceCookie);
12268        }
12269
12270        /** Existing install */
12271        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12272                        boolean isExternal, boolean isForwardLocked) {
12273            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12274                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12275                    instructionSets, null, null, null, 0);
12276            // Hackily pretend we're still looking at a full code path
12277            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12278                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12279            }
12280
12281            // Extract cid from fullCodePath
12282            int eidx = fullCodePath.lastIndexOf("/");
12283            String subStr1 = fullCodePath.substring(0, eidx);
12284            int sidx = subStr1.lastIndexOf("/");
12285            cid = subStr1.substring(sidx+1, eidx);
12286            setMountPath(subStr1);
12287        }
12288
12289        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12290            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12291                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12292                    instructionSets, null, null, null, 0);
12293            this.cid = cid;
12294            setMountPath(PackageHelper.getSdDir(cid));
12295        }
12296
12297        void createCopyFile() {
12298            cid = mInstallerService.allocateExternalStageCidLegacy();
12299        }
12300
12301        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12302            if (origin.staged && origin.cid != null) {
12303                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12304                cid = origin.cid;
12305                setMountPath(PackageHelper.getSdDir(cid));
12306                return PackageManager.INSTALL_SUCCEEDED;
12307            }
12308
12309            if (temp) {
12310                createCopyFile();
12311            } else {
12312                /*
12313                 * Pre-emptively destroy the container since it's destroyed if
12314                 * copying fails due to it existing anyway.
12315                 */
12316                PackageHelper.destroySdDir(cid);
12317            }
12318
12319            final String newMountPath = imcs.copyPackageToContainer(
12320                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12321                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12322
12323            if (newMountPath != null) {
12324                setMountPath(newMountPath);
12325                return PackageManager.INSTALL_SUCCEEDED;
12326            } else {
12327                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12328            }
12329        }
12330
12331        @Override
12332        String getCodePath() {
12333            return packagePath;
12334        }
12335
12336        @Override
12337        String getResourcePath() {
12338            return resourcePath;
12339        }
12340
12341        int doPreInstall(int status) {
12342            if (status != PackageManager.INSTALL_SUCCEEDED) {
12343                // Destroy container
12344                PackageHelper.destroySdDir(cid);
12345            } else {
12346                boolean mounted = PackageHelper.isContainerMounted(cid);
12347                if (!mounted) {
12348                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12349                            Process.SYSTEM_UID);
12350                    if (newMountPath != null) {
12351                        setMountPath(newMountPath);
12352                    } else {
12353                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12354                    }
12355                }
12356            }
12357            return status;
12358        }
12359
12360        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12361            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12362            String newMountPath = null;
12363            if (PackageHelper.isContainerMounted(cid)) {
12364                // Unmount the container
12365                if (!PackageHelper.unMountSdDir(cid)) {
12366                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12367                    return false;
12368                }
12369            }
12370            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12371                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12372                        " which might be stale. Will try to clean up.");
12373                // Clean up the stale container and proceed to recreate.
12374                if (!PackageHelper.destroySdDir(newCacheId)) {
12375                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12376                    return false;
12377                }
12378                // Successfully cleaned up stale container. Try to rename again.
12379                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12380                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12381                            + " inspite of cleaning it up.");
12382                    return false;
12383                }
12384            }
12385            if (!PackageHelper.isContainerMounted(newCacheId)) {
12386                Slog.w(TAG, "Mounting container " + newCacheId);
12387                newMountPath = PackageHelper.mountSdDir(newCacheId,
12388                        getEncryptKey(), Process.SYSTEM_UID);
12389            } else {
12390                newMountPath = PackageHelper.getSdDir(newCacheId);
12391            }
12392            if (newMountPath == null) {
12393                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12394                return false;
12395            }
12396            Log.i(TAG, "Succesfully renamed " + cid +
12397                    " to " + newCacheId +
12398                    " at new path: " + newMountPath);
12399            cid = newCacheId;
12400
12401            final File beforeCodeFile = new File(packagePath);
12402            setMountPath(newMountPath);
12403            final File afterCodeFile = new File(packagePath);
12404
12405            // Reflect the rename in scanned details
12406            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12407            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12408                    afterCodeFile, pkg.baseCodePath));
12409            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12410                    afterCodeFile, pkg.splitCodePaths));
12411
12412            // Reflect the rename in app info
12413            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12414            pkg.setApplicationInfoCodePath(pkg.codePath);
12415            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12416            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12417            pkg.setApplicationInfoResourcePath(pkg.codePath);
12418            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12419            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12420
12421            return true;
12422        }
12423
12424        private void setMountPath(String mountPath) {
12425            final File mountFile = new File(mountPath);
12426
12427            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12428            if (monolithicFile.exists()) {
12429                packagePath = monolithicFile.getAbsolutePath();
12430                if (isFwdLocked()) {
12431                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12432                } else {
12433                    resourcePath = packagePath;
12434                }
12435            } else {
12436                packagePath = mountFile.getAbsolutePath();
12437                resourcePath = packagePath;
12438            }
12439        }
12440
12441        int doPostInstall(int status, int uid) {
12442            if (status != PackageManager.INSTALL_SUCCEEDED) {
12443                cleanUp();
12444            } else {
12445                final int groupOwner;
12446                final String protectedFile;
12447                if (isFwdLocked()) {
12448                    groupOwner = UserHandle.getSharedAppGid(uid);
12449                    protectedFile = RES_FILE_NAME;
12450                } else {
12451                    groupOwner = -1;
12452                    protectedFile = null;
12453                }
12454
12455                if (uid < Process.FIRST_APPLICATION_UID
12456                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12457                    Slog.e(TAG, "Failed to finalize " + cid);
12458                    PackageHelper.destroySdDir(cid);
12459                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12460                }
12461
12462                boolean mounted = PackageHelper.isContainerMounted(cid);
12463                if (!mounted) {
12464                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12465                }
12466            }
12467            return status;
12468        }
12469
12470        private void cleanUp() {
12471            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12472
12473            // Destroy secure container
12474            PackageHelper.destroySdDir(cid);
12475        }
12476
12477        private List<String> getAllCodePaths() {
12478            final File codeFile = new File(getCodePath());
12479            if (codeFile != null && codeFile.exists()) {
12480                try {
12481                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12482                    return pkg.getAllCodePaths();
12483                } catch (PackageParserException e) {
12484                    // Ignored; we tried our best
12485                }
12486            }
12487            return Collections.EMPTY_LIST;
12488        }
12489
12490        void cleanUpResourcesLI() {
12491            // Enumerate all code paths before deleting
12492            cleanUpResourcesLI(getAllCodePaths());
12493        }
12494
12495        private void cleanUpResourcesLI(List<String> allCodePaths) {
12496            cleanUp();
12497            removeDexFiles(allCodePaths, instructionSets);
12498        }
12499
12500        String getPackageName() {
12501            return getAsecPackageName(cid);
12502        }
12503
12504        boolean doPostDeleteLI(boolean delete) {
12505            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12506            final List<String> allCodePaths = getAllCodePaths();
12507            boolean mounted = PackageHelper.isContainerMounted(cid);
12508            if (mounted) {
12509                // Unmount first
12510                if (PackageHelper.unMountSdDir(cid)) {
12511                    mounted = false;
12512                }
12513            }
12514            if (!mounted && delete) {
12515                cleanUpResourcesLI(allCodePaths);
12516            }
12517            return !mounted;
12518        }
12519
12520        @Override
12521        int doPreCopy() {
12522            if (isFwdLocked()) {
12523                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12524                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12525                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12526                }
12527            }
12528
12529            return PackageManager.INSTALL_SUCCEEDED;
12530        }
12531
12532        @Override
12533        int doPostCopy(int uid) {
12534            if (isFwdLocked()) {
12535                if (uid < Process.FIRST_APPLICATION_UID
12536                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12537                                RES_FILE_NAME)) {
12538                    Slog.e(TAG, "Failed to finalize " + cid);
12539                    PackageHelper.destroySdDir(cid);
12540                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12541                }
12542            }
12543
12544            return PackageManager.INSTALL_SUCCEEDED;
12545        }
12546    }
12547
12548    /**
12549     * Logic to handle movement of existing installed applications.
12550     */
12551    class MoveInstallArgs extends InstallArgs {
12552        private File codeFile;
12553        private File resourceFile;
12554
12555        /** New install */
12556        MoveInstallArgs(InstallParams params) {
12557            super(params.origin, params.move, params.observer, params.installFlags,
12558                    params.installerPackageName, params.volumeUuid,
12559                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12560                    params.grantedRuntimePermissions,
12561                    params.traceMethod, params.traceCookie);
12562        }
12563
12564        int copyApk(IMediaContainerService imcs, boolean temp) {
12565            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12566                    + move.fromUuid + " to " + move.toUuid);
12567            synchronized (mInstaller) {
12568                try {
12569                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12570                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12571                } catch (InstallerException e) {
12572                    Slog.w(TAG, "Failed to move app", e);
12573                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12574                }
12575            }
12576
12577            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12578            resourceFile = codeFile;
12579            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12580
12581            return PackageManager.INSTALL_SUCCEEDED;
12582        }
12583
12584        int doPreInstall(int status) {
12585            if (status != PackageManager.INSTALL_SUCCEEDED) {
12586                cleanUp(move.toUuid);
12587            }
12588            return status;
12589        }
12590
12591        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12592            if (status != PackageManager.INSTALL_SUCCEEDED) {
12593                cleanUp(move.toUuid);
12594                return false;
12595            }
12596
12597            // Reflect the move in app info
12598            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12599            pkg.setApplicationInfoCodePath(pkg.codePath);
12600            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12601            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12602            pkg.setApplicationInfoResourcePath(pkg.codePath);
12603            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12604            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12605
12606            return true;
12607        }
12608
12609        int doPostInstall(int status, int uid) {
12610            if (status == PackageManager.INSTALL_SUCCEEDED) {
12611                cleanUp(move.fromUuid);
12612            } else {
12613                cleanUp(move.toUuid);
12614            }
12615            return status;
12616        }
12617
12618        @Override
12619        String getCodePath() {
12620            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12621        }
12622
12623        @Override
12624        String getResourcePath() {
12625            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12626        }
12627
12628        private boolean cleanUp(String volumeUuid) {
12629            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12630                    move.dataAppName);
12631            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12632            synchronized (mInstallLock) {
12633                // Clean up both app data and code
12634                removeDataDirsLI(volumeUuid, move.packageName);
12635                removeCodePathLI(codeFile);
12636            }
12637            return true;
12638        }
12639
12640        void cleanUpResourcesLI() {
12641            throw new UnsupportedOperationException();
12642        }
12643
12644        boolean doPostDeleteLI(boolean delete) {
12645            throw new UnsupportedOperationException();
12646        }
12647    }
12648
12649    static String getAsecPackageName(String packageCid) {
12650        int idx = packageCid.lastIndexOf("-");
12651        if (idx == -1) {
12652            return packageCid;
12653        }
12654        return packageCid.substring(0, idx);
12655    }
12656
12657    // Utility method used to create code paths based on package name and available index.
12658    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12659        String idxStr = "";
12660        int idx = 1;
12661        // Fall back to default value of idx=1 if prefix is not
12662        // part of oldCodePath
12663        if (oldCodePath != null) {
12664            String subStr = oldCodePath;
12665            // Drop the suffix right away
12666            if (suffix != null && subStr.endsWith(suffix)) {
12667                subStr = subStr.substring(0, subStr.length() - suffix.length());
12668            }
12669            // If oldCodePath already contains prefix find out the
12670            // ending index to either increment or decrement.
12671            int sidx = subStr.lastIndexOf(prefix);
12672            if (sidx != -1) {
12673                subStr = subStr.substring(sidx + prefix.length());
12674                if (subStr != null) {
12675                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12676                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12677                    }
12678                    try {
12679                        idx = Integer.parseInt(subStr);
12680                        if (idx <= 1) {
12681                            idx++;
12682                        } else {
12683                            idx--;
12684                        }
12685                    } catch(NumberFormatException e) {
12686                    }
12687                }
12688            }
12689        }
12690        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12691        return prefix + idxStr;
12692    }
12693
12694    private File getNextCodePath(File targetDir, String packageName) {
12695        int suffix = 1;
12696        File result;
12697        do {
12698            result = new File(targetDir, packageName + "-" + suffix);
12699            suffix++;
12700        } while (result.exists());
12701        return result;
12702    }
12703
12704    // Utility method that returns the relative package path with respect
12705    // to the installation directory. Like say for /data/data/com.test-1.apk
12706    // string com.test-1 is returned.
12707    static String deriveCodePathName(String codePath) {
12708        if (codePath == null) {
12709            return null;
12710        }
12711        final File codeFile = new File(codePath);
12712        final String name = codeFile.getName();
12713        if (codeFile.isDirectory()) {
12714            return name;
12715        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12716            final int lastDot = name.lastIndexOf('.');
12717            return name.substring(0, lastDot);
12718        } else {
12719            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12720            return null;
12721        }
12722    }
12723
12724    static class PackageInstalledInfo {
12725        String name;
12726        int uid;
12727        // The set of users that originally had this package installed.
12728        int[] origUsers;
12729        // The set of users that now have this package installed.
12730        int[] newUsers;
12731        PackageParser.Package pkg;
12732        int returnCode;
12733        String returnMsg;
12734        PackageRemovedInfo removedInfo;
12735        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12736
12737        public void setError(int code, String msg) {
12738            setReturnCode(code);
12739            setReturnMessage(msg);
12740            Slog.w(TAG, msg);
12741        }
12742
12743        public void setError(String msg, PackageParserException e) {
12744            setReturnCode(e.error);
12745            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12746            Slog.w(TAG, msg, e);
12747        }
12748
12749        public void setError(String msg, PackageManagerException e) {
12750            returnCode = e.error;
12751            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12752            Slog.w(TAG, msg, e);
12753        }
12754
12755        public void setReturnCode(int returnCode) {
12756            this.returnCode = returnCode;
12757            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12758            for (int i = 0; i < childCount; i++) {
12759                addedChildPackages.valueAt(i).returnCode = returnCode;
12760            }
12761        }
12762
12763        private void setReturnMessage(String returnMsg) {
12764            this.returnMsg = returnMsg;
12765            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12766            for (int i = 0; i < childCount; i++) {
12767                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12768            }
12769        }
12770
12771        // In some error cases we want to convey more info back to the observer
12772        String origPackage;
12773        String origPermission;
12774    }
12775
12776    /*
12777     * Install a non-existing package.
12778     */
12779    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12780            UserHandle user, String installerPackageName, String volumeUuid,
12781            PackageInstalledInfo res) {
12782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12783
12784        // Remember this for later, in case we need to rollback this install
12785        String pkgName = pkg.packageName;
12786
12787        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12788
12789        synchronized(mPackages) {
12790            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12791                // A package with the same name is already installed, though
12792                // it has been renamed to an older name.  The package we
12793                // are trying to install should be installed as an update to
12794                // the existing one, but that has not been requested, so bail.
12795                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12796                        + " without first uninstalling package running as "
12797                        + mSettings.mRenamedPackages.get(pkgName));
12798                return;
12799            }
12800            if (mPackages.containsKey(pkgName)) {
12801                // Don't allow installation over an existing package with the same name.
12802                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12803                        + " without first uninstalling.");
12804                return;
12805            }
12806        }
12807
12808        try {
12809            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12810                    System.currentTimeMillis(), user);
12811
12812            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12813
12814            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12815                prepareAppDataAfterInstall(newPackage);
12816
12817            } else {
12818                // Remove package from internal structures, but keep around any
12819                // data that might have already existed
12820                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12821                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12822            }
12823        } catch (PackageManagerException e) {
12824            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12825        }
12826
12827        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12828    }
12829
12830    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12831        // Can't rotate keys during boot or if sharedUser.
12832        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12833                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12834            return false;
12835        }
12836        // app is using upgradeKeySets; make sure all are valid
12837        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12838        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12839        for (int i = 0; i < upgradeKeySets.length; i++) {
12840            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12841                Slog.wtf(TAG, "Package "
12842                         + (oldPs.name != null ? oldPs.name : "<null>")
12843                         + " contains upgrade-key-set reference to unknown key-set: "
12844                         + upgradeKeySets[i]
12845                         + " reverting to signatures check.");
12846                return false;
12847            }
12848        }
12849        return true;
12850    }
12851
12852    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12853        // Upgrade keysets are being used.  Determine if new package has a superset of the
12854        // required keys.
12855        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12856        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12857        for (int i = 0; i < upgradeKeySets.length; i++) {
12858            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12859            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12860                return true;
12861            }
12862        }
12863        return false;
12864    }
12865
12866    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12867            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12868        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12869
12870        final PackageParser.Package oldPackage;
12871        final String pkgName = pkg.packageName;
12872        final int[] allUsers;
12873
12874        // First find the old package info and check signatures
12875        synchronized(mPackages) {
12876            oldPackage = mPackages.get(pkgName);
12877            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12878            if (isEphemeral && !oldIsEphemeral) {
12879                // can't downgrade from full to ephemeral
12880                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12881                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
12882                return;
12883            }
12884            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12885            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12886            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12887                if (!checkUpgradeKeySetLP(ps, pkg)) {
12888                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12889                            "New package not signed by keys specified by upgrade-keysets: "
12890                                    + pkgName);
12891                    return;
12892                }
12893            } else {
12894                // default to original signature matching
12895                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12896                        != PackageManager.SIGNATURE_MATCH) {
12897                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12898                            "New package has a different signature: " + pkgName);
12899                    return;
12900                }
12901            }
12902
12903            // In case of rollback, remember per-user/profile install state
12904            allUsers = sUserManager.getUserIds();
12905        }
12906
12907        // Update what is removed
12908        res.removedInfo = new PackageRemovedInfo();
12909        res.removedInfo.uid = oldPackage.applicationInfo.uid;
12910        res.removedInfo.removedPackage = oldPackage.packageName;
12911        res.removedInfo.isUpdate = true;
12912        final int childCount = (oldPackage.childPackages != null)
12913                ? oldPackage.childPackages.size() : 0;
12914        for (int i = 0; i < childCount; i++) {
12915            boolean childPackageUpdated = false;
12916            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
12917            if (res.addedChildPackages != null) {
12918                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
12919                if (childRes != null) {
12920                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
12921                    childRes.removedInfo.removedPackage = childPkg.packageName;
12922                    childRes.removedInfo.isUpdate = true;
12923                    childPackageUpdated = true;
12924                }
12925            }
12926            if (!childPackageUpdated) {
12927                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
12928                childRemovedRes.removedPackage = childPkg.packageName;
12929                childRemovedRes.isUpdate = false;
12930                childRemovedRes.dataRemoved = true;
12931                synchronized (mPackages) {
12932                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
12933                    if (childPs != null) {
12934                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
12935                    }
12936                }
12937                if (res.removedInfo.removedChildPackages == null) {
12938                    res.removedInfo.removedChildPackages = new ArrayMap<>();
12939                }
12940                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
12941            }
12942        }
12943
12944        boolean sysPkg = (isSystemApp(oldPackage));
12945        if (sysPkg) {
12946            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12947                    user, allUsers, installerPackageName, res);
12948        } else {
12949            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12950                    user, allUsers, installerPackageName, res);
12951        }
12952    }
12953
12954    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12955            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12956            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
12957        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12958                + deletedPackage);
12959
12960        String pkgName = deletedPackage.packageName;
12961        boolean deletedPkg = true;
12962        boolean addedPkg = false;
12963
12964        final long origUpdateTime = (pkg.mExtras != null)
12965                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
12966
12967        // First delete the existing package while retaining the data directory
12968        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
12969                res.removedInfo, true, pkg)) {
12970            // If the existing package wasn't successfully deleted
12971            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12972            deletedPkg = false;
12973        } else {
12974            // Successfully deleted the old package; proceed with replace.
12975
12976            // If deleted package lived in a container, give users a chance to
12977            // relinquish resources before killing.
12978            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12979                if (DEBUG_INSTALL) {
12980                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12981                }
12982                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12983                final ArrayList<String> pkgList = new ArrayList<String>(1);
12984                pkgList.add(deletedPackage.applicationInfo.packageName);
12985                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12986            }
12987
12988            deleteCodeCacheDirsLI(pkg);
12989
12990            try {
12991                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12992                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12993                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
12994                prepareAppDataAfterInstall(newPackage);
12995                addedPkg = true;
12996            } catch (PackageManagerException e) {
12997                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12998            }
12999        }
13000
13001        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13002            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13003
13004            // Revert all internal state mutations and added folders for the failed install
13005            if (addedPkg) {
13006                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13007                        res.removedInfo, true, null);
13008            }
13009
13010            // Restore the old package
13011            if (deletedPkg) {
13012                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13013                File restoreFile = new File(deletedPackage.codePath);
13014                // Parse old package
13015                boolean oldExternal = isExternal(deletedPackage);
13016                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13017                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13018                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13019                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13020                try {
13021                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13022                            null);
13023                } catch (PackageManagerException e) {
13024                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13025                            + e.getMessage());
13026                    return;
13027                }
13028
13029                synchronized (mPackages) {
13030                    // Ensure the installer package name up to date
13031                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13032
13033                    // Update permissions for restored package
13034                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13035
13036                    mSettings.writeLPr();
13037                }
13038
13039                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13040            }
13041        } else {
13042            synchronized (mPackages) {
13043                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13044                if (ps != null) {
13045                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13046                    if (res.removedInfo.removedChildPackages != null) {
13047                        final int childCount = res.removedInfo.removedChildPackages.size();
13048                        // Iterate in reverse as we may modify the collection
13049                        for (int i = childCount - 1; i >= 0; i--) {
13050                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13051                            if (res.addedChildPackages.containsKey(childPackageName)) {
13052                                res.removedInfo.removedChildPackages.removeAt(i);
13053                            } else {
13054                                PackageRemovedInfo childInfo = res.removedInfo
13055                                        .removedChildPackages.valueAt(i);
13056                                childInfo.removedForAllUsers = mPackages.get(
13057                                        childInfo.removedPackage) == null;
13058                            }
13059                        }
13060                    }
13061                }
13062            }
13063        }
13064    }
13065
13066    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13067            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13068            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13069        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13070                + ", old=" + deletedPackage);
13071
13072        final boolean disabledSystem;
13073
13074        // Set the system/privileged flags as needed
13075        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13076        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13077                != 0) {
13078            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13079        }
13080
13081        // Kill package processes including services, providers, etc.
13082        killPackage(deletedPackage, "replace sys pkg");
13083
13084        // Remove existing system package
13085        removePackageLI(deletedPackage, true);
13086
13087        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13088        if (!disabledSystem) {
13089            // We didn't need to disable the .apk as a current system package,
13090            // which means we are replacing another update that is already
13091            // installed.  We need to make sure to delete the older one's .apk.
13092            res.removedInfo.args = createInstallArgsForExisting(0,
13093                    deletedPackage.applicationInfo.getCodePath(),
13094                    deletedPackage.applicationInfo.getResourcePath(),
13095                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13096        } else {
13097            res.removedInfo.args = null;
13098        }
13099
13100        // Successfully disabled the old package. Now proceed with re-installation
13101        deleteCodeCacheDirsLI(pkg);
13102
13103        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13104        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13105                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13106
13107        PackageParser.Package newPackage = null;
13108        try {
13109            // Add the package to the internal data structures
13110            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13111
13112            // Set the update and install times
13113            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13114            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13115                    System.currentTimeMillis());
13116
13117            // Check for shared user id changes
13118            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13119                    deletedPackage, newPackage);
13120            if (invalidPackageName != null) {
13121                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13122                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13123                                + " to " + invalidPackageName);
13124            }
13125
13126            // Update the package dynamic state if succeeded
13127            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13128                // Now that the install succeeded make sure we remove data
13129                // directories for any child package the update removed.
13130                final int deletedChildCount = (deletedPackage.childPackages != null)
13131                        ? deletedPackage.childPackages.size() : 0;
13132                final int newChildCount = (newPackage.childPackages != null)
13133                        ? newPackage.childPackages.size() : 0;
13134                for (int i = 0; i < deletedChildCount; i++) {
13135                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13136                    boolean childPackageDeleted = true;
13137                    for (int j = 0; j < newChildCount; j++) {
13138                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13139                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13140                            childPackageDeleted = false;
13141                            break;
13142                        }
13143                    }
13144                    if (childPackageDeleted) {
13145                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13146                                deletedChildPkg.packageName);
13147                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13148                            PackageRemovedInfo removedChildRes = res.removedInfo
13149                                    .removedChildPackages.get(deletedChildPkg.packageName);
13150                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13151                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13152                        }
13153                    }
13154                }
13155
13156                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13157                prepareAppDataAfterInstall(newPackage);
13158            }
13159        } catch (PackageManagerException e) {
13160            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13161            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13162        }
13163
13164        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13165            // Re installation failed. Restore old information
13166            // Remove new pkg information
13167            if (newPackage != null) {
13168                removeInstalledPackageLI(newPackage, true);
13169            }
13170            // Add back the old system package
13171            try {
13172                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13173            } catch (PackageManagerException e) {
13174                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13175            }
13176
13177            synchronized (mPackages) {
13178                if (disabledSystem) {
13179                    enableSystemPackageLPw(deletedPackage);
13180                }
13181
13182                // Ensure the installer package name up to date
13183                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13184
13185                // Update permissions for restored package
13186                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13187
13188                mSettings.writeLPr();
13189            }
13190
13191            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13192                    + " after failed upgrade");
13193        }
13194    }
13195
13196    /**
13197     * Checks whether the parent or any of the child packages have a change shared
13198     * user. For a package to be a valid update the shred users of the parent and
13199     * the children should match. We may later support changing child shared users.
13200     * @param oldPkg The updated package.
13201     * @param newPkg The update package.
13202     * @return The shared user that change between the versions.
13203     */
13204    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13205            PackageParser.Package newPkg) {
13206        // Check parent shared user
13207        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13208            return newPkg.packageName;
13209        }
13210        // Check child shared users
13211        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13212        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13213        for (int i = 0; i < newChildCount; i++) {
13214            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13215            // If this child was present, did it have the same shared user?
13216            for (int j = 0; j < oldChildCount; j++) {
13217                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13218                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13219                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13220                    return newChildPkg.packageName;
13221                }
13222            }
13223        }
13224        return null;
13225    }
13226
13227    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13228        // Remove the lib path for the parent package
13229        PackageSetting ps = (PackageSetting) pkg.mExtras;
13230        if (ps != null) {
13231            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13232        }
13233        // Remove the lib path for the child packages
13234        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13235        for (int i = 0; i < childCount; i++) {
13236            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13237            if (ps != null) {
13238                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13239            }
13240        }
13241    }
13242
13243    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13244        // Enable the parent package
13245        mSettings.enableSystemPackageLPw(pkg.packageName);
13246        // Enable the child packages
13247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13248        for (int i = 0; i < childCount; i++) {
13249            PackageParser.Package childPkg = pkg.childPackages.get(i);
13250            mSettings.enableSystemPackageLPw(childPkg.packageName);
13251        }
13252    }
13253
13254    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13255            PackageParser.Package newPkg) {
13256        // Disable the parent package (parent always replaced)
13257        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13258        // Disable the child packages
13259        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13260        for (int i = 0; i < childCount; i++) {
13261            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13262            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13263            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13264        }
13265        return disabled;
13266    }
13267
13268    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13269            String installerPackageName) {
13270        // Enable the parent package
13271        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13272        // Enable the child packages
13273        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13274        for (int i = 0; i < childCount; i++) {
13275            PackageParser.Package childPkg = pkg.childPackages.get(i);
13276            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13277        }
13278    }
13279
13280    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13281        // Collect all used permissions in the UID
13282        ArraySet<String> usedPermissions = new ArraySet<>();
13283        final int packageCount = su.packages.size();
13284        for (int i = 0; i < packageCount; i++) {
13285            PackageSetting ps = su.packages.valueAt(i);
13286            if (ps.pkg == null) {
13287                continue;
13288            }
13289            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13290            for (int j = 0; j < requestedPermCount; j++) {
13291                String permission = ps.pkg.requestedPermissions.get(j);
13292                BasePermission bp = mSettings.mPermissions.get(permission);
13293                if (bp != null) {
13294                    usedPermissions.add(permission);
13295                }
13296            }
13297        }
13298
13299        PermissionsState permissionsState = su.getPermissionsState();
13300        // Prune install permissions
13301        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13302        final int installPermCount = installPermStates.size();
13303        for (int i = installPermCount - 1; i >= 0;  i--) {
13304            PermissionState permissionState = installPermStates.get(i);
13305            if (!usedPermissions.contains(permissionState.getName())) {
13306                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13307                if (bp != null) {
13308                    permissionsState.revokeInstallPermission(bp);
13309                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13310                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13311                }
13312            }
13313        }
13314
13315        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13316
13317        // Prune runtime permissions
13318        for (int userId : allUserIds) {
13319            List<PermissionState> runtimePermStates = permissionsState
13320                    .getRuntimePermissionStates(userId);
13321            final int runtimePermCount = runtimePermStates.size();
13322            for (int i = runtimePermCount - 1; i >= 0; i--) {
13323                PermissionState permissionState = runtimePermStates.get(i);
13324                if (!usedPermissions.contains(permissionState.getName())) {
13325                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13326                    if (bp != null) {
13327                        permissionsState.revokeRuntimePermission(bp, userId);
13328                        permissionsState.updatePermissionFlags(bp, userId,
13329                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13330                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13331                                runtimePermissionChangedUserIds, userId);
13332                    }
13333                }
13334            }
13335        }
13336
13337        return runtimePermissionChangedUserIds;
13338    }
13339
13340    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13341            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13342        // Update the parent package setting
13343        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13344                res, user);
13345        // Update the child packages setting
13346        final int childCount = (newPackage.childPackages != null)
13347                ? newPackage.childPackages.size() : 0;
13348        for (int i = 0; i < childCount; i++) {
13349            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13350            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13351            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13352                    childRes.origUsers, childRes, user);
13353        }
13354    }
13355
13356    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13357            String installerPackageName, int[] allUsers, int[] installedForUsers,
13358            PackageInstalledInfo res, UserHandle user) {
13359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13360
13361        String pkgName = newPackage.packageName;
13362        synchronized (mPackages) {
13363            //write settings. the installStatus will be incomplete at this stage.
13364            //note that the new package setting would have already been
13365            //added to mPackages. It hasn't been persisted yet.
13366            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13367            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13368            mSettings.writeLPr();
13369            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13370        }
13371
13372        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13373        synchronized (mPackages) {
13374            updatePermissionsLPw(newPackage.packageName, newPackage,
13375                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13376                            ? UPDATE_PERMISSIONS_ALL : 0));
13377            // For system-bundled packages, we assume that installing an upgraded version
13378            // of the package implies that the user actually wants to run that new code,
13379            // so we enable the package.
13380            PackageSetting ps = mSettings.mPackages.get(pkgName);
13381            final int userId = user.getIdentifier();
13382            if (ps != null) {
13383                if (isSystemApp(newPackage)) {
13384                    if (DEBUG_INSTALL) {
13385                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13386                    }
13387                    // Enable system package for requested users
13388                    if (res.origUsers != null) {
13389                        for (int origUserId : res.origUsers) {
13390                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13391                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13392                                        origUserId, installerPackageName);
13393                            }
13394                        }
13395                    }
13396                    // Also convey the prior install/uninstall state
13397                    if (allUsers != null && installedForUsers != null) {
13398                        for (int currentUserId : allUsers) {
13399                            final boolean installed = ArrayUtils.contains(
13400                                    installedForUsers, currentUserId);
13401                            if (DEBUG_INSTALL) {
13402                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13403                            }
13404                            ps.setInstalled(installed, currentUserId);
13405                        }
13406                        // these install state changes will be persisted in the
13407                        // upcoming call to mSettings.writeLPr().
13408                    }
13409                }
13410                // It's implied that when a user requests installation, they want the app to be
13411                // installed and enabled.
13412                if (userId != UserHandle.USER_ALL) {
13413                    ps.setInstalled(true, userId);
13414                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13415                }
13416            }
13417            res.name = pkgName;
13418            res.uid = newPackage.applicationInfo.uid;
13419            res.pkg = newPackage;
13420            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13421            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13422            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13423            //to update install status
13424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13425            mSettings.writeLPr();
13426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13427        }
13428
13429        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13430    }
13431
13432    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13433        try {
13434            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13435            installPackageLI(args, res);
13436        } finally {
13437            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13438        }
13439    }
13440
13441    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13442        final int installFlags = args.installFlags;
13443        final String installerPackageName = args.installerPackageName;
13444        final String volumeUuid = args.volumeUuid;
13445        final File tmpPackageFile = new File(args.getCodePath());
13446        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13447        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13448                || (args.volumeUuid != null));
13449        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13450        boolean replace = false;
13451        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13452        if (args.move != null) {
13453            // moving a complete application; perform an initial scan on the new install location
13454            scanFlags |= SCAN_INITIAL;
13455        }
13456
13457        // Result object to be returned
13458        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13459
13460        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13461
13462        // Sanity check
13463        if (ephemeral && (forwardLocked || onExternal)) {
13464            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13465                    + " external=" + onExternal);
13466            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13467            return;
13468        }
13469
13470        // Retrieve PackageSettings and parse package
13471        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13472                | PackageParser.PARSE_ENFORCE_CODE
13473                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13474                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13475                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13476        PackageParser pp = new PackageParser();
13477        pp.setSeparateProcesses(mSeparateProcesses);
13478        pp.setDisplayMetrics(mMetrics);
13479
13480        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13481        final PackageParser.Package pkg;
13482        try {
13483            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13484        } catch (PackageParserException e) {
13485            res.setError("Failed parse during installPackageLI", e);
13486            return;
13487        } finally {
13488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13489        }
13490
13491        // If we are installing a clustered package add results for the children
13492        if (pkg.childPackages != null) {
13493            synchronized (mPackages) {
13494                final int childCount = pkg.childPackages.size();
13495                for (int i = 0; i < childCount; i++) {
13496                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13497                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13498                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13499                    childRes.pkg = childPkg;
13500                    childRes.name = childPkg.packageName;
13501                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13502                    if (childPs != null) {
13503                        childRes.origUsers = childPs.queryInstalledUsers(
13504                                sUserManager.getUserIds(), true);
13505                    }
13506                    if ((mPackages.containsKey(childPkg.packageName))) {
13507                        childRes.removedInfo = new PackageRemovedInfo();
13508                        childRes.removedInfo.removedPackage = childPkg.packageName;
13509                    }
13510                    if (res.addedChildPackages == null) {
13511                        res.addedChildPackages = new ArrayMap<>();
13512                    }
13513                    res.addedChildPackages.put(childPkg.packageName, childRes);
13514                }
13515            }
13516        }
13517
13518        // If package doesn't declare API override, mark that we have an install
13519        // time CPU ABI override.
13520        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13521            pkg.cpuAbiOverride = args.abiOverride;
13522        }
13523
13524        String pkgName = res.name = pkg.packageName;
13525        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13526            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13527                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13528                return;
13529            }
13530        }
13531
13532        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13533        try {
13534            PackageParser.collectCertificates(pkg, parseFlags);
13535        } catch (PackageParserException e) {
13536            res.setError("Failed collect during installPackageLI", e);
13537            return;
13538        } finally {
13539            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13540        }
13541
13542        // Get rid of all references to package scan path via parser.
13543        pp = null;
13544        String oldCodePath = null;
13545        boolean systemApp = false;
13546        synchronized (mPackages) {
13547            // Check if installing already existing package
13548            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13549                String oldName = mSettings.mRenamedPackages.get(pkgName);
13550                if (pkg.mOriginalPackages != null
13551                        && pkg.mOriginalPackages.contains(oldName)
13552                        && mPackages.containsKey(oldName)) {
13553                    // This package is derived from an original package,
13554                    // and this device has been updating from that original
13555                    // name.  We must continue using the original name, so
13556                    // rename the new package here.
13557                    pkg.setPackageName(oldName);
13558                    pkgName = pkg.packageName;
13559                    replace = true;
13560                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13561                            + oldName + " pkgName=" + pkgName);
13562                } else if (mPackages.containsKey(pkgName)) {
13563                    // This package, under its official name, already exists
13564                    // on the device; we should replace it.
13565                    replace = true;
13566                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13567                }
13568
13569                // Child packages are installed through the parent package
13570                if (pkg.parentPackage != null) {
13571                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13572                            "Package " + pkg.packageName + " is child of package "
13573                                    + pkg.parentPackage.parentPackage + ". Child packages "
13574                                    + "can be updated only through the parent package.");
13575                    return;
13576                }
13577
13578                if (replace) {
13579                    // Prevent apps opting out from runtime permissions
13580                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13581                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13582                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13583                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13584                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13585                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13586                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13587                                        + " doesn't support runtime permissions but the old"
13588                                        + " target SDK " + oldTargetSdk + " does.");
13589                        return;
13590                    }
13591
13592                    // Prevent installing of child packages
13593                    if (oldPackage.parentPackage != null) {
13594                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13595                                "Package " + pkg.packageName + " is child of package "
13596                                        + oldPackage.parentPackage + ". Child packages "
13597                                        + "can be updated only through the parent package.");
13598                        return;
13599                    }
13600                }
13601            }
13602
13603            PackageSetting ps = mSettings.mPackages.get(pkgName);
13604            if (ps != null) {
13605                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13606
13607                // Quick sanity check that we're signed correctly if updating;
13608                // we'll check this again later when scanning, but we want to
13609                // bail early here before tripping over redefined permissions.
13610                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13611                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13612                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13613                                + pkg.packageName + " upgrade keys do not match the "
13614                                + "previously installed version");
13615                        return;
13616                    }
13617                } else {
13618                    try {
13619                        verifySignaturesLP(ps, pkg);
13620                    } catch (PackageManagerException e) {
13621                        res.setError(e.error, e.getMessage());
13622                        return;
13623                    }
13624                }
13625
13626                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13627                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13628                    systemApp = (ps.pkg.applicationInfo.flags &
13629                            ApplicationInfo.FLAG_SYSTEM) != 0;
13630                }
13631                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13632            }
13633
13634            // Check whether the newly-scanned package wants to define an already-defined perm
13635            int N = pkg.permissions.size();
13636            for (int i = N-1; i >= 0; i--) {
13637                PackageParser.Permission perm = pkg.permissions.get(i);
13638                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13639                if (bp != null) {
13640                    // If the defining package is signed with our cert, it's okay.  This
13641                    // also includes the "updating the same package" case, of course.
13642                    // "updating same package" could also involve key-rotation.
13643                    final boolean sigsOk;
13644                    if (bp.sourcePackage.equals(pkg.packageName)
13645                            && (bp.packageSetting instanceof PackageSetting)
13646                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13647                                    scanFlags))) {
13648                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13649                    } else {
13650                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13651                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13652                    }
13653                    if (!sigsOk) {
13654                        // If the owning package is the system itself, we log but allow
13655                        // install to proceed; we fail the install on all other permission
13656                        // redefinitions.
13657                        if (!bp.sourcePackage.equals("android")) {
13658                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13659                                    + pkg.packageName + " attempting to redeclare permission "
13660                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13661                            res.origPermission = perm.info.name;
13662                            res.origPackage = bp.sourcePackage;
13663                            return;
13664                        } else {
13665                            Slog.w(TAG, "Package " + pkg.packageName
13666                                    + " attempting to redeclare system permission "
13667                                    + perm.info.name + "; ignoring new declaration");
13668                            pkg.permissions.remove(i);
13669                        }
13670                    }
13671                }
13672            }
13673        }
13674
13675        if (systemApp) {
13676            if (onExternal) {
13677                // Abort update; system app can't be replaced with app on sdcard
13678                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13679                        "Cannot install updates to system apps on sdcard");
13680                return;
13681            } else if (ephemeral) {
13682                // Abort update; system app can't be replaced with an ephemeral app
13683                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13684                        "Cannot update a system app with an ephemeral app");
13685                return;
13686            }
13687        }
13688
13689        if (args.move != null) {
13690            // We did an in-place move, so dex is ready to roll
13691            scanFlags |= SCAN_NO_DEX;
13692            scanFlags |= SCAN_MOVE;
13693
13694            synchronized (mPackages) {
13695                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13696                if (ps == null) {
13697                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13698                            "Missing settings for moved package " + pkgName);
13699                }
13700
13701                // We moved the entire application as-is, so bring over the
13702                // previously derived ABI information.
13703                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13704                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13705            }
13706
13707        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13708            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13709            scanFlags |= SCAN_NO_DEX;
13710
13711            try {
13712                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13713                    args.abiOverride : pkg.cpuAbiOverride);
13714                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13715                        true /* extract libs */);
13716            } catch (PackageManagerException pme) {
13717                Slog.e(TAG, "Error deriving application ABI", pme);
13718                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13719                return;
13720            }
13721
13722            // Extract package to save the VM unzipping the APK in memory during
13723            // launch. Only do this if profile-guided compilation is enabled because
13724            // otherwise BackgroundDexOptService will not dexopt the package later.
13725            if (mUseJitProfiles) {
13726                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13727                // Do not run PackageDexOptimizer through the local performDexOpt
13728                // method because `pkg` is not in `mPackages` yet.
13729                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13730                        false /* useProfiles */, true /* extractOnly */);
13731                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13732                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13733                    String msg = "Extracking package failed for " + pkgName;
13734                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13735                    return;
13736                }
13737            }
13738        }
13739
13740        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13741            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13742            return;
13743        }
13744
13745        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13746
13747        if (replace) {
13748            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13749                    installerPackageName, res);
13750        } else {
13751            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13752                    args.user, installerPackageName, volumeUuid, res);
13753        }
13754        synchronized (mPackages) {
13755            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13756            if (ps != null) {
13757                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13758            }
13759
13760            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13761            for (int i = 0; i < childCount; i++) {
13762                PackageParser.Package childPkg = pkg.childPackages.get(i);
13763                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13764                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13765                if (childPs != null) {
13766                    childRes.newUsers = childPs.queryInstalledUsers(
13767                            sUserManager.getUserIds(), true);
13768                }
13769            }
13770        }
13771    }
13772
13773    private void startIntentFilterVerifications(int userId, boolean replacing,
13774            PackageParser.Package pkg) {
13775        if (mIntentFilterVerifierComponent == null) {
13776            Slog.w(TAG, "No IntentFilter verification will not be done as "
13777                    + "there is no IntentFilterVerifier available!");
13778            return;
13779        }
13780
13781        final int verifierUid = getPackageUid(
13782                mIntentFilterVerifierComponent.getPackageName(),
13783                MATCH_DEBUG_TRIAGED_MISSING,
13784                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13785
13786        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13787        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13788        mHandler.sendMessage(msg);
13789
13790        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13791        for (int i = 0; i < childCount; i++) {
13792            PackageParser.Package childPkg = pkg.childPackages.get(i);
13793            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13794            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13795            mHandler.sendMessage(msg);
13796        }
13797    }
13798
13799    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13800            PackageParser.Package pkg) {
13801        int size = pkg.activities.size();
13802        if (size == 0) {
13803            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13804                    "No activity, so no need to verify any IntentFilter!");
13805            return;
13806        }
13807
13808        final boolean hasDomainURLs = hasDomainURLs(pkg);
13809        if (!hasDomainURLs) {
13810            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13811                    "No domain URLs, so no need to verify any IntentFilter!");
13812            return;
13813        }
13814
13815        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13816                + " if any IntentFilter from the " + size
13817                + " Activities needs verification ...");
13818
13819        int count = 0;
13820        final String packageName = pkg.packageName;
13821
13822        synchronized (mPackages) {
13823            // If this is a new install and we see that we've already run verification for this
13824            // package, we have nothing to do: it means the state was restored from backup.
13825            if (!replacing) {
13826                IntentFilterVerificationInfo ivi =
13827                        mSettings.getIntentFilterVerificationLPr(packageName);
13828                if (ivi != null) {
13829                    if (DEBUG_DOMAIN_VERIFICATION) {
13830                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13831                                + ivi.getStatusString());
13832                    }
13833                    return;
13834                }
13835            }
13836
13837            // If any filters need to be verified, then all need to be.
13838            boolean needToVerify = false;
13839            for (PackageParser.Activity a : pkg.activities) {
13840                for (ActivityIntentInfo filter : a.intents) {
13841                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13842                        if (DEBUG_DOMAIN_VERIFICATION) {
13843                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13844                        }
13845                        needToVerify = true;
13846                        break;
13847                    }
13848                }
13849            }
13850
13851            if (needToVerify) {
13852                final int verificationId = mIntentFilterVerificationToken++;
13853                for (PackageParser.Activity a : pkg.activities) {
13854                    for (ActivityIntentInfo filter : a.intents) {
13855                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13856                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13857                                    "Verification needed for IntentFilter:" + filter.toString());
13858                            mIntentFilterVerifier.addOneIntentFilterVerification(
13859                                    verifierUid, userId, verificationId, filter, packageName);
13860                            count++;
13861                        }
13862                    }
13863                }
13864            }
13865        }
13866
13867        if (count > 0) {
13868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13869                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13870                    +  " for userId:" + userId);
13871            mIntentFilterVerifier.startVerifications(userId);
13872        } else {
13873            if (DEBUG_DOMAIN_VERIFICATION) {
13874                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13875            }
13876        }
13877    }
13878
13879    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13880        final ComponentName cn  = filter.activity.getComponentName();
13881        final String packageName = cn.getPackageName();
13882
13883        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13884                packageName);
13885        if (ivi == null) {
13886            return true;
13887        }
13888        int status = ivi.getStatus();
13889        switch (status) {
13890            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13891            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13892                return true;
13893
13894            default:
13895                // Nothing to do
13896                return false;
13897        }
13898    }
13899
13900    private static boolean isMultiArch(ApplicationInfo info) {
13901        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13902    }
13903
13904    private static boolean isExternal(PackageParser.Package pkg) {
13905        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13906    }
13907
13908    private static boolean isExternal(PackageSetting ps) {
13909        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13910    }
13911
13912    private static boolean isEphemeral(PackageParser.Package pkg) {
13913        return pkg.applicationInfo.isEphemeralApp();
13914    }
13915
13916    private static boolean isEphemeral(PackageSetting ps) {
13917        return ps.pkg != null && isEphemeral(ps.pkg);
13918    }
13919
13920    private static boolean isSystemApp(PackageParser.Package pkg) {
13921        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13922    }
13923
13924    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13925        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13926    }
13927
13928    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13929        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13930    }
13931
13932    private static boolean isSystemApp(PackageSetting ps) {
13933        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13934    }
13935
13936    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13937        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13938    }
13939
13940    private int packageFlagsToInstallFlags(PackageSetting ps) {
13941        int installFlags = 0;
13942        if (isEphemeral(ps)) {
13943            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13944        }
13945        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13946            // This existing package was an external ASEC install when we have
13947            // the external flag without a UUID
13948            installFlags |= PackageManager.INSTALL_EXTERNAL;
13949        }
13950        if (ps.isForwardLocked()) {
13951            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13952        }
13953        return installFlags;
13954    }
13955
13956    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13957        if (isExternal(pkg)) {
13958            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13959                return StorageManager.UUID_PRIMARY_PHYSICAL;
13960            } else {
13961                return pkg.volumeUuid;
13962            }
13963        } else {
13964            return StorageManager.UUID_PRIVATE_INTERNAL;
13965        }
13966    }
13967
13968    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13969        if (isExternal(pkg)) {
13970            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13971                return mSettings.getExternalVersion();
13972            } else {
13973                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13974            }
13975        } else {
13976            return mSettings.getInternalVersion();
13977        }
13978    }
13979
13980    private void deleteTempPackageFiles() {
13981        final FilenameFilter filter = new FilenameFilter() {
13982            public boolean accept(File dir, String name) {
13983                return name.startsWith("vmdl") && name.endsWith(".tmp");
13984            }
13985        };
13986        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13987            file.delete();
13988        }
13989    }
13990
13991    @Override
13992    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13993            int flags) {
13994        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13995                flags);
13996    }
13997
13998    @Override
13999    public void deletePackage(final String packageName,
14000            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14001        mContext.enforceCallingOrSelfPermission(
14002                android.Manifest.permission.DELETE_PACKAGES, null);
14003        Preconditions.checkNotNull(packageName);
14004        Preconditions.checkNotNull(observer);
14005        final int uid = Binder.getCallingUid();
14006        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14007        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14008        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14009            mContext.enforceCallingOrSelfPermission(
14010                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14011                    "deletePackage for user " + userId);
14012        }
14013
14014        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14015            try {
14016                observer.onPackageDeleted(packageName,
14017                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14018            } catch (RemoteException re) {
14019            }
14020            return;
14021        }
14022
14023        for (int currentUserId : users) {
14024            if (getBlockUninstallForUser(packageName, currentUserId)) {
14025                try {
14026                    observer.onPackageDeleted(packageName,
14027                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14028                } catch (RemoteException re) {
14029                }
14030                return;
14031            }
14032        }
14033
14034        if (DEBUG_REMOVE) {
14035            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
14036        }
14037        // Queue up an async operation since the package deletion may take a little while.
14038        mHandler.post(new Runnable() {
14039            public void run() {
14040                mHandler.removeCallbacks(this);
14041                final int returnCode = deletePackageX(packageName, userId, flags);
14042                try {
14043                    observer.onPackageDeleted(packageName, returnCode, null);
14044                } catch (RemoteException e) {
14045                    Log.i(TAG, "Observer no longer exists.");
14046                } //end catch
14047            } //end run
14048        });
14049    }
14050
14051    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14052        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14053                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14054        try {
14055            if (dpm != null) {
14056                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14057                        /* callingUserOnly =*/ false);
14058                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14059                        : deviceOwnerComponentName.getPackageName();
14060                // Does the package contains the device owner?
14061                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14062                // this check is probably not needed, since DO should be registered as a device
14063                // admin on some user too. (Original bug for this: b/17657954)
14064                if (packageName.equals(deviceOwnerPackageName)) {
14065                    return true;
14066                }
14067                // Does it contain a device admin for any user?
14068                int[] users;
14069                if (userId == UserHandle.USER_ALL) {
14070                    users = sUserManager.getUserIds();
14071                } else {
14072                    users = new int[]{userId};
14073                }
14074                for (int i = 0; i < users.length; ++i) {
14075                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14076                        return true;
14077                    }
14078                }
14079            }
14080        } catch (RemoteException e) {
14081        }
14082        return false;
14083    }
14084
14085    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14086        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14087    }
14088
14089    /**
14090     *  This method is an internal method that could be get invoked either
14091     *  to delete an installed package or to clean up a failed installation.
14092     *  After deleting an installed package, a broadcast is sent to notify any
14093     *  listeners that the package has been installed. For cleaning up a failed
14094     *  installation, the broadcast is not necessary since the package's
14095     *  installation wouldn't have sent the initial broadcast either
14096     *  The key steps in deleting a package are
14097     *  deleting the package information in internal structures like mPackages,
14098     *  deleting the packages base directories through installd
14099     *  updating mSettings to reflect current status
14100     *  persisting settings for later use
14101     *  sending a broadcast if necessary
14102     */
14103    private int deletePackageX(String packageName, int userId, int flags) {
14104        final PackageRemovedInfo info = new PackageRemovedInfo();
14105        final boolean res;
14106
14107        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14108                ? UserHandle.ALL : new UserHandle(userId);
14109
14110        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14111            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14112            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14113        }
14114
14115        PackageSetting uninstalledPs = null;
14116
14117        // for the uninstall-updates case and restricted profiles, remember the per-
14118        // user handle installed state
14119        int[] allUsers;
14120        synchronized (mPackages) {
14121            uninstalledPs = mSettings.mPackages.get(packageName);
14122            if (uninstalledPs == null) {
14123                Slog.w(TAG, "Not removing non-existent package " + packageName);
14124                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14125            }
14126            allUsers = sUserManager.getUserIds();
14127            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14128        }
14129
14130        synchronized (mInstallLock) {
14131            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14132            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14133                    flags | REMOVE_CHATTY, info, true, null);
14134            synchronized (mPackages) {
14135                if (res) {
14136                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14137                }
14138            }
14139        }
14140
14141        if (res) {
14142            info.sendPackageRemovedBroadcasts();
14143            info.sendSystemPackageUpdatedBroadcasts();
14144            info.sendSystemPackageAppearedBroadcasts();
14145        }
14146        // Force a gc here.
14147        Runtime.getRuntime().gc();
14148        // Delete the resources here after sending the broadcast to let
14149        // other processes clean up before deleting resources.
14150        if (info.args != null) {
14151            synchronized (mInstallLock) {
14152                info.args.doPostDeleteLI(true);
14153            }
14154        }
14155
14156        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14157    }
14158
14159    class PackageRemovedInfo {
14160        String removedPackage;
14161        int uid = -1;
14162        int removedAppId = -1;
14163        int[] origUsers;
14164        int[] removedUsers = null;
14165        boolean isRemovedPackageSystemUpdate = false;
14166        boolean isUpdate;
14167        boolean dataRemoved;
14168        boolean removedForAllUsers;
14169        // Clean up resources deleted packages.
14170        InstallArgs args = null;
14171        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14172        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14173
14174        void sendPackageRemovedBroadcasts() {
14175            sendPackageRemovedBroadcastInternal();
14176            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14177            for (int i = 0; i < childCount; i++) {
14178                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14179                childInfo.sendPackageRemovedBroadcastInternal();
14180            }
14181        }
14182
14183        void sendSystemPackageUpdatedBroadcasts() {
14184            if (isRemovedPackageSystemUpdate) {
14185                sendSystemPackageUpdatedBroadcastsInternal();
14186                final int childCount = (removedChildPackages != null)
14187                        ? removedChildPackages.size() : 0;
14188                for (int i = 0; i < childCount; i++) {
14189                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14190                    if (childInfo.isRemovedPackageSystemUpdate) {
14191                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14192                    }
14193                }
14194            }
14195        }
14196
14197        void sendSystemPackageAppearedBroadcasts() {
14198            final int packageCount = (appearedChildPackages != null)
14199                    ? appearedChildPackages.size() : 0;
14200            for (int i = 0; i < packageCount; i++) {
14201                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14202                for (int userId : installedInfo.newUsers) {
14203                    sendPackageAddedForUser(installedInfo.name, true,
14204                            UserHandle.getAppId(installedInfo.uid), userId);
14205                }
14206            }
14207        }
14208
14209        private void sendSystemPackageUpdatedBroadcastsInternal() {
14210            Bundle extras = new Bundle(2);
14211            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14212            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14213            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14214                    extras, 0, null, null, null);
14215            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14216                    extras, 0, null, null, null);
14217            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14218                    null, 0, removedPackage, null, null);
14219        }
14220
14221        private void sendPackageRemovedBroadcastInternal() {
14222            Bundle extras = new Bundle(2);
14223            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14224            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14225            if (isUpdate || isRemovedPackageSystemUpdate) {
14226                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14227            }
14228            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14229            if (removedPackage != null) {
14230                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14231                        extras, 0, null, null, removedUsers);
14232                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14233                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14234                            removedPackage, extras, 0, null, null, removedUsers);
14235                }
14236            }
14237            if (removedAppId >= 0) {
14238                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14239                        removedUsers);
14240            }
14241        }
14242    }
14243
14244    /*
14245     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14246     * flag is not set, the data directory is removed as well.
14247     * make sure this flag is set for partially installed apps. If not its meaningless to
14248     * delete a partially installed application.
14249     */
14250    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14251            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14252        String packageName = ps.name;
14253        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14254        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14255        // Retrieve object to delete permissions for shared user later on
14256        final PackageSetting deletedPs;
14257        // reader
14258        synchronized (mPackages) {
14259            deletedPs = mSettings.mPackages.get(packageName);
14260            if (outInfo != null) {
14261                outInfo.removedPackage = packageName;
14262                outInfo.removedUsers = deletedPs != null
14263                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14264                        : null;
14265            }
14266        }
14267        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14268            removeDataDirsLI(ps.volumeUuid, packageName);
14269            if (outInfo != null) {
14270                outInfo.dataRemoved = true;
14271            }
14272            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14273        }
14274        // writer
14275        synchronized (mPackages) {
14276            if (deletedPs != null) {
14277                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14278                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14279                    clearDefaultBrowserIfNeeded(packageName);
14280                    if (outInfo != null) {
14281                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14282                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14283                    }
14284                    updatePermissionsLPw(deletedPs.name, null, 0);
14285                    if (deletedPs.sharedUser != null) {
14286                        // Remove permissions associated with package. Since runtime
14287                        // permissions are per user we have to kill the removed package
14288                        // or packages running under the shared user of the removed
14289                        // package if revoking the permissions requested only by the removed
14290                        // package is successful and this causes a change in gids.
14291                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14292                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14293                                    userId);
14294                            if (userIdToKill == UserHandle.USER_ALL
14295                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14296                                // If gids changed for this user, kill all affected packages.
14297                                mHandler.post(new Runnable() {
14298                                    @Override
14299                                    public void run() {
14300                                        // This has to happen with no lock held.
14301                                        killApplication(deletedPs.name, deletedPs.appId,
14302                                                KILL_APP_REASON_GIDS_CHANGED);
14303                                    }
14304                                });
14305                                break;
14306                            }
14307                        }
14308                    }
14309                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14310                }
14311                // make sure to preserve per-user disabled state if this removal was just
14312                // a downgrade of a system app to the factory package
14313                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14314                    if (DEBUG_REMOVE) {
14315                        Slog.d(TAG, "Propagating install state across downgrade");
14316                    }
14317                    for (int userId : allUserHandles) {
14318                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14319                        if (DEBUG_REMOVE) {
14320                            Slog.d(TAG, "    user " + userId + " => " + installed);
14321                        }
14322                        ps.setInstalled(installed, userId);
14323                    }
14324                }
14325            }
14326            // can downgrade to reader
14327            if (writeSettings) {
14328                // Save settings now
14329                mSettings.writeLPr();
14330            }
14331        }
14332        if (outInfo != null) {
14333            // A user ID was deleted here. Go through all users and remove it
14334            // from KeyStore.
14335            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14336        }
14337    }
14338
14339    static boolean locationIsPrivileged(File path) {
14340        try {
14341            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14342                    .getCanonicalPath();
14343            return path.getCanonicalPath().startsWith(privilegedAppDir);
14344        } catch (IOException e) {
14345            Slog.e(TAG, "Unable to access code path " + path);
14346        }
14347        return false;
14348    }
14349
14350    /*
14351     * Tries to delete system package.
14352     */
14353    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14354            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14355            boolean writeSettings) {
14356        if (deletedPkg.parentPackage != null) {
14357            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14358            return false;
14359        }
14360
14361        final boolean applyUserRestrictions
14362                = (allUserHandles != null) && (outInfo.origUsers != null);
14363        final PackageSetting disabledPs;
14364        // Confirm if the system package has been updated
14365        // An updated system app can be deleted. This will also have to restore
14366        // the system pkg from system partition
14367        // reader
14368        synchronized (mPackages) {
14369            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14370        }
14371
14372        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14373                + " disabledPs=" + disabledPs);
14374
14375        if (disabledPs == null) {
14376            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14377            return false;
14378        } else if (DEBUG_REMOVE) {
14379            Slog.d(TAG, "Deleting system pkg from data partition");
14380        }
14381
14382        if (DEBUG_REMOVE) {
14383            if (applyUserRestrictions) {
14384                Slog.d(TAG, "Remembering install states:");
14385                for (int userId : allUserHandles) {
14386                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14387                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14388                }
14389            }
14390        }
14391
14392        // Delete the updated package
14393        outInfo.isRemovedPackageSystemUpdate = true;
14394        if (outInfo.removedChildPackages != null) {
14395            final int childCount = (deletedPkg.childPackages != null)
14396                    ? deletedPkg.childPackages.size() : 0;
14397            for (int i = 0; i < childCount; i++) {
14398                String childPackageName = deletedPkg.childPackages.get(i).packageName;
14399                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14400                        .contains(childPackageName)) {
14401                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14402                            childPackageName);
14403                    if (childInfo != null) {
14404                        childInfo.isRemovedPackageSystemUpdate = true;
14405                    }
14406                }
14407            }
14408        }
14409
14410        if (disabledPs.versionCode < deletedPs.versionCode) {
14411            // Delete data for downgrades
14412            flags &= ~PackageManager.DELETE_KEEP_DATA;
14413        } else {
14414            // Preserve data by setting flag
14415            flags |= PackageManager.DELETE_KEEP_DATA;
14416        }
14417
14418        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14419                outInfo, writeSettings, disabledPs.pkg);
14420        if (!ret) {
14421            return false;
14422        }
14423
14424        // writer
14425        synchronized (mPackages) {
14426            // Reinstate the old system package
14427            enableSystemPackageLPw(disabledPs.pkg);
14428            // Remove any native libraries from the upgraded package.
14429            removeNativeBinariesLI(deletedPkg);
14430        }
14431
14432        // Install the system package
14433        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14434        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14435        if (locationIsPrivileged(disabledPs.codePath)) {
14436            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14437        }
14438
14439        final PackageParser.Package newPkg;
14440        try {
14441            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14442        } catch (PackageManagerException e) {
14443            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14444                    + e.getMessage());
14445            return false;
14446        }
14447
14448        prepareAppDataAfterInstall(newPkg);
14449
14450        // writer
14451        synchronized (mPackages) {
14452            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14453
14454            // Propagate the permissions state as we do not want to drop on the floor
14455            // runtime permissions. The update permissions method below will take
14456            // care of removing obsolete permissions and grant install permissions.
14457            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14458            updatePermissionsLPw(newPkg.packageName, newPkg,
14459                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14460
14461            if (applyUserRestrictions) {
14462                if (DEBUG_REMOVE) {
14463                    Slog.d(TAG, "Propagating install state across reinstall");
14464                }
14465                for (int userId : allUserHandles) {
14466                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14467                    if (DEBUG_REMOVE) {
14468                        Slog.d(TAG, "    user " + userId + " => " + installed);
14469                    }
14470                    ps.setInstalled(installed, userId);
14471
14472                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14473                }
14474                // Regardless of writeSettings we need to ensure that this restriction
14475                // state propagation is persisted
14476                mSettings.writeAllUsersPackageRestrictionsLPr();
14477            }
14478            // can downgrade to reader here
14479            if (writeSettings) {
14480                mSettings.writeLPr();
14481            }
14482        }
14483        return true;
14484    }
14485
14486    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14487            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14488            PackageRemovedInfo outInfo, boolean writeSettings,
14489            PackageParser.Package replacingPackage) {
14490        PackageSetting ps = null;
14491
14492        synchronized (mPackages) {
14493            pkg = mPackages.get(pkg.packageName);
14494            if (pkg == null) {
14495                return false;
14496            }
14497
14498            ps = mSettings.mPackages.get(pkg.packageName);
14499            if (ps == null) {
14500                return false;
14501            }
14502
14503            if (outInfo != null) {
14504                outInfo.uid = ps.appId;
14505            }
14506
14507            if (outInfo != null && outInfo.removedChildPackages != null) {
14508                final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14509                for (int i = 0; i < childCount; i++) {
14510                    String childPackageName = ps.childPackageNames.get(i);
14511                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14512                    if (childPs == null) {
14513                        return false;
14514                    }
14515                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14516                            childPackageName);
14517                    if (childInfo != null) {
14518                        childInfo.uid = childPs.appId;
14519                    }
14520                }
14521            }
14522        }
14523
14524        // Delete package data from internal structures and also remove data if flag is set
14525        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14526
14527        // Delete the child packages data
14528        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14529        for (int i = 0; i < childCount; i++) {
14530            PackageSetting childPs;
14531            synchronized (mPackages) {
14532                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14533            }
14534            if (childPs != null) {
14535                PackageRemovedInfo childOutInfo = (outInfo != null
14536                        && outInfo.removedChildPackages != null)
14537                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14538                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14539                        && (replacingPackage != null
14540                        && !replacingPackage.hasChildPackage(childPs.name))
14541                        ? flags & ~DELETE_KEEP_DATA : flags;
14542                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14543                        deleteFlags, writeSettings);
14544            }
14545        }
14546
14547        // Delete application code and resources only for parent packages
14548        if (ps.pkg.parentPackage == null) {
14549            if (deleteCodeAndResources && (outInfo != null)) {
14550                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14551                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14552                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14553            }
14554        }
14555
14556        return true;
14557    }
14558
14559    @Override
14560    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14561            int userId) {
14562        mContext.enforceCallingOrSelfPermission(
14563                android.Manifest.permission.DELETE_PACKAGES, null);
14564        synchronized (mPackages) {
14565            PackageSetting ps = mSettings.mPackages.get(packageName);
14566            if (ps == null) {
14567                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14568                return false;
14569            }
14570            if (!ps.getInstalled(userId)) {
14571                // Can't block uninstall for an app that is not installed or enabled.
14572                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14573                return false;
14574            }
14575            ps.setBlockUninstall(blockUninstall, userId);
14576            mSettings.writePackageRestrictionsLPr(userId);
14577        }
14578        return true;
14579    }
14580
14581    @Override
14582    public boolean getBlockUninstallForUser(String packageName, int userId) {
14583        synchronized (mPackages) {
14584            PackageSetting ps = mSettings.mPackages.get(packageName);
14585            if (ps == null) {
14586                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14587                return false;
14588            }
14589            return ps.getBlockUninstall(userId);
14590        }
14591    }
14592
14593    @Override
14594    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14595        int callingUid = Binder.getCallingUid();
14596        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14597            throw new SecurityException(
14598                    "setRequiredForSystemUser can only be run by the system or root");
14599        }
14600        synchronized (mPackages) {
14601            PackageSetting ps = mSettings.mPackages.get(packageName);
14602            if (ps == null) {
14603                Log.w(TAG, "Package doesn't exist: " + packageName);
14604                return false;
14605            }
14606            if (systemUserApp) {
14607                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14608            } else {
14609                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14610            }
14611            mSettings.writeLPr();
14612        }
14613        return true;
14614    }
14615
14616    /*
14617     * This method handles package deletion in general
14618     */
14619    private boolean deletePackageLI(String packageName, UserHandle user,
14620            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14621            PackageRemovedInfo outInfo, boolean writeSettings,
14622            PackageParser.Package replacingPackage) {
14623        if (packageName == null) {
14624            Slog.w(TAG, "Attempt to delete null packageName.");
14625            return false;
14626        }
14627
14628        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14629
14630        PackageSetting ps;
14631
14632        synchronized (mPackages) {
14633            ps = mSettings.mPackages.get(packageName);
14634            if (ps == null) {
14635                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14636                return false;
14637            }
14638
14639            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14640                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14641                if (DEBUG_REMOVE) {
14642                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14643                            + ((user == null) ? UserHandle.USER_ALL : user));
14644                }
14645                final int removedUserId = (user != null) ? user.getIdentifier()
14646                        : UserHandle.USER_ALL;
14647                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14648                    return false;
14649                }
14650                markPackageUninstalledForUserLPw(ps, user);
14651                scheduleWritePackageRestrictionsLocked(user);
14652                return true;
14653            }
14654        }
14655
14656        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14657                && user.getIdentifier() != UserHandle.USER_ALL)) {
14658            // The caller is asking that the package only be deleted for a single
14659            // user.  To do this, we just mark its uninstalled state and delete
14660            // its data. If this is a system app, we only allow this to happen if
14661            // they have set the special DELETE_SYSTEM_APP which requests different
14662            // semantics than normal for uninstalling system apps.
14663            markPackageUninstalledForUserLPw(ps, user);
14664
14665            if (!isSystemApp(ps)) {
14666                // Do not uninstall the APK if an app should be cached
14667                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14668                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14669                    // Other user still have this package installed, so all
14670                    // we need to do is clear this user's data and save that
14671                    // it is uninstalled.
14672                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14673                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14674                        return false;
14675                    }
14676                    scheduleWritePackageRestrictionsLocked(user);
14677                    return true;
14678                } else {
14679                    // We need to set it back to 'installed' so the uninstall
14680                    // broadcasts will be sent correctly.
14681                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14682                    ps.setInstalled(true, user.getIdentifier());
14683                }
14684            } else {
14685                // This is a system app, so we assume that the
14686                // other users still have this package installed, so all
14687                // we need to do is clear this user's data and save that
14688                // it is uninstalled.
14689                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14690                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14691                    return false;
14692                }
14693                scheduleWritePackageRestrictionsLocked(user);
14694                return true;
14695            }
14696        }
14697
14698        // If we are deleting a composite package for all users, keep track
14699        // of result for each child.
14700        if (ps.childPackageNames != null && outInfo != null) {
14701            synchronized (mPackages) {
14702                final int childCount = ps.childPackageNames.size();
14703                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14704                for (int i = 0; i < childCount; i++) {
14705                    String childPackageName = ps.childPackageNames.get(i);
14706                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14707                    childInfo.removedPackage = childPackageName;
14708                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14709                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14710                    if (childPs != null) {
14711                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14712                    }
14713                }
14714            }
14715        }
14716
14717        boolean ret = false;
14718        if (isSystemApp(ps)) {
14719            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14720            // When an updated system application is deleted we delete the existing resources
14721            // as well and fall back to existing code in system partition
14722            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14723        } else {
14724            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14725            // Kill application pre-emptively especially for apps on sd.
14726            killApplication(packageName, ps.appId, "uninstall pkg");
14727            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14728                    outInfo, writeSettings, replacingPackage);
14729        }
14730
14731        // Take a note whether we deleted the package for all users
14732        if (outInfo != null) {
14733            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14734            if (outInfo.removedChildPackages != null) {
14735                synchronized (mPackages) {
14736                    final int childCount = outInfo.removedChildPackages.size();
14737                    for (int i = 0; i < childCount; i++) {
14738                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14739                        if (childInfo != null) {
14740                            childInfo.removedForAllUsers = mPackages.get(
14741                                    childInfo.removedPackage) == null;
14742                        }
14743                    }
14744                }
14745            }
14746            // If we uninstalled an update to a system app there may be some
14747            // child packages that appeared as they are declared in the system
14748            // app but were not declared in the update.
14749            if (isSystemApp(ps)) {
14750                synchronized (mPackages) {
14751                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14752                    final int childCount = (updatedPs.childPackageNames != null)
14753                            ? updatedPs.childPackageNames.size() : 0;
14754                    for (int i = 0; i < childCount; i++) {
14755                        String childPackageName = updatedPs.childPackageNames.get(i);
14756                        if (outInfo.removedChildPackages == null
14757                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14758                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14759                            if (childPs == null) {
14760                                continue;
14761                            }
14762                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14763                            installRes.name = childPackageName;
14764                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14765                            installRes.pkg = mPackages.get(childPackageName);
14766                            installRes.uid = childPs.pkg.applicationInfo.uid;
14767                            if (outInfo.appearedChildPackages == null) {
14768                                outInfo.appearedChildPackages = new ArrayMap<>();
14769                            }
14770                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14771                        }
14772                    }
14773                }
14774            }
14775        }
14776
14777        return ret;
14778    }
14779
14780    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14781        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14782                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14783        for (int nextUserId : userIds) {
14784            if (DEBUG_REMOVE) {
14785                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14786            }
14787            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14788                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14789                    false /*hidden*/, false /*suspended*/, null, null, null,
14790                    false /*blockUninstall*/,
14791                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14792        }
14793    }
14794
14795    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14796            PackageRemovedInfo outInfo) {
14797        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14798                : new int[] {userId};
14799        for (int nextUserId : userIds) {
14800            if (DEBUG_REMOVE) {
14801                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14802                        + nextUserId);
14803            }
14804            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14805            try {
14806                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14807            } catch (InstallerException e) {
14808                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14809                return false;
14810            }
14811            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14812            schedulePackageCleaning(ps.name, nextUserId, false);
14813            synchronized (mPackages) {
14814                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14815                    scheduleWritePackageRestrictionsLocked(nextUserId);
14816                }
14817                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14818            }
14819        }
14820
14821        if (outInfo != null) {
14822            outInfo.removedPackage = ps.name;
14823            outInfo.removedAppId = ps.appId;
14824            outInfo.removedUsers = userIds;
14825        }
14826
14827        return true;
14828    }
14829
14830    private final class ClearStorageConnection implements ServiceConnection {
14831        IMediaContainerService mContainerService;
14832
14833        @Override
14834        public void onServiceConnected(ComponentName name, IBinder service) {
14835            synchronized (this) {
14836                mContainerService = IMediaContainerService.Stub.asInterface(service);
14837                notifyAll();
14838            }
14839        }
14840
14841        @Override
14842        public void onServiceDisconnected(ComponentName name) {
14843        }
14844    }
14845
14846    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14847        final boolean mounted;
14848        if (Environment.isExternalStorageEmulated()) {
14849            mounted = true;
14850        } else {
14851            final String status = Environment.getExternalStorageState();
14852
14853            mounted = status.equals(Environment.MEDIA_MOUNTED)
14854                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14855        }
14856
14857        if (!mounted) {
14858            return;
14859        }
14860
14861        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14862        int[] users;
14863        if (userId == UserHandle.USER_ALL) {
14864            users = sUserManager.getUserIds();
14865        } else {
14866            users = new int[] { userId };
14867        }
14868        final ClearStorageConnection conn = new ClearStorageConnection();
14869        if (mContext.bindServiceAsUser(
14870                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14871            try {
14872                for (int curUser : users) {
14873                    long timeout = SystemClock.uptimeMillis() + 5000;
14874                    synchronized (conn) {
14875                        long now = SystemClock.uptimeMillis();
14876                        while (conn.mContainerService == null && now < timeout) {
14877                            try {
14878                                conn.wait(timeout - now);
14879                            } catch (InterruptedException e) {
14880                            }
14881                        }
14882                    }
14883                    if (conn.mContainerService == null) {
14884                        return;
14885                    }
14886
14887                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14888                    clearDirectory(conn.mContainerService,
14889                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14890                    if (allData) {
14891                        clearDirectory(conn.mContainerService,
14892                                userEnv.buildExternalStorageAppDataDirs(packageName));
14893                        clearDirectory(conn.mContainerService,
14894                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14895                    }
14896                }
14897            } finally {
14898                mContext.unbindService(conn);
14899            }
14900        }
14901    }
14902
14903    @Override
14904    public void clearApplicationUserData(final String packageName,
14905            final IPackageDataObserver observer, final int userId) {
14906        mContext.enforceCallingOrSelfPermission(
14907                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14908        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14909        // Queue up an async operation since the package deletion may take a little while.
14910        mHandler.post(new Runnable() {
14911            public void run() {
14912                mHandler.removeCallbacks(this);
14913                final boolean succeeded;
14914                synchronized (mInstallLock) {
14915                    succeeded = clearApplicationUserDataLI(packageName, userId);
14916                }
14917                clearExternalStorageDataSync(packageName, userId, true);
14918                if (succeeded) {
14919                    // invoke DeviceStorageMonitor's update method to clear any notifications
14920                    DeviceStorageMonitorInternal
14921                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14922                    if (dsm != null) {
14923                        dsm.checkMemory();
14924                    }
14925                }
14926                if(observer != null) {
14927                    try {
14928                        observer.onRemoveCompleted(packageName, succeeded);
14929                    } catch (RemoteException e) {
14930                        Log.i(TAG, "Observer no longer exists.");
14931                    }
14932                } //end if observer
14933            } //end run
14934        });
14935    }
14936
14937    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14938        if (packageName == null) {
14939            Slog.w(TAG, "Attempt to delete null packageName.");
14940            return false;
14941        }
14942
14943        // Try finding details about the requested package
14944        PackageParser.Package pkg;
14945        synchronized (mPackages) {
14946            pkg = mPackages.get(packageName);
14947            if (pkg == null) {
14948                final PackageSetting ps = mSettings.mPackages.get(packageName);
14949                if (ps != null) {
14950                    pkg = ps.pkg;
14951                }
14952            }
14953
14954            if (pkg == null) {
14955                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14956                return false;
14957            }
14958
14959            PackageSetting ps = (PackageSetting) pkg.mExtras;
14960            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14961        }
14962
14963        // Always delete data directories for package, even if we found no other
14964        // record of app. This helps users recover from UID mismatches without
14965        // resorting to a full data wipe.
14966        // TODO: triage flags as part of 26466827
14967        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14968        try {
14969            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14970        } catch (InstallerException e) {
14971            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14972            return false;
14973        }
14974
14975        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14976        removeKeystoreDataIfNeeded(userId, appId);
14977
14978        // Create a native library symlink only if we have native libraries
14979        // and if the native libraries are 32 bit libraries. We do not provide
14980        // this symlink for 64 bit libraries.
14981        if (pkg.applicationInfo.primaryCpuAbi != null &&
14982                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14983            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14984            try {
14985                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14986                        nativeLibPath, userId);
14987            } catch (InstallerException e) {
14988                Slog.w(TAG, "Failed linking native library dir", e);
14989                return false;
14990            }
14991        }
14992
14993        return true;
14994    }
14995
14996    /**
14997     * Reverts user permission state changes (permissions and flags) in
14998     * all packages for a given user.
14999     *
15000     * @param userId The device user for which to do a reset.
15001     */
15002    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15003        final int packageCount = mPackages.size();
15004        for (int i = 0; i < packageCount; i++) {
15005            PackageParser.Package pkg = mPackages.valueAt(i);
15006            PackageSetting ps = (PackageSetting) pkg.mExtras;
15007            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15008        }
15009    }
15010
15011    /**
15012     * Reverts user permission state changes (permissions and flags).
15013     *
15014     * @param ps The package for which to reset.
15015     * @param userId The device user for which to do a reset.
15016     */
15017    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15018            final PackageSetting ps, final int userId) {
15019        if (ps.pkg == null) {
15020            return;
15021        }
15022
15023        // These are flags that can change base on user actions.
15024        final int userSettableMask = FLAG_PERMISSION_USER_SET
15025                | FLAG_PERMISSION_USER_FIXED
15026                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15027                | FLAG_PERMISSION_REVIEW_REQUIRED;
15028
15029        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15030                | FLAG_PERMISSION_POLICY_FIXED;
15031
15032        boolean writeInstallPermissions = false;
15033        boolean writeRuntimePermissions = false;
15034
15035        final int permissionCount = ps.pkg.requestedPermissions.size();
15036        for (int i = 0; i < permissionCount; i++) {
15037            String permission = ps.pkg.requestedPermissions.get(i);
15038
15039            BasePermission bp = mSettings.mPermissions.get(permission);
15040            if (bp == null) {
15041                continue;
15042            }
15043
15044            // If shared user we just reset the state to which only this app contributed.
15045            if (ps.sharedUser != null) {
15046                boolean used = false;
15047                final int packageCount = ps.sharedUser.packages.size();
15048                for (int j = 0; j < packageCount; j++) {
15049                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15050                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15051                            && pkg.pkg.requestedPermissions.contains(permission)) {
15052                        used = true;
15053                        break;
15054                    }
15055                }
15056                if (used) {
15057                    continue;
15058                }
15059            }
15060
15061            PermissionsState permissionsState = ps.getPermissionsState();
15062
15063            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15064
15065            // Always clear the user settable flags.
15066            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15067                    bp.name) != null;
15068            // If permission review is enabled and this is a legacy app, mark the
15069            // permission as requiring a review as this is the initial state.
15070            int flags = 0;
15071            if (Build.PERMISSIONS_REVIEW_REQUIRED
15072                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15073                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15074            }
15075            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15076                if (hasInstallState) {
15077                    writeInstallPermissions = true;
15078                } else {
15079                    writeRuntimePermissions = true;
15080                }
15081            }
15082
15083            // Below is only runtime permission handling.
15084            if (!bp.isRuntime()) {
15085                continue;
15086            }
15087
15088            // Never clobber system or policy.
15089            if ((oldFlags & policyOrSystemFlags) != 0) {
15090                continue;
15091            }
15092
15093            // If this permission was granted by default, make sure it is.
15094            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15095                if (permissionsState.grantRuntimePermission(bp, userId)
15096                        != PERMISSION_OPERATION_FAILURE) {
15097                    writeRuntimePermissions = true;
15098                }
15099            // If permission review is enabled the permissions for a legacy apps
15100            // are represented as constantly granted runtime ones, so don't revoke.
15101            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15102                // Otherwise, reset the permission.
15103                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15104                switch (revokeResult) {
15105                    case PERMISSION_OPERATION_SUCCESS: {
15106                        writeRuntimePermissions = true;
15107                    } break;
15108
15109                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15110                        writeRuntimePermissions = true;
15111                        final int appId = ps.appId;
15112                        mHandler.post(new Runnable() {
15113                            @Override
15114                            public void run() {
15115                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15116                            }
15117                        });
15118                    } break;
15119                }
15120            }
15121        }
15122
15123        // Synchronously write as we are taking permissions away.
15124        if (writeRuntimePermissions) {
15125            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15126        }
15127
15128        // Synchronously write as we are taking permissions away.
15129        if (writeInstallPermissions) {
15130            mSettings.writeLPr();
15131        }
15132    }
15133
15134    /**
15135     * Remove entries from the keystore daemon. Will only remove it if the
15136     * {@code appId} is valid.
15137     */
15138    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15139        if (appId < 0) {
15140            return;
15141        }
15142
15143        final KeyStore keyStore = KeyStore.getInstance();
15144        if (keyStore != null) {
15145            if (userId == UserHandle.USER_ALL) {
15146                for (final int individual : sUserManager.getUserIds()) {
15147                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15148                }
15149            } else {
15150                keyStore.clearUid(UserHandle.getUid(userId, appId));
15151            }
15152        } else {
15153            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15154        }
15155    }
15156
15157    @Override
15158    public void deleteApplicationCacheFiles(final String packageName,
15159            final IPackageDataObserver observer) {
15160        mContext.enforceCallingOrSelfPermission(
15161                android.Manifest.permission.DELETE_CACHE_FILES, null);
15162        // Queue up an async operation since the package deletion may take a little while.
15163        final int userId = UserHandle.getCallingUserId();
15164        mHandler.post(new Runnable() {
15165            public void run() {
15166                mHandler.removeCallbacks(this);
15167                final boolean succeded;
15168                synchronized (mInstallLock) {
15169                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15170                }
15171                clearExternalStorageDataSync(packageName, userId, false);
15172                if (observer != null) {
15173                    try {
15174                        observer.onRemoveCompleted(packageName, succeded);
15175                    } catch (RemoteException e) {
15176                        Log.i(TAG, "Observer no longer exists.");
15177                    }
15178                } //end if observer
15179            } //end run
15180        });
15181    }
15182
15183    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15184        if (packageName == null) {
15185            Slog.w(TAG, "Attempt to delete null packageName.");
15186            return false;
15187        }
15188        PackageParser.Package p;
15189        synchronized (mPackages) {
15190            p = mPackages.get(packageName);
15191        }
15192        if (p == null) {
15193            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15194            return false;
15195        }
15196        final ApplicationInfo applicationInfo = p.applicationInfo;
15197        if (applicationInfo == null) {
15198            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15199            return false;
15200        }
15201        // TODO: triage flags as part of 26466827
15202        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15203        try {
15204            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15205                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15206        } catch (InstallerException e) {
15207            Slog.w(TAG, "Couldn't remove cache files for package "
15208                    + packageName + " u" + userId, e);
15209            return false;
15210        }
15211        return true;
15212    }
15213
15214    @Override
15215    public void getPackageSizeInfo(final String packageName, int userHandle,
15216            final IPackageStatsObserver observer) {
15217        mContext.enforceCallingOrSelfPermission(
15218                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15219        if (packageName == null) {
15220            throw new IllegalArgumentException("Attempt to get size of null packageName");
15221        }
15222
15223        PackageStats stats = new PackageStats(packageName, userHandle);
15224
15225        /*
15226         * Queue up an async operation since the package measurement may take a
15227         * little while.
15228         */
15229        Message msg = mHandler.obtainMessage(INIT_COPY);
15230        msg.obj = new MeasureParams(stats, observer);
15231        mHandler.sendMessage(msg);
15232    }
15233
15234    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15235            PackageStats pStats) {
15236        if (packageName == null) {
15237            Slog.w(TAG, "Attempt to get size of null packageName.");
15238            return false;
15239        }
15240        PackageParser.Package p;
15241        boolean dataOnly = false;
15242        String libDirRoot = null;
15243        String asecPath = null;
15244        PackageSetting ps = null;
15245        synchronized (mPackages) {
15246            p = mPackages.get(packageName);
15247            ps = mSettings.mPackages.get(packageName);
15248            if(p == null) {
15249                dataOnly = true;
15250                if((ps == null) || (ps.pkg == null)) {
15251                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15252                    return false;
15253                }
15254                p = ps.pkg;
15255            }
15256            if (ps != null) {
15257                libDirRoot = ps.legacyNativeLibraryPathString;
15258            }
15259            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15260                final long token = Binder.clearCallingIdentity();
15261                try {
15262                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15263                    if (secureContainerId != null) {
15264                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15265                    }
15266                } finally {
15267                    Binder.restoreCallingIdentity(token);
15268                }
15269            }
15270        }
15271        String publicSrcDir = null;
15272        if(!dataOnly) {
15273            final ApplicationInfo applicationInfo = p.applicationInfo;
15274            if (applicationInfo == null) {
15275                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15276                return false;
15277            }
15278            if (p.isForwardLocked()) {
15279                publicSrcDir = applicationInfo.getBaseResourcePath();
15280            }
15281        }
15282        // TODO: extend to measure size of split APKs
15283        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15284        // not just the first level.
15285        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15286        // just the primary.
15287        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15288
15289        String apkPath;
15290        File packageDir = new File(p.codePath);
15291
15292        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15293            apkPath = packageDir.getAbsolutePath();
15294            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15295            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15296                libDirRoot = null;
15297            }
15298        } else {
15299            apkPath = p.baseCodePath;
15300        }
15301
15302        // TODO: triage flags as part of 26466827
15303        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15304        try {
15305            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15306                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15307        } catch (InstallerException e) {
15308            return false;
15309        }
15310
15311        // Fix-up for forward-locked applications in ASEC containers.
15312        if (!isExternal(p)) {
15313            pStats.codeSize += pStats.externalCodeSize;
15314            pStats.externalCodeSize = 0L;
15315        }
15316
15317        return true;
15318    }
15319
15320
15321    @Override
15322    public void addPackageToPreferred(String packageName) {
15323        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15324    }
15325
15326    @Override
15327    public void removePackageFromPreferred(String packageName) {
15328        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15329    }
15330
15331    @Override
15332    public List<PackageInfo> getPreferredPackages(int flags) {
15333        return new ArrayList<PackageInfo>();
15334    }
15335
15336    private int getUidTargetSdkVersionLockedLPr(int uid) {
15337        Object obj = mSettings.getUserIdLPr(uid);
15338        if (obj instanceof SharedUserSetting) {
15339            final SharedUserSetting sus = (SharedUserSetting) obj;
15340            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15341            final Iterator<PackageSetting> it = sus.packages.iterator();
15342            while (it.hasNext()) {
15343                final PackageSetting ps = it.next();
15344                if (ps.pkg != null) {
15345                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15346                    if (v < vers) vers = v;
15347                }
15348            }
15349            return vers;
15350        } else if (obj instanceof PackageSetting) {
15351            final PackageSetting ps = (PackageSetting) obj;
15352            if (ps.pkg != null) {
15353                return ps.pkg.applicationInfo.targetSdkVersion;
15354            }
15355        }
15356        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15357    }
15358
15359    @Override
15360    public void addPreferredActivity(IntentFilter filter, int match,
15361            ComponentName[] set, ComponentName activity, int userId) {
15362        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15363                "Adding preferred");
15364    }
15365
15366    private void addPreferredActivityInternal(IntentFilter filter, int match,
15367            ComponentName[] set, ComponentName activity, boolean always, int userId,
15368            String opname) {
15369        // writer
15370        int callingUid = Binder.getCallingUid();
15371        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15372        if (filter.countActions() == 0) {
15373            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15374            return;
15375        }
15376        synchronized (mPackages) {
15377            if (mContext.checkCallingOrSelfPermission(
15378                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15379                    != PackageManager.PERMISSION_GRANTED) {
15380                if (getUidTargetSdkVersionLockedLPr(callingUid)
15381                        < Build.VERSION_CODES.FROYO) {
15382                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15383                            + callingUid);
15384                    return;
15385                }
15386                mContext.enforceCallingOrSelfPermission(
15387                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15388            }
15389
15390            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15391            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15392                    + userId + ":");
15393            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15394            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15395            scheduleWritePackageRestrictionsLocked(userId);
15396        }
15397    }
15398
15399    @Override
15400    public void replacePreferredActivity(IntentFilter filter, int match,
15401            ComponentName[] set, ComponentName activity, int userId) {
15402        if (filter.countActions() != 1) {
15403            throw new IllegalArgumentException(
15404                    "replacePreferredActivity expects filter to have only 1 action.");
15405        }
15406        if (filter.countDataAuthorities() != 0
15407                || filter.countDataPaths() != 0
15408                || filter.countDataSchemes() > 1
15409                || filter.countDataTypes() != 0) {
15410            throw new IllegalArgumentException(
15411                    "replacePreferredActivity expects filter to have no data authorities, " +
15412                    "paths, or types; and at most one scheme.");
15413        }
15414
15415        final int callingUid = Binder.getCallingUid();
15416        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15417        synchronized (mPackages) {
15418            if (mContext.checkCallingOrSelfPermission(
15419                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15420                    != PackageManager.PERMISSION_GRANTED) {
15421                if (getUidTargetSdkVersionLockedLPr(callingUid)
15422                        < Build.VERSION_CODES.FROYO) {
15423                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15424                            + Binder.getCallingUid());
15425                    return;
15426                }
15427                mContext.enforceCallingOrSelfPermission(
15428                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15429            }
15430
15431            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15432            if (pir != null) {
15433                // Get all of the existing entries that exactly match this filter.
15434                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15435                if (existing != null && existing.size() == 1) {
15436                    PreferredActivity cur = existing.get(0);
15437                    if (DEBUG_PREFERRED) {
15438                        Slog.i(TAG, "Checking replace of preferred:");
15439                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15440                        if (!cur.mPref.mAlways) {
15441                            Slog.i(TAG, "  -- CUR; not mAlways!");
15442                        } else {
15443                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15444                            Slog.i(TAG, "  -- CUR: mSet="
15445                                    + Arrays.toString(cur.mPref.mSetComponents));
15446                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15447                            Slog.i(TAG, "  -- NEW: mMatch="
15448                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15449                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15450                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15451                        }
15452                    }
15453                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15454                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15455                            && cur.mPref.sameSet(set)) {
15456                        // Setting the preferred activity to what it happens to be already
15457                        if (DEBUG_PREFERRED) {
15458                            Slog.i(TAG, "Replacing with same preferred activity "
15459                                    + cur.mPref.mShortComponent + " for user "
15460                                    + userId + ":");
15461                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15462                        }
15463                        return;
15464                    }
15465                }
15466
15467                if (existing != null) {
15468                    if (DEBUG_PREFERRED) {
15469                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15470                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15471                    }
15472                    for (int i = 0; i < existing.size(); i++) {
15473                        PreferredActivity pa = existing.get(i);
15474                        if (DEBUG_PREFERRED) {
15475                            Slog.i(TAG, "Removing existing preferred activity "
15476                                    + pa.mPref.mComponent + ":");
15477                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15478                        }
15479                        pir.removeFilter(pa);
15480                    }
15481                }
15482            }
15483            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15484                    "Replacing preferred");
15485        }
15486    }
15487
15488    @Override
15489    public void clearPackagePreferredActivities(String packageName) {
15490        final int uid = Binder.getCallingUid();
15491        // writer
15492        synchronized (mPackages) {
15493            PackageParser.Package pkg = mPackages.get(packageName);
15494            if (pkg == null || pkg.applicationInfo.uid != uid) {
15495                if (mContext.checkCallingOrSelfPermission(
15496                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15497                        != PackageManager.PERMISSION_GRANTED) {
15498                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15499                            < Build.VERSION_CODES.FROYO) {
15500                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15501                                + Binder.getCallingUid());
15502                        return;
15503                    }
15504                    mContext.enforceCallingOrSelfPermission(
15505                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15506                }
15507            }
15508
15509            int user = UserHandle.getCallingUserId();
15510            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15511                scheduleWritePackageRestrictionsLocked(user);
15512            }
15513        }
15514    }
15515
15516    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15517    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15518        ArrayList<PreferredActivity> removed = null;
15519        boolean changed = false;
15520        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15521            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15522            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15523            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15524                continue;
15525            }
15526            Iterator<PreferredActivity> it = pir.filterIterator();
15527            while (it.hasNext()) {
15528                PreferredActivity pa = it.next();
15529                // Mark entry for removal only if it matches the package name
15530                // and the entry is of type "always".
15531                if (packageName == null ||
15532                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15533                                && pa.mPref.mAlways)) {
15534                    if (removed == null) {
15535                        removed = new ArrayList<PreferredActivity>();
15536                    }
15537                    removed.add(pa);
15538                }
15539            }
15540            if (removed != null) {
15541                for (int j=0; j<removed.size(); j++) {
15542                    PreferredActivity pa = removed.get(j);
15543                    pir.removeFilter(pa);
15544                }
15545                changed = true;
15546            }
15547        }
15548        return changed;
15549    }
15550
15551    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15552    private void clearIntentFilterVerificationsLPw(int userId) {
15553        final int packageCount = mPackages.size();
15554        for (int i = 0; i < packageCount; i++) {
15555            PackageParser.Package pkg = mPackages.valueAt(i);
15556            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15557        }
15558    }
15559
15560    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15561    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15562        if (userId == UserHandle.USER_ALL) {
15563            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15564                    sUserManager.getUserIds())) {
15565                for (int oneUserId : sUserManager.getUserIds()) {
15566                    scheduleWritePackageRestrictionsLocked(oneUserId);
15567                }
15568            }
15569        } else {
15570            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15571                scheduleWritePackageRestrictionsLocked(userId);
15572            }
15573        }
15574    }
15575
15576    void clearDefaultBrowserIfNeeded(String packageName) {
15577        for (int oneUserId : sUserManager.getUserIds()) {
15578            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15579            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15580            if (packageName.equals(defaultBrowserPackageName)) {
15581                setDefaultBrowserPackageName(null, oneUserId);
15582            }
15583        }
15584    }
15585
15586    @Override
15587    public void resetApplicationPreferences(int userId) {
15588        mContext.enforceCallingOrSelfPermission(
15589                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15590        // writer
15591        synchronized (mPackages) {
15592            final long identity = Binder.clearCallingIdentity();
15593            try {
15594                clearPackagePreferredActivitiesLPw(null, userId);
15595                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15596                // TODO: We have to reset the default SMS and Phone. This requires
15597                // significant refactoring to keep all default apps in the package
15598                // manager (cleaner but more work) or have the services provide
15599                // callbacks to the package manager to request a default app reset.
15600                applyFactoryDefaultBrowserLPw(userId);
15601                clearIntentFilterVerificationsLPw(userId);
15602                primeDomainVerificationsLPw(userId);
15603                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15604                scheduleWritePackageRestrictionsLocked(userId);
15605            } finally {
15606                Binder.restoreCallingIdentity(identity);
15607            }
15608        }
15609    }
15610
15611    @Override
15612    public int getPreferredActivities(List<IntentFilter> outFilters,
15613            List<ComponentName> outActivities, String packageName) {
15614
15615        int num = 0;
15616        final int userId = UserHandle.getCallingUserId();
15617        // reader
15618        synchronized (mPackages) {
15619            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15620            if (pir != null) {
15621                final Iterator<PreferredActivity> it = pir.filterIterator();
15622                while (it.hasNext()) {
15623                    final PreferredActivity pa = it.next();
15624                    if (packageName == null
15625                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15626                                    && pa.mPref.mAlways)) {
15627                        if (outFilters != null) {
15628                            outFilters.add(new IntentFilter(pa));
15629                        }
15630                        if (outActivities != null) {
15631                            outActivities.add(pa.mPref.mComponent);
15632                        }
15633                    }
15634                }
15635            }
15636        }
15637
15638        return num;
15639    }
15640
15641    @Override
15642    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15643            int userId) {
15644        int callingUid = Binder.getCallingUid();
15645        if (callingUid != Process.SYSTEM_UID) {
15646            throw new SecurityException(
15647                    "addPersistentPreferredActivity can only be run by the system");
15648        }
15649        if (filter.countActions() == 0) {
15650            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15651            return;
15652        }
15653        synchronized (mPackages) {
15654            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15655                    ":");
15656            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15657            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15658                    new PersistentPreferredActivity(filter, activity));
15659            scheduleWritePackageRestrictionsLocked(userId);
15660        }
15661    }
15662
15663    @Override
15664    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15665        int callingUid = Binder.getCallingUid();
15666        if (callingUid != Process.SYSTEM_UID) {
15667            throw new SecurityException(
15668                    "clearPackagePersistentPreferredActivities can only be run by the system");
15669        }
15670        ArrayList<PersistentPreferredActivity> removed = null;
15671        boolean changed = false;
15672        synchronized (mPackages) {
15673            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15674                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15675                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15676                        .valueAt(i);
15677                if (userId != thisUserId) {
15678                    continue;
15679                }
15680                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15681                while (it.hasNext()) {
15682                    PersistentPreferredActivity ppa = it.next();
15683                    // Mark entry for removal only if it matches the package name.
15684                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15685                        if (removed == null) {
15686                            removed = new ArrayList<PersistentPreferredActivity>();
15687                        }
15688                        removed.add(ppa);
15689                    }
15690                }
15691                if (removed != null) {
15692                    for (int j=0; j<removed.size(); j++) {
15693                        PersistentPreferredActivity ppa = removed.get(j);
15694                        ppir.removeFilter(ppa);
15695                    }
15696                    changed = true;
15697                }
15698            }
15699
15700            if (changed) {
15701                scheduleWritePackageRestrictionsLocked(userId);
15702            }
15703        }
15704    }
15705
15706    /**
15707     * Common machinery for picking apart a restored XML blob and passing
15708     * it to a caller-supplied functor to be applied to the running system.
15709     */
15710    private void restoreFromXml(XmlPullParser parser, int userId,
15711            String expectedStartTag, BlobXmlRestorer functor)
15712            throws IOException, XmlPullParserException {
15713        int type;
15714        while ((type = parser.next()) != XmlPullParser.START_TAG
15715                && type != XmlPullParser.END_DOCUMENT) {
15716        }
15717        if (type != XmlPullParser.START_TAG) {
15718            // oops didn't find a start tag?!
15719            if (DEBUG_BACKUP) {
15720                Slog.e(TAG, "Didn't find start tag during restore");
15721            }
15722            return;
15723        }
15724Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15725        // this is supposed to be TAG_PREFERRED_BACKUP
15726        if (!expectedStartTag.equals(parser.getName())) {
15727            if (DEBUG_BACKUP) {
15728                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15729            }
15730            return;
15731        }
15732
15733        // skip interfering stuff, then we're aligned with the backing implementation
15734        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15735Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15736        functor.apply(parser, userId);
15737    }
15738
15739    private interface BlobXmlRestorer {
15740        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15741    }
15742
15743    /**
15744     * Non-Binder method, support for the backup/restore mechanism: write the
15745     * full set of preferred activities in its canonical XML format.  Returns the
15746     * XML output as a byte array, or null if there is none.
15747     */
15748    @Override
15749    public byte[] getPreferredActivityBackup(int userId) {
15750        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15751            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15752        }
15753
15754        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15755        try {
15756            final XmlSerializer serializer = new FastXmlSerializer();
15757            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15758            serializer.startDocument(null, true);
15759            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15760
15761            synchronized (mPackages) {
15762                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15763            }
15764
15765            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15766            serializer.endDocument();
15767            serializer.flush();
15768        } catch (Exception e) {
15769            if (DEBUG_BACKUP) {
15770                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15771            }
15772            return null;
15773        }
15774
15775        return dataStream.toByteArray();
15776    }
15777
15778    @Override
15779    public void restorePreferredActivities(byte[] backup, int userId) {
15780        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15781            throw new SecurityException("Only the system may call restorePreferredActivities()");
15782        }
15783
15784        try {
15785            final XmlPullParser parser = Xml.newPullParser();
15786            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15787            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15788                    new BlobXmlRestorer() {
15789                        @Override
15790                        public void apply(XmlPullParser parser, int userId)
15791                                throws XmlPullParserException, IOException {
15792                            synchronized (mPackages) {
15793                                mSettings.readPreferredActivitiesLPw(parser, userId);
15794                            }
15795                        }
15796                    } );
15797        } catch (Exception e) {
15798            if (DEBUG_BACKUP) {
15799                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15800            }
15801        }
15802    }
15803
15804    /**
15805     * Non-Binder method, support for the backup/restore mechanism: write the
15806     * default browser (etc) settings in its canonical XML format.  Returns the default
15807     * browser XML representation as a byte array, or null if there is none.
15808     */
15809    @Override
15810    public byte[] getDefaultAppsBackup(int userId) {
15811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15812            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15813        }
15814
15815        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15816        try {
15817            final XmlSerializer serializer = new FastXmlSerializer();
15818            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15819            serializer.startDocument(null, true);
15820            serializer.startTag(null, TAG_DEFAULT_APPS);
15821
15822            synchronized (mPackages) {
15823                mSettings.writeDefaultAppsLPr(serializer, userId);
15824            }
15825
15826            serializer.endTag(null, TAG_DEFAULT_APPS);
15827            serializer.endDocument();
15828            serializer.flush();
15829        } catch (Exception e) {
15830            if (DEBUG_BACKUP) {
15831                Slog.e(TAG, "Unable to write default apps for backup", e);
15832            }
15833            return null;
15834        }
15835
15836        return dataStream.toByteArray();
15837    }
15838
15839    @Override
15840    public void restoreDefaultApps(byte[] backup, int userId) {
15841        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15842            throw new SecurityException("Only the system may call restoreDefaultApps()");
15843        }
15844
15845        try {
15846            final XmlPullParser parser = Xml.newPullParser();
15847            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15848            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15849                    new BlobXmlRestorer() {
15850                        @Override
15851                        public void apply(XmlPullParser parser, int userId)
15852                                throws XmlPullParserException, IOException {
15853                            synchronized (mPackages) {
15854                                mSettings.readDefaultAppsLPw(parser, userId);
15855                            }
15856                        }
15857                    } );
15858        } catch (Exception e) {
15859            if (DEBUG_BACKUP) {
15860                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15861            }
15862        }
15863    }
15864
15865    @Override
15866    public byte[] getIntentFilterVerificationBackup(int userId) {
15867        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15868            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15869        }
15870
15871        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15872        try {
15873            final XmlSerializer serializer = new FastXmlSerializer();
15874            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15875            serializer.startDocument(null, true);
15876            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15877
15878            synchronized (mPackages) {
15879                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15880            }
15881
15882            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15883            serializer.endDocument();
15884            serializer.flush();
15885        } catch (Exception e) {
15886            if (DEBUG_BACKUP) {
15887                Slog.e(TAG, "Unable to write default apps for backup", e);
15888            }
15889            return null;
15890        }
15891
15892        return dataStream.toByteArray();
15893    }
15894
15895    @Override
15896    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15897        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15898            throw new SecurityException("Only the system may call restorePreferredActivities()");
15899        }
15900
15901        try {
15902            final XmlPullParser parser = Xml.newPullParser();
15903            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15904            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15905                    new BlobXmlRestorer() {
15906                        @Override
15907                        public void apply(XmlPullParser parser, int userId)
15908                                throws XmlPullParserException, IOException {
15909                            synchronized (mPackages) {
15910                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15911                                mSettings.writeLPr();
15912                            }
15913                        }
15914                    } );
15915        } catch (Exception e) {
15916            if (DEBUG_BACKUP) {
15917                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15918            }
15919        }
15920    }
15921
15922    @Override
15923    public byte[] getPermissionGrantBackup(int userId) {
15924        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15925            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15926        }
15927
15928        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15929        try {
15930            final XmlSerializer serializer = new FastXmlSerializer();
15931            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15932            serializer.startDocument(null, true);
15933            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15934
15935            synchronized (mPackages) {
15936                serializeRuntimePermissionGrantsLPr(serializer, userId);
15937            }
15938
15939            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15940            serializer.endDocument();
15941            serializer.flush();
15942        } catch (Exception e) {
15943            if (DEBUG_BACKUP) {
15944                Slog.e(TAG, "Unable to write default apps for backup", e);
15945            }
15946            return null;
15947        }
15948
15949        return dataStream.toByteArray();
15950    }
15951
15952    @Override
15953    public void restorePermissionGrants(byte[] backup, int userId) {
15954        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15955            throw new SecurityException("Only the system may call restorePermissionGrants()");
15956        }
15957
15958        try {
15959            final XmlPullParser parser = Xml.newPullParser();
15960            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15961            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15962                    new BlobXmlRestorer() {
15963                        @Override
15964                        public void apply(XmlPullParser parser, int userId)
15965                                throws XmlPullParserException, IOException {
15966                            synchronized (mPackages) {
15967                                processRestoredPermissionGrantsLPr(parser, userId);
15968                            }
15969                        }
15970                    } );
15971        } catch (Exception e) {
15972            if (DEBUG_BACKUP) {
15973                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15974            }
15975        }
15976    }
15977
15978    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15979            throws IOException {
15980        serializer.startTag(null, TAG_ALL_GRANTS);
15981
15982        final int N = mSettings.mPackages.size();
15983        for (int i = 0; i < N; i++) {
15984            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15985            boolean pkgGrantsKnown = false;
15986
15987            PermissionsState packagePerms = ps.getPermissionsState();
15988
15989            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15990                final int grantFlags = state.getFlags();
15991                // only look at grants that are not system/policy fixed
15992                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15993                    final boolean isGranted = state.isGranted();
15994                    // And only back up the user-twiddled state bits
15995                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15996                        final String packageName = mSettings.mPackages.keyAt(i);
15997                        if (!pkgGrantsKnown) {
15998                            serializer.startTag(null, TAG_GRANT);
15999                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16000                            pkgGrantsKnown = true;
16001                        }
16002
16003                        final boolean userSet =
16004                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16005                        final boolean userFixed =
16006                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16007                        final boolean revoke =
16008                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16009
16010                        serializer.startTag(null, TAG_PERMISSION);
16011                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16012                        if (isGranted) {
16013                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16014                        }
16015                        if (userSet) {
16016                            serializer.attribute(null, ATTR_USER_SET, "true");
16017                        }
16018                        if (userFixed) {
16019                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16020                        }
16021                        if (revoke) {
16022                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16023                        }
16024                        serializer.endTag(null, TAG_PERMISSION);
16025                    }
16026                }
16027            }
16028
16029            if (pkgGrantsKnown) {
16030                serializer.endTag(null, TAG_GRANT);
16031            }
16032        }
16033
16034        serializer.endTag(null, TAG_ALL_GRANTS);
16035    }
16036
16037    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16038            throws XmlPullParserException, IOException {
16039        String pkgName = null;
16040        int outerDepth = parser.getDepth();
16041        int type;
16042        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16043                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16044            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16045                continue;
16046            }
16047
16048            final String tagName = parser.getName();
16049            if (tagName.equals(TAG_GRANT)) {
16050                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16051                if (DEBUG_BACKUP) {
16052                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16053                }
16054            } else if (tagName.equals(TAG_PERMISSION)) {
16055
16056                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16057                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16058
16059                int newFlagSet = 0;
16060                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16061                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16062                }
16063                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16064                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16065                }
16066                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16067                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16068                }
16069                if (DEBUG_BACKUP) {
16070                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16071                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16072                }
16073                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16074                if (ps != null) {
16075                    // Already installed so we apply the grant immediately
16076                    if (DEBUG_BACKUP) {
16077                        Slog.v(TAG, "        + already installed; applying");
16078                    }
16079                    PermissionsState perms = ps.getPermissionsState();
16080                    BasePermission bp = mSettings.mPermissions.get(permName);
16081                    if (bp != null) {
16082                        if (isGranted) {
16083                            perms.grantRuntimePermission(bp, userId);
16084                        }
16085                        if (newFlagSet != 0) {
16086                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16087                        }
16088                    }
16089                } else {
16090                    // Need to wait for post-restore install to apply the grant
16091                    if (DEBUG_BACKUP) {
16092                        Slog.v(TAG, "        - not yet installed; saving for later");
16093                    }
16094                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16095                            isGranted, newFlagSet, userId);
16096                }
16097            } else {
16098                PackageManagerService.reportSettingsProblem(Log.WARN,
16099                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16100                XmlUtils.skipCurrentTag(parser);
16101            }
16102        }
16103
16104        scheduleWriteSettingsLocked();
16105        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16106    }
16107
16108    @Override
16109    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16110            int sourceUserId, int targetUserId, int flags) {
16111        mContext.enforceCallingOrSelfPermission(
16112                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16113        int callingUid = Binder.getCallingUid();
16114        enforceOwnerRights(ownerPackage, callingUid);
16115        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16116        if (intentFilter.countActions() == 0) {
16117            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16118            return;
16119        }
16120        synchronized (mPackages) {
16121            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16122                    ownerPackage, targetUserId, flags);
16123            CrossProfileIntentResolver resolver =
16124                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16125            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16126            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16127            if (existing != null) {
16128                int size = existing.size();
16129                for (int i = 0; i < size; i++) {
16130                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16131                        return;
16132                    }
16133                }
16134            }
16135            resolver.addFilter(newFilter);
16136            scheduleWritePackageRestrictionsLocked(sourceUserId);
16137        }
16138    }
16139
16140    @Override
16141    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16142        mContext.enforceCallingOrSelfPermission(
16143                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16144        int callingUid = Binder.getCallingUid();
16145        enforceOwnerRights(ownerPackage, callingUid);
16146        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16147        synchronized (mPackages) {
16148            CrossProfileIntentResolver resolver =
16149                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16150            ArraySet<CrossProfileIntentFilter> set =
16151                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16152            for (CrossProfileIntentFilter filter : set) {
16153                if (filter.getOwnerPackage().equals(ownerPackage)) {
16154                    resolver.removeFilter(filter);
16155                }
16156            }
16157            scheduleWritePackageRestrictionsLocked(sourceUserId);
16158        }
16159    }
16160
16161    // Enforcing that callingUid is owning pkg on userId
16162    private void enforceOwnerRights(String pkg, int callingUid) {
16163        // The system owns everything.
16164        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16165            return;
16166        }
16167        int callingUserId = UserHandle.getUserId(callingUid);
16168        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16169        if (pi == null) {
16170            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16171                    + callingUserId);
16172        }
16173        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16174            throw new SecurityException("Calling uid " + callingUid
16175                    + " does not own package " + pkg);
16176        }
16177    }
16178
16179    @Override
16180    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16181        Intent intent = new Intent(Intent.ACTION_MAIN);
16182        intent.addCategory(Intent.CATEGORY_HOME);
16183
16184        final int callingUserId = UserHandle.getCallingUserId();
16185        List<ResolveInfo> list = queryIntentActivities(intent, null,
16186                PackageManager.GET_META_DATA, callingUserId);
16187        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16188                true, false, false, callingUserId);
16189
16190        allHomeCandidates.clear();
16191        if (list != null) {
16192            for (ResolveInfo ri : list) {
16193                allHomeCandidates.add(ri);
16194            }
16195        }
16196        return (preferred == null || preferred.activityInfo == null)
16197                ? null
16198                : new ComponentName(preferred.activityInfo.packageName,
16199                        preferred.activityInfo.name);
16200    }
16201
16202    @Override
16203    public void setApplicationEnabledSetting(String appPackageName,
16204            int newState, int flags, int userId, String callingPackage) {
16205        if (!sUserManager.exists(userId)) return;
16206        if (callingPackage == null) {
16207            callingPackage = Integer.toString(Binder.getCallingUid());
16208        }
16209        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16210    }
16211
16212    @Override
16213    public void setComponentEnabledSetting(ComponentName componentName,
16214            int newState, int flags, int userId) {
16215        if (!sUserManager.exists(userId)) return;
16216        setEnabledSetting(componentName.getPackageName(),
16217                componentName.getClassName(), newState, flags, userId, null);
16218    }
16219
16220    private void setEnabledSetting(final String packageName, String className, int newState,
16221            final int flags, int userId, String callingPackage) {
16222        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16223              || newState == COMPONENT_ENABLED_STATE_ENABLED
16224              || newState == COMPONENT_ENABLED_STATE_DISABLED
16225              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16226              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16227            throw new IllegalArgumentException("Invalid new component state: "
16228                    + newState);
16229        }
16230        PackageSetting pkgSetting;
16231        final int uid = Binder.getCallingUid();
16232        final int permission = mContext.checkCallingOrSelfPermission(
16233                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16234        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
16235        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16236        boolean sendNow = false;
16237        boolean isApp = (className == null);
16238        String componentName = isApp ? packageName : className;
16239        int packageUid = -1;
16240        ArrayList<String> components;
16241
16242        // writer
16243        synchronized (mPackages) {
16244            pkgSetting = mSettings.mPackages.get(packageName);
16245            if (pkgSetting == null) {
16246                if (className == null) {
16247                    throw new IllegalArgumentException("Unknown package: " + packageName);
16248                }
16249                throw new IllegalArgumentException(
16250                        "Unknown component: " + packageName + "/" + className);
16251            }
16252            // Allow root and verify that userId is not being specified by a different user
16253            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16254                throw new SecurityException(
16255                        "Permission Denial: attempt to change component state from pid="
16256                        + Binder.getCallingPid()
16257                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16258            }
16259            if (className == null) {
16260                // We're dealing with an application/package level state change
16261                if (pkgSetting.getEnabled(userId) == newState) {
16262                    // Nothing to do
16263                    return;
16264                }
16265                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16266                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16267                    // Don't care about who enables an app.
16268                    callingPackage = null;
16269                }
16270                pkgSetting.setEnabled(newState, userId, callingPackage);
16271                // pkgSetting.pkg.mSetEnabled = newState;
16272            } else {
16273                // We're dealing with a component level state change
16274                // First, verify that this is a valid class name.
16275                PackageParser.Package pkg = pkgSetting.pkg;
16276                if (pkg == null || !pkg.hasComponentClassName(className)) {
16277                    if (pkg != null &&
16278                            pkg.applicationInfo.targetSdkVersion >=
16279                                    Build.VERSION_CODES.JELLY_BEAN) {
16280                        throw new IllegalArgumentException("Component class " + className
16281                                + " does not exist in " + packageName);
16282                    } else {
16283                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16284                                + className + " does not exist in " + packageName);
16285                    }
16286                }
16287                switch (newState) {
16288                case COMPONENT_ENABLED_STATE_ENABLED:
16289                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16290                        return;
16291                    }
16292                    break;
16293                case COMPONENT_ENABLED_STATE_DISABLED:
16294                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16295                        return;
16296                    }
16297                    break;
16298                case COMPONENT_ENABLED_STATE_DEFAULT:
16299                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16300                        return;
16301                    }
16302                    break;
16303                default:
16304                    Slog.e(TAG, "Invalid new component state: " + newState);
16305                    return;
16306                }
16307            }
16308            scheduleWritePackageRestrictionsLocked(userId);
16309            components = mPendingBroadcasts.get(userId, packageName);
16310            final boolean newPackage = components == null;
16311            if (newPackage) {
16312                components = new ArrayList<String>();
16313            }
16314            if (!components.contains(componentName)) {
16315                components.add(componentName);
16316            }
16317            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16318                sendNow = true;
16319                // Purge entry from pending broadcast list if another one exists already
16320                // since we are sending one right away.
16321                mPendingBroadcasts.remove(userId, packageName);
16322            } else {
16323                if (newPackage) {
16324                    mPendingBroadcasts.put(userId, packageName, components);
16325                }
16326                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16327                    // Schedule a message
16328                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16329                }
16330            }
16331        }
16332
16333        long callingId = Binder.clearCallingIdentity();
16334        try {
16335            if (sendNow) {
16336                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16337                sendPackageChangedBroadcast(packageName,
16338                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16339            }
16340        } finally {
16341            Binder.restoreCallingIdentity(callingId);
16342        }
16343    }
16344
16345    private void sendPackageChangedBroadcast(String packageName,
16346            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16347        if (DEBUG_INSTALL)
16348            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16349                    + componentNames);
16350        Bundle extras = new Bundle(4);
16351        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16352        String nameList[] = new String[componentNames.size()];
16353        componentNames.toArray(nameList);
16354        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16355        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16356        extras.putInt(Intent.EXTRA_UID, packageUid);
16357        // If this is not reporting a change of the overall package, then only send it
16358        // to registered receivers.  We don't want to launch a swath of apps for every
16359        // little component state change.
16360        final int flags = !componentNames.contains(packageName)
16361                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16362        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16363                new int[] {UserHandle.getUserId(packageUid)});
16364    }
16365
16366    @Override
16367    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16368        if (!sUserManager.exists(userId)) return;
16369        final int uid = Binder.getCallingUid();
16370        final int permission = mContext.checkCallingOrSelfPermission(
16371                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16372        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16373        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16374        // writer
16375        synchronized (mPackages) {
16376            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16377                    allowedByPermission, uid, userId)) {
16378                scheduleWritePackageRestrictionsLocked(userId);
16379            }
16380        }
16381    }
16382
16383    @Override
16384    public String getInstallerPackageName(String packageName) {
16385        // reader
16386        synchronized (mPackages) {
16387            return mSettings.getInstallerPackageNameLPr(packageName);
16388        }
16389    }
16390
16391    @Override
16392    public int getApplicationEnabledSetting(String packageName, int userId) {
16393        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16394        int uid = Binder.getCallingUid();
16395        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16396        // reader
16397        synchronized (mPackages) {
16398            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16399        }
16400    }
16401
16402    @Override
16403    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16404        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16405        int uid = Binder.getCallingUid();
16406        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16407        // reader
16408        synchronized (mPackages) {
16409            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16410        }
16411    }
16412
16413    @Override
16414    public void enterSafeMode() {
16415        enforceSystemOrRoot("Only the system can request entering safe mode");
16416
16417        if (!mSystemReady) {
16418            mSafeMode = true;
16419        }
16420    }
16421
16422    @Override
16423    public void systemReady() {
16424        mSystemReady = true;
16425
16426        // Read the compatibilty setting when the system is ready.
16427        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16428                mContext.getContentResolver(),
16429                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16430        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16431        if (DEBUG_SETTINGS) {
16432            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16433        }
16434
16435        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16436
16437        synchronized (mPackages) {
16438            // Verify that all of the preferred activity components actually
16439            // exist.  It is possible for applications to be updated and at
16440            // that point remove a previously declared activity component that
16441            // had been set as a preferred activity.  We try to clean this up
16442            // the next time we encounter that preferred activity, but it is
16443            // possible for the user flow to never be able to return to that
16444            // situation so here we do a sanity check to make sure we haven't
16445            // left any junk around.
16446            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16447            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16448                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16449                removed.clear();
16450                for (PreferredActivity pa : pir.filterSet()) {
16451                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16452                        removed.add(pa);
16453                    }
16454                }
16455                if (removed.size() > 0) {
16456                    for (int r=0; r<removed.size(); r++) {
16457                        PreferredActivity pa = removed.get(r);
16458                        Slog.w(TAG, "Removing dangling preferred activity: "
16459                                + pa.mPref.mComponent);
16460                        pir.removeFilter(pa);
16461                    }
16462                    mSettings.writePackageRestrictionsLPr(
16463                            mSettings.mPreferredActivities.keyAt(i));
16464                }
16465            }
16466
16467            for (int userId : UserManagerService.getInstance().getUserIds()) {
16468                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16469                    grantPermissionsUserIds = ArrayUtils.appendInt(
16470                            grantPermissionsUserIds, userId);
16471                }
16472            }
16473        }
16474        sUserManager.systemReady();
16475
16476        // If we upgraded grant all default permissions before kicking off.
16477        for (int userId : grantPermissionsUserIds) {
16478            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16479        }
16480
16481        // Kick off any messages waiting for system ready
16482        if (mPostSystemReadyMessages != null) {
16483            for (Message msg : mPostSystemReadyMessages) {
16484                msg.sendToTarget();
16485            }
16486            mPostSystemReadyMessages = null;
16487        }
16488
16489        // Watch for external volumes that come and go over time
16490        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16491        storage.registerListener(mStorageListener);
16492
16493        mInstallerService.systemReady();
16494        mPackageDexOptimizer.systemReady();
16495
16496        MountServiceInternal mountServiceInternal = LocalServices.getService(
16497                MountServiceInternal.class);
16498        mountServiceInternal.addExternalStoragePolicy(
16499                new MountServiceInternal.ExternalStorageMountPolicy() {
16500            @Override
16501            public int getMountMode(int uid, String packageName) {
16502                if (Process.isIsolated(uid)) {
16503                    return Zygote.MOUNT_EXTERNAL_NONE;
16504                }
16505                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16506                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16507                }
16508                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16509                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16510                }
16511                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16512                    return Zygote.MOUNT_EXTERNAL_READ;
16513                }
16514                return Zygote.MOUNT_EXTERNAL_WRITE;
16515            }
16516
16517            @Override
16518            public boolean hasExternalStorage(int uid, String packageName) {
16519                return true;
16520            }
16521        });
16522    }
16523
16524    @Override
16525    public boolean isSafeMode() {
16526        return mSafeMode;
16527    }
16528
16529    @Override
16530    public boolean hasSystemUidErrors() {
16531        return mHasSystemUidErrors;
16532    }
16533
16534    static String arrayToString(int[] array) {
16535        StringBuffer buf = new StringBuffer(128);
16536        buf.append('[');
16537        if (array != null) {
16538            for (int i=0; i<array.length; i++) {
16539                if (i > 0) buf.append(", ");
16540                buf.append(array[i]);
16541            }
16542        }
16543        buf.append(']');
16544        return buf.toString();
16545    }
16546
16547    static class DumpState {
16548        public static final int DUMP_LIBS = 1 << 0;
16549        public static final int DUMP_FEATURES = 1 << 1;
16550        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16551        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16552        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16553        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16554        public static final int DUMP_PERMISSIONS = 1 << 6;
16555        public static final int DUMP_PACKAGES = 1 << 7;
16556        public static final int DUMP_SHARED_USERS = 1 << 8;
16557        public static final int DUMP_MESSAGES = 1 << 9;
16558        public static final int DUMP_PROVIDERS = 1 << 10;
16559        public static final int DUMP_VERIFIERS = 1 << 11;
16560        public static final int DUMP_PREFERRED = 1 << 12;
16561        public static final int DUMP_PREFERRED_XML = 1 << 13;
16562        public static final int DUMP_KEYSETS = 1 << 14;
16563        public static final int DUMP_VERSION = 1 << 15;
16564        public static final int DUMP_INSTALLS = 1 << 16;
16565        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16566        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16567
16568        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16569
16570        private int mTypes;
16571
16572        private int mOptions;
16573
16574        private boolean mTitlePrinted;
16575
16576        private SharedUserSetting mSharedUser;
16577
16578        public boolean isDumping(int type) {
16579            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16580                return true;
16581            }
16582
16583            return (mTypes & type) != 0;
16584        }
16585
16586        public void setDump(int type) {
16587            mTypes |= type;
16588        }
16589
16590        public boolean isOptionEnabled(int option) {
16591            return (mOptions & option) != 0;
16592        }
16593
16594        public void setOptionEnabled(int option) {
16595            mOptions |= option;
16596        }
16597
16598        public boolean onTitlePrinted() {
16599            final boolean printed = mTitlePrinted;
16600            mTitlePrinted = true;
16601            return printed;
16602        }
16603
16604        public boolean getTitlePrinted() {
16605            return mTitlePrinted;
16606        }
16607
16608        public void setTitlePrinted(boolean enabled) {
16609            mTitlePrinted = enabled;
16610        }
16611
16612        public SharedUserSetting getSharedUser() {
16613            return mSharedUser;
16614        }
16615
16616        public void setSharedUser(SharedUserSetting user) {
16617            mSharedUser = user;
16618        }
16619    }
16620
16621    @Override
16622    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16623            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16624        (new PackageManagerShellCommand(this)).exec(
16625                this, in, out, err, args, resultReceiver);
16626    }
16627
16628    @Override
16629    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16630        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16631                != PackageManager.PERMISSION_GRANTED) {
16632            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16633                    + Binder.getCallingPid()
16634                    + ", uid=" + Binder.getCallingUid()
16635                    + " without permission "
16636                    + android.Manifest.permission.DUMP);
16637            return;
16638        }
16639
16640        DumpState dumpState = new DumpState();
16641        boolean fullPreferred = false;
16642        boolean checkin = false;
16643
16644        String packageName = null;
16645        ArraySet<String> permissionNames = null;
16646
16647        int opti = 0;
16648        while (opti < args.length) {
16649            String opt = args[opti];
16650            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16651                break;
16652            }
16653            opti++;
16654
16655            if ("-a".equals(opt)) {
16656                // Right now we only know how to print all.
16657            } else if ("-h".equals(opt)) {
16658                pw.println("Package manager dump options:");
16659                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16660                pw.println("    --checkin: dump for a checkin");
16661                pw.println("    -f: print details of intent filters");
16662                pw.println("    -h: print this help");
16663                pw.println("  cmd may be one of:");
16664                pw.println("    l[ibraries]: list known shared libraries");
16665                pw.println("    f[eatures]: list device features");
16666                pw.println("    k[eysets]: print known keysets");
16667                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16668                pw.println("    perm[issions]: dump permissions");
16669                pw.println("    permission [name ...]: dump declaration and use of given permission");
16670                pw.println("    pref[erred]: print preferred package settings");
16671                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16672                pw.println("    prov[iders]: dump content providers");
16673                pw.println("    p[ackages]: dump installed packages");
16674                pw.println("    s[hared-users]: dump shared user IDs");
16675                pw.println("    m[essages]: print collected runtime messages");
16676                pw.println("    v[erifiers]: print package verifier info");
16677                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16678                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16679                pw.println("    version: print database version info");
16680                pw.println("    write: write current settings now");
16681                pw.println("    installs: details about install sessions");
16682                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16683                pw.println("    <package.name>: info about given package");
16684                return;
16685            } else if ("--checkin".equals(opt)) {
16686                checkin = true;
16687            } else if ("-f".equals(opt)) {
16688                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16689            } else {
16690                pw.println("Unknown argument: " + opt + "; use -h for help");
16691            }
16692        }
16693
16694        // Is the caller requesting to dump a particular piece of data?
16695        if (opti < args.length) {
16696            String cmd = args[opti];
16697            opti++;
16698            // Is this a package name?
16699            if ("android".equals(cmd) || cmd.contains(".")) {
16700                packageName = cmd;
16701                // When dumping a single package, we always dump all of its
16702                // filter information since the amount of data will be reasonable.
16703                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16704            } else if ("check-permission".equals(cmd)) {
16705                if (opti >= args.length) {
16706                    pw.println("Error: check-permission missing permission argument");
16707                    return;
16708                }
16709                String perm = args[opti];
16710                opti++;
16711                if (opti >= args.length) {
16712                    pw.println("Error: check-permission missing package argument");
16713                    return;
16714                }
16715                String pkg = args[opti];
16716                opti++;
16717                int user = UserHandle.getUserId(Binder.getCallingUid());
16718                if (opti < args.length) {
16719                    try {
16720                        user = Integer.parseInt(args[opti]);
16721                    } catch (NumberFormatException e) {
16722                        pw.println("Error: check-permission user argument is not a number: "
16723                                + args[opti]);
16724                        return;
16725                    }
16726                }
16727                pw.println(checkPermission(perm, pkg, user));
16728                return;
16729            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16730                dumpState.setDump(DumpState.DUMP_LIBS);
16731            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16732                dumpState.setDump(DumpState.DUMP_FEATURES);
16733            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16734                if (opti >= args.length) {
16735                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16736                            | DumpState.DUMP_SERVICE_RESOLVERS
16737                            | DumpState.DUMP_RECEIVER_RESOLVERS
16738                            | DumpState.DUMP_CONTENT_RESOLVERS);
16739                } else {
16740                    while (opti < args.length) {
16741                        String name = args[opti];
16742                        if ("a".equals(name) || "activity".equals(name)) {
16743                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16744                        } else if ("s".equals(name) || "service".equals(name)) {
16745                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16746                        } else if ("r".equals(name) || "receiver".equals(name)) {
16747                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16748                        } else if ("c".equals(name) || "content".equals(name)) {
16749                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16750                        } else {
16751                            pw.println("Error: unknown resolver table type: " + name);
16752                            return;
16753                        }
16754                        opti++;
16755                    }
16756                }
16757            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16758                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16759            } else if ("permission".equals(cmd)) {
16760                if (opti >= args.length) {
16761                    pw.println("Error: permission requires permission name");
16762                    return;
16763                }
16764                permissionNames = new ArraySet<>();
16765                while (opti < args.length) {
16766                    permissionNames.add(args[opti]);
16767                    opti++;
16768                }
16769                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16770                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16771            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16772                dumpState.setDump(DumpState.DUMP_PREFERRED);
16773            } else if ("preferred-xml".equals(cmd)) {
16774                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16775                if (opti < args.length && "--full".equals(args[opti])) {
16776                    fullPreferred = true;
16777                    opti++;
16778                }
16779            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16780                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16781            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16782                dumpState.setDump(DumpState.DUMP_PACKAGES);
16783            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16784                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16785            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16786                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16787            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16788                dumpState.setDump(DumpState.DUMP_MESSAGES);
16789            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16790                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16791            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16792                    || "intent-filter-verifiers".equals(cmd)) {
16793                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16794            } else if ("version".equals(cmd)) {
16795                dumpState.setDump(DumpState.DUMP_VERSION);
16796            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16797                dumpState.setDump(DumpState.DUMP_KEYSETS);
16798            } else if ("installs".equals(cmd)) {
16799                dumpState.setDump(DumpState.DUMP_INSTALLS);
16800            } else if ("write".equals(cmd)) {
16801                synchronized (mPackages) {
16802                    mSettings.writeLPr();
16803                    pw.println("Settings written.");
16804                    return;
16805                }
16806            }
16807        }
16808
16809        if (checkin) {
16810            pw.println("vers,1");
16811        }
16812
16813        // reader
16814        synchronized (mPackages) {
16815            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16816                if (!checkin) {
16817                    if (dumpState.onTitlePrinted())
16818                        pw.println();
16819                    pw.println("Database versions:");
16820                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16821                }
16822            }
16823
16824            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16825                if (!checkin) {
16826                    if (dumpState.onTitlePrinted())
16827                        pw.println();
16828                    pw.println("Verifiers:");
16829                    pw.print("  Required: ");
16830                    pw.print(mRequiredVerifierPackage);
16831                    pw.print(" (uid=");
16832                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16833                            UserHandle.USER_SYSTEM));
16834                    pw.println(")");
16835                } else if (mRequiredVerifierPackage != null) {
16836                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16837                    pw.print(",");
16838                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16839                            UserHandle.USER_SYSTEM));
16840                }
16841            }
16842
16843            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16844                    packageName == null) {
16845                if (mIntentFilterVerifierComponent != null) {
16846                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16847                    if (!checkin) {
16848                        if (dumpState.onTitlePrinted())
16849                            pw.println();
16850                        pw.println("Intent Filter Verifier:");
16851                        pw.print("  Using: ");
16852                        pw.print(verifierPackageName);
16853                        pw.print(" (uid=");
16854                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16855                                UserHandle.USER_SYSTEM));
16856                        pw.println(")");
16857                    } else if (verifierPackageName != null) {
16858                        pw.print("ifv,"); pw.print(verifierPackageName);
16859                        pw.print(",");
16860                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16861                                UserHandle.USER_SYSTEM));
16862                    }
16863                } else {
16864                    pw.println();
16865                    pw.println("No Intent Filter Verifier available!");
16866                }
16867            }
16868
16869            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16870                boolean printedHeader = false;
16871                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16872                while (it.hasNext()) {
16873                    String name = it.next();
16874                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16875                    if (!checkin) {
16876                        if (!printedHeader) {
16877                            if (dumpState.onTitlePrinted())
16878                                pw.println();
16879                            pw.println("Libraries:");
16880                            printedHeader = true;
16881                        }
16882                        pw.print("  ");
16883                    } else {
16884                        pw.print("lib,");
16885                    }
16886                    pw.print(name);
16887                    if (!checkin) {
16888                        pw.print(" -> ");
16889                    }
16890                    if (ent.path != null) {
16891                        if (!checkin) {
16892                            pw.print("(jar) ");
16893                            pw.print(ent.path);
16894                        } else {
16895                            pw.print(",jar,");
16896                            pw.print(ent.path);
16897                        }
16898                    } else {
16899                        if (!checkin) {
16900                            pw.print("(apk) ");
16901                            pw.print(ent.apk);
16902                        } else {
16903                            pw.print(",apk,");
16904                            pw.print(ent.apk);
16905                        }
16906                    }
16907                    pw.println();
16908                }
16909            }
16910
16911            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16912                if (dumpState.onTitlePrinted())
16913                    pw.println();
16914                if (!checkin) {
16915                    pw.println("Features:");
16916                }
16917
16918                for (FeatureInfo feat : mAvailableFeatures.values()) {
16919                    if (checkin) {
16920                        pw.print("feat,");
16921                        pw.print(feat.name);
16922                        pw.print(",");
16923                        pw.println(feat.version);
16924                    } else {
16925                        pw.print("  ");
16926                        pw.print(feat.name);
16927                        if (feat.version > 0) {
16928                            pw.print(" version=");
16929                            pw.print(feat.version);
16930                        }
16931                        pw.println();
16932                    }
16933                }
16934            }
16935
16936            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16937                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16938                        : "Activity Resolver Table:", "  ", packageName,
16939                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16940                    dumpState.setTitlePrinted(true);
16941                }
16942            }
16943            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16944                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16945                        : "Receiver Resolver Table:", "  ", packageName,
16946                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16947                    dumpState.setTitlePrinted(true);
16948                }
16949            }
16950            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16951                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16952                        : "Service Resolver Table:", "  ", packageName,
16953                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16954                    dumpState.setTitlePrinted(true);
16955                }
16956            }
16957            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16958                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16959                        : "Provider Resolver Table:", "  ", packageName,
16960                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16961                    dumpState.setTitlePrinted(true);
16962                }
16963            }
16964
16965            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16966                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16967                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16968                    int user = mSettings.mPreferredActivities.keyAt(i);
16969                    if (pir.dump(pw,
16970                            dumpState.getTitlePrinted()
16971                                ? "\nPreferred Activities User " + user + ":"
16972                                : "Preferred Activities User " + user + ":", "  ",
16973                            packageName, true, false)) {
16974                        dumpState.setTitlePrinted(true);
16975                    }
16976                }
16977            }
16978
16979            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16980                pw.flush();
16981                FileOutputStream fout = new FileOutputStream(fd);
16982                BufferedOutputStream str = new BufferedOutputStream(fout);
16983                XmlSerializer serializer = new FastXmlSerializer();
16984                try {
16985                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16986                    serializer.startDocument(null, true);
16987                    serializer.setFeature(
16988                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16989                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16990                    serializer.endDocument();
16991                    serializer.flush();
16992                } catch (IllegalArgumentException e) {
16993                    pw.println("Failed writing: " + e);
16994                } catch (IllegalStateException e) {
16995                    pw.println("Failed writing: " + e);
16996                } catch (IOException e) {
16997                    pw.println("Failed writing: " + e);
16998                }
16999            }
17000
17001            if (!checkin
17002                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17003                    && packageName == null) {
17004                pw.println();
17005                int count = mSettings.mPackages.size();
17006                if (count == 0) {
17007                    pw.println("No applications!");
17008                    pw.println();
17009                } else {
17010                    final String prefix = "  ";
17011                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17012                    if (allPackageSettings.size() == 0) {
17013                        pw.println("No domain preferred apps!");
17014                        pw.println();
17015                    } else {
17016                        pw.println("App verification status:");
17017                        pw.println();
17018                        count = 0;
17019                        for (PackageSetting ps : allPackageSettings) {
17020                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17021                            if (ivi == null || ivi.getPackageName() == null) continue;
17022                            pw.println(prefix + "Package: " + ivi.getPackageName());
17023                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17024                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17025                            pw.println();
17026                            count++;
17027                        }
17028                        if (count == 0) {
17029                            pw.println(prefix + "No app verification established.");
17030                            pw.println();
17031                        }
17032                        for (int userId : sUserManager.getUserIds()) {
17033                            pw.println("App linkages for user " + userId + ":");
17034                            pw.println();
17035                            count = 0;
17036                            for (PackageSetting ps : allPackageSettings) {
17037                                final long status = ps.getDomainVerificationStatusForUser(userId);
17038                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17039                                    continue;
17040                                }
17041                                pw.println(prefix + "Package: " + ps.name);
17042                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17043                                String statusStr = IntentFilterVerificationInfo.
17044                                        getStatusStringFromValue(status);
17045                                pw.println(prefix + "Status:  " + statusStr);
17046                                pw.println();
17047                                count++;
17048                            }
17049                            if (count == 0) {
17050                                pw.println(prefix + "No configured app linkages.");
17051                                pw.println();
17052                            }
17053                        }
17054                    }
17055                }
17056            }
17057
17058            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17059                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17060                if (packageName == null && permissionNames == null) {
17061                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17062                        if (iperm == 0) {
17063                            if (dumpState.onTitlePrinted())
17064                                pw.println();
17065                            pw.println("AppOp Permissions:");
17066                        }
17067                        pw.print("  AppOp Permission ");
17068                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17069                        pw.println(":");
17070                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17071                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17072                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17073                        }
17074                    }
17075                }
17076            }
17077
17078            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17079                boolean printedSomething = false;
17080                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17081                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17082                        continue;
17083                    }
17084                    if (!printedSomething) {
17085                        if (dumpState.onTitlePrinted())
17086                            pw.println();
17087                        pw.println("Registered ContentProviders:");
17088                        printedSomething = true;
17089                    }
17090                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17091                    pw.print("    "); pw.println(p.toString());
17092                }
17093                printedSomething = false;
17094                for (Map.Entry<String, PackageParser.Provider> entry :
17095                        mProvidersByAuthority.entrySet()) {
17096                    PackageParser.Provider p = entry.getValue();
17097                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17098                        continue;
17099                    }
17100                    if (!printedSomething) {
17101                        if (dumpState.onTitlePrinted())
17102                            pw.println();
17103                        pw.println("ContentProvider Authorities:");
17104                        printedSomething = true;
17105                    }
17106                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17107                    pw.print("    "); pw.println(p.toString());
17108                    if (p.info != null && p.info.applicationInfo != null) {
17109                        final String appInfo = p.info.applicationInfo.toString();
17110                        pw.print("      applicationInfo="); pw.println(appInfo);
17111                    }
17112                }
17113            }
17114
17115            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17116                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17117            }
17118
17119            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17120                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17121            }
17122
17123            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17124                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17125            }
17126
17127            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17128                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17129            }
17130
17131            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17132                // XXX should handle packageName != null by dumping only install data that
17133                // the given package is involved with.
17134                if (dumpState.onTitlePrinted()) pw.println();
17135                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17136            }
17137
17138            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17139                if (dumpState.onTitlePrinted()) pw.println();
17140                mSettings.dumpReadMessagesLPr(pw, dumpState);
17141
17142                pw.println();
17143                pw.println("Package warning messages:");
17144                BufferedReader in = null;
17145                String line = null;
17146                try {
17147                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17148                    while ((line = in.readLine()) != null) {
17149                        if (line.contains("ignored: updated version")) continue;
17150                        pw.println(line);
17151                    }
17152                } catch (IOException ignored) {
17153                } finally {
17154                    IoUtils.closeQuietly(in);
17155                }
17156            }
17157
17158            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17159                BufferedReader in = null;
17160                String line = null;
17161                try {
17162                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17163                    while ((line = in.readLine()) != null) {
17164                        if (line.contains("ignored: updated version")) continue;
17165                        pw.print("msg,");
17166                        pw.println(line);
17167                    }
17168                } catch (IOException ignored) {
17169                } finally {
17170                    IoUtils.closeQuietly(in);
17171                }
17172            }
17173        }
17174    }
17175
17176    private String dumpDomainString(String packageName) {
17177        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17178        List<IntentFilter> filters = getAllIntentFilters(packageName);
17179
17180        ArraySet<String> result = new ArraySet<>();
17181        if (iviList.size() > 0) {
17182            for (IntentFilterVerificationInfo ivi : iviList) {
17183                for (String host : ivi.getDomains()) {
17184                    result.add(host);
17185                }
17186            }
17187        }
17188        if (filters != null && filters.size() > 0) {
17189            for (IntentFilter filter : filters) {
17190                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17191                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17192                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17193                    result.addAll(filter.getHostsList());
17194                }
17195            }
17196        }
17197
17198        StringBuilder sb = new StringBuilder(result.size() * 16);
17199        for (String domain : result) {
17200            if (sb.length() > 0) sb.append(" ");
17201            sb.append(domain);
17202        }
17203        return sb.toString();
17204    }
17205
17206    // ------- apps on sdcard specific code -------
17207    static final boolean DEBUG_SD_INSTALL = false;
17208
17209    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17210
17211    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17212
17213    private boolean mMediaMounted = false;
17214
17215    static String getEncryptKey() {
17216        try {
17217            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17218                    SD_ENCRYPTION_KEYSTORE_NAME);
17219            if (sdEncKey == null) {
17220                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17221                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17222                if (sdEncKey == null) {
17223                    Slog.e(TAG, "Failed to create encryption keys");
17224                    return null;
17225                }
17226            }
17227            return sdEncKey;
17228        } catch (NoSuchAlgorithmException nsae) {
17229            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17230            return null;
17231        } catch (IOException ioe) {
17232            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17233            return null;
17234        }
17235    }
17236
17237    /*
17238     * Update media status on PackageManager.
17239     */
17240    @Override
17241    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17242        int callingUid = Binder.getCallingUid();
17243        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17244            throw new SecurityException("Media status can only be updated by the system");
17245        }
17246        // reader; this apparently protects mMediaMounted, but should probably
17247        // be a different lock in that case.
17248        synchronized (mPackages) {
17249            Log.i(TAG, "Updating external media status from "
17250                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17251                    + (mediaStatus ? "mounted" : "unmounted"));
17252            if (DEBUG_SD_INSTALL)
17253                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17254                        + ", mMediaMounted=" + mMediaMounted);
17255            if (mediaStatus == mMediaMounted) {
17256                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17257                        : 0, -1);
17258                mHandler.sendMessage(msg);
17259                return;
17260            }
17261            mMediaMounted = mediaStatus;
17262        }
17263        // Queue up an async operation since the package installation may take a
17264        // little while.
17265        mHandler.post(new Runnable() {
17266            public void run() {
17267                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17268            }
17269        });
17270    }
17271
17272    /**
17273     * Called by MountService when the initial ASECs to scan are available.
17274     * Should block until all the ASEC containers are finished being scanned.
17275     */
17276    public void scanAvailableAsecs() {
17277        updateExternalMediaStatusInner(true, false, false);
17278    }
17279
17280    /*
17281     * Collect information of applications on external media, map them against
17282     * existing containers and update information based on current mount status.
17283     * Please note that we always have to report status if reportStatus has been
17284     * set to true especially when unloading packages.
17285     */
17286    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17287            boolean externalStorage) {
17288        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17289        int[] uidArr = EmptyArray.INT;
17290
17291        final String[] list = PackageHelper.getSecureContainerList();
17292        if (ArrayUtils.isEmpty(list)) {
17293            Log.i(TAG, "No secure containers found");
17294        } else {
17295            // Process list of secure containers and categorize them
17296            // as active or stale based on their package internal state.
17297
17298            // reader
17299            synchronized (mPackages) {
17300                for (String cid : list) {
17301                    // Leave stages untouched for now; installer service owns them
17302                    if (PackageInstallerService.isStageName(cid)) continue;
17303
17304                    if (DEBUG_SD_INSTALL)
17305                        Log.i(TAG, "Processing container " + cid);
17306                    String pkgName = getAsecPackageName(cid);
17307                    if (pkgName == null) {
17308                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17309                        continue;
17310                    }
17311                    if (DEBUG_SD_INSTALL)
17312                        Log.i(TAG, "Looking for pkg : " + pkgName);
17313
17314                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17315                    if (ps == null) {
17316                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17317                        continue;
17318                    }
17319
17320                    /*
17321                     * Skip packages that are not external if we're unmounting
17322                     * external storage.
17323                     */
17324                    if (externalStorage && !isMounted && !isExternal(ps)) {
17325                        continue;
17326                    }
17327
17328                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17329                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17330                    // The package status is changed only if the code path
17331                    // matches between settings and the container id.
17332                    if (ps.codePathString != null
17333                            && ps.codePathString.startsWith(args.getCodePath())) {
17334                        if (DEBUG_SD_INSTALL) {
17335                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17336                                    + " at code path: " + ps.codePathString);
17337                        }
17338
17339                        // We do have a valid package installed on sdcard
17340                        processCids.put(args, ps.codePathString);
17341                        final int uid = ps.appId;
17342                        if (uid != -1) {
17343                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17344                        }
17345                    } else {
17346                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17347                                + ps.codePathString);
17348                    }
17349                }
17350            }
17351
17352            Arrays.sort(uidArr);
17353        }
17354
17355        // Process packages with valid entries.
17356        if (isMounted) {
17357            if (DEBUG_SD_INSTALL)
17358                Log.i(TAG, "Loading packages");
17359            loadMediaPackages(processCids, uidArr, externalStorage);
17360            startCleaningPackages();
17361            mInstallerService.onSecureContainersAvailable();
17362        } else {
17363            if (DEBUG_SD_INSTALL)
17364                Log.i(TAG, "Unloading packages");
17365            unloadMediaPackages(processCids, uidArr, reportStatus);
17366        }
17367    }
17368
17369    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17370            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17371        final int size = infos.size();
17372        final String[] packageNames = new String[size];
17373        final int[] packageUids = new int[size];
17374        for (int i = 0; i < size; i++) {
17375            final ApplicationInfo info = infos.get(i);
17376            packageNames[i] = info.packageName;
17377            packageUids[i] = info.uid;
17378        }
17379        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17380                finishedReceiver);
17381    }
17382
17383    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17384            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17385        sendResourcesChangedBroadcast(mediaStatus, replacing,
17386                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17387    }
17388
17389    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17390            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17391        int size = pkgList.length;
17392        if (size > 0) {
17393            // Send broadcasts here
17394            Bundle extras = new Bundle();
17395            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17396            if (uidArr != null) {
17397                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17398            }
17399            if (replacing) {
17400                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17401            }
17402            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17403                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17404            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17405        }
17406    }
17407
17408   /*
17409     * Look at potentially valid container ids from processCids If package
17410     * information doesn't match the one on record or package scanning fails,
17411     * the cid is added to list of removeCids. We currently don't delete stale
17412     * containers.
17413     */
17414    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17415            boolean externalStorage) {
17416        ArrayList<String> pkgList = new ArrayList<String>();
17417        Set<AsecInstallArgs> keys = processCids.keySet();
17418
17419        for (AsecInstallArgs args : keys) {
17420            String codePath = processCids.get(args);
17421            if (DEBUG_SD_INSTALL)
17422                Log.i(TAG, "Loading container : " + args.cid);
17423            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17424            try {
17425                // Make sure there are no container errors first.
17426                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17427                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17428                            + " when installing from sdcard");
17429                    continue;
17430                }
17431                // Check code path here.
17432                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17433                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17434                            + " does not match one in settings " + codePath);
17435                    continue;
17436                }
17437                // Parse package
17438                int parseFlags = mDefParseFlags;
17439                if (args.isExternalAsec()) {
17440                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17441                }
17442                if (args.isFwdLocked()) {
17443                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17444                }
17445
17446                synchronized (mInstallLock) {
17447                    PackageParser.Package pkg = null;
17448                    try {
17449                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17450                    } catch (PackageManagerException e) {
17451                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17452                    }
17453                    // Scan the package
17454                    if (pkg != null) {
17455                        /*
17456                         * TODO why is the lock being held? doPostInstall is
17457                         * called in other places without the lock. This needs
17458                         * to be straightened out.
17459                         */
17460                        // writer
17461                        synchronized (mPackages) {
17462                            retCode = PackageManager.INSTALL_SUCCEEDED;
17463                            pkgList.add(pkg.packageName);
17464                            // Post process args
17465                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17466                                    pkg.applicationInfo.uid);
17467                        }
17468                    } else {
17469                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17470                    }
17471                }
17472
17473            } finally {
17474                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17475                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17476                }
17477            }
17478        }
17479        // writer
17480        synchronized (mPackages) {
17481            // If the platform SDK has changed since the last time we booted,
17482            // we need to re-grant app permission to catch any new ones that
17483            // appear. This is really a hack, and means that apps can in some
17484            // cases get permissions that the user didn't initially explicitly
17485            // allow... it would be nice to have some better way to handle
17486            // this situation.
17487            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17488                    : mSettings.getInternalVersion();
17489            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17490                    : StorageManager.UUID_PRIVATE_INTERNAL;
17491
17492            int updateFlags = UPDATE_PERMISSIONS_ALL;
17493            if (ver.sdkVersion != mSdkVersion) {
17494                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17495                        + mSdkVersion + "; regranting permissions for external");
17496                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17497            }
17498            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17499
17500            // Yay, everything is now upgraded
17501            ver.forceCurrent();
17502
17503            // can downgrade to reader
17504            // Persist settings
17505            mSettings.writeLPr();
17506        }
17507        // Send a broadcast to let everyone know we are done processing
17508        if (pkgList.size() > 0) {
17509            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17510        }
17511    }
17512
17513   /*
17514     * Utility method to unload a list of specified containers
17515     */
17516    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17517        // Just unmount all valid containers.
17518        for (AsecInstallArgs arg : cidArgs) {
17519            synchronized (mInstallLock) {
17520                arg.doPostDeleteLI(false);
17521           }
17522       }
17523   }
17524
17525    /*
17526     * Unload packages mounted on external media. This involves deleting package
17527     * data from internal structures, sending broadcasts about disabled packages,
17528     * gc'ing to free up references, unmounting all secure containers
17529     * corresponding to packages on external media, and posting a
17530     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17531     * that we always have to post this message if status has been requested no
17532     * matter what.
17533     */
17534    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17535            final boolean reportStatus) {
17536        if (DEBUG_SD_INSTALL)
17537            Log.i(TAG, "unloading media packages");
17538        ArrayList<String> pkgList = new ArrayList<String>();
17539        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17540        final Set<AsecInstallArgs> keys = processCids.keySet();
17541        for (AsecInstallArgs args : keys) {
17542            String pkgName = args.getPackageName();
17543            if (DEBUG_SD_INSTALL)
17544                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17545            // Delete package internally
17546            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17547            synchronized (mInstallLock) {
17548                boolean res = deletePackageLI(pkgName, null, false, null,
17549                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17550                if (res) {
17551                    pkgList.add(pkgName);
17552                } else {
17553                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17554                    failedList.add(args);
17555                }
17556            }
17557        }
17558
17559        // reader
17560        synchronized (mPackages) {
17561            // We didn't update the settings after removing each package;
17562            // write them now for all packages.
17563            mSettings.writeLPr();
17564        }
17565
17566        // We have to absolutely send UPDATED_MEDIA_STATUS only
17567        // after confirming that all the receivers processed the ordered
17568        // broadcast when packages get disabled, force a gc to clean things up.
17569        // and unload all the containers.
17570        if (pkgList.size() > 0) {
17571            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17572                    new IIntentReceiver.Stub() {
17573                public void performReceive(Intent intent, int resultCode, String data,
17574                        Bundle extras, boolean ordered, boolean sticky,
17575                        int sendingUser) throws RemoteException {
17576                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17577                            reportStatus ? 1 : 0, 1, keys);
17578                    mHandler.sendMessage(msg);
17579                }
17580            });
17581        } else {
17582            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17583                    keys);
17584            mHandler.sendMessage(msg);
17585        }
17586    }
17587
17588    private void loadPrivatePackages(final VolumeInfo vol) {
17589        mHandler.post(new Runnable() {
17590            @Override
17591            public void run() {
17592                loadPrivatePackagesInner(vol);
17593            }
17594        });
17595    }
17596
17597    private void loadPrivatePackagesInner(VolumeInfo vol) {
17598        final String volumeUuid = vol.fsUuid;
17599        if (TextUtils.isEmpty(volumeUuid)) {
17600            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17601            return;
17602        }
17603
17604        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17605        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17606
17607        final VersionInfo ver;
17608        final List<PackageSetting> packages;
17609        synchronized (mPackages) {
17610            ver = mSettings.findOrCreateVersion(volumeUuid);
17611            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17612        }
17613
17614        // TODO: introduce a new concept similar to "frozen" to prevent these
17615        // apps from being launched until after data has been fully reconciled
17616        for (PackageSetting ps : packages) {
17617            synchronized (mInstallLock) {
17618                final PackageParser.Package pkg;
17619                try {
17620                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17621                    loaded.add(pkg.applicationInfo);
17622
17623                } catch (PackageManagerException e) {
17624                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17625                }
17626
17627                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17628                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17629                }
17630            }
17631        }
17632
17633        // Reconcile app data for all started/unlocked users
17634        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17635        final UserManager um = mContext.getSystemService(UserManager.class);
17636        for (UserInfo user : um.getUsers()) {
17637            final int flags;
17638            if (um.isUserUnlocked(user.id)) {
17639                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17640            } else if (um.isUserRunning(user.id)) {
17641                flags = StorageManager.FLAG_STORAGE_DE;
17642            } else {
17643                continue;
17644            }
17645
17646            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17647            reconcileAppsData(volumeUuid, user.id, flags);
17648        }
17649
17650        synchronized (mPackages) {
17651            int updateFlags = UPDATE_PERMISSIONS_ALL;
17652            if (ver.sdkVersion != mSdkVersion) {
17653                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17654                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17655                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17656            }
17657            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17658
17659            // Yay, everything is now upgraded
17660            ver.forceCurrent();
17661
17662            mSettings.writeLPr();
17663        }
17664
17665        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17666        sendResourcesChangedBroadcast(true, false, loaded, null);
17667    }
17668
17669    private void unloadPrivatePackages(final VolumeInfo vol) {
17670        mHandler.post(new Runnable() {
17671            @Override
17672            public void run() {
17673                unloadPrivatePackagesInner(vol);
17674            }
17675        });
17676    }
17677
17678    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17679        final String volumeUuid = vol.fsUuid;
17680        if (TextUtils.isEmpty(volumeUuid)) {
17681            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17682            return;
17683        }
17684
17685        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17686        synchronized (mInstallLock) {
17687        synchronized (mPackages) {
17688            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17689            for (PackageSetting ps : packages) {
17690                if (ps.pkg == null) continue;
17691
17692                final ApplicationInfo info = ps.pkg.applicationInfo;
17693                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17694                if (deletePackageLI(ps.name, null, false, null,
17695                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17696                    unloaded.add(info);
17697                } else {
17698                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17699                }
17700            }
17701
17702            mSettings.writeLPr();
17703        }
17704        }
17705
17706        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17707        sendResourcesChangedBroadcast(false, false, unloaded, null);
17708    }
17709
17710    /**
17711     * Examine all users present on given mounted volume, and destroy data
17712     * belonging to users that are no longer valid, or whose user ID has been
17713     * recycled.
17714     */
17715    private void reconcileUsers(String volumeUuid) {
17716        // TODO: also reconcile DE directories
17717        final File[] files = FileUtils
17718                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17719        for (File file : files) {
17720            if (!file.isDirectory()) continue;
17721
17722            final int userId;
17723            final UserInfo info;
17724            try {
17725                userId = Integer.parseInt(file.getName());
17726                info = sUserManager.getUserInfo(userId);
17727            } catch (NumberFormatException e) {
17728                Slog.w(TAG, "Invalid user directory " + file);
17729                continue;
17730            }
17731
17732            boolean destroyUser = false;
17733            if (info == null) {
17734                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17735                        + " because no matching user was found");
17736                destroyUser = true;
17737            } else {
17738                try {
17739                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17740                } catch (IOException e) {
17741                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17742                            + " because we failed to enforce serial number: " + e);
17743                    destroyUser = true;
17744                }
17745            }
17746
17747            if (destroyUser) {
17748                synchronized (mInstallLock) {
17749                    try {
17750                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17751                    } catch (InstallerException e) {
17752                        Slog.w(TAG, "Failed to clean up user dirs", e);
17753                    }
17754                }
17755            }
17756        }
17757    }
17758
17759    private void assertPackageKnown(String volumeUuid, String packageName)
17760            throws PackageManagerException {
17761        synchronized (mPackages) {
17762            final PackageSetting ps = mSettings.mPackages.get(packageName);
17763            if (ps == null) {
17764                throw new PackageManagerException("Package " + packageName + " is unknown");
17765            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17766                throw new PackageManagerException(
17767                        "Package " + packageName + " found on unknown volume " + volumeUuid
17768                                + "; expected volume " + ps.volumeUuid);
17769            }
17770        }
17771    }
17772
17773    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17774            throws PackageManagerException {
17775        synchronized (mPackages) {
17776            final PackageSetting ps = mSettings.mPackages.get(packageName);
17777            if (ps == null) {
17778                throw new PackageManagerException("Package " + packageName + " is unknown");
17779            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17780                throw new PackageManagerException(
17781                        "Package " + packageName + " found on unknown volume " + volumeUuid
17782                                + "; expected volume " + ps.volumeUuid);
17783            } else if (!ps.getInstalled(userId)) {
17784                throw new PackageManagerException(
17785                        "Package " + packageName + " not installed for user " + userId);
17786            }
17787        }
17788    }
17789
17790    /**
17791     * Examine all apps present on given mounted volume, and destroy apps that
17792     * aren't expected, either due to uninstallation or reinstallation on
17793     * another volume.
17794     */
17795    private void reconcileApps(String volumeUuid) {
17796        final File[] files = FileUtils
17797                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17798        for (File file : files) {
17799            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17800                    && !PackageInstallerService.isStageName(file.getName());
17801            if (!isPackage) {
17802                // Ignore entries which are not packages
17803                continue;
17804            }
17805
17806            try {
17807                final PackageLite pkg = PackageParser.parsePackageLite(file,
17808                        PackageParser.PARSE_MUST_BE_APK);
17809                assertPackageKnown(volumeUuid, pkg.packageName);
17810
17811            } catch (PackageParserException | PackageManagerException e) {
17812                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17813                synchronized (mInstallLock) {
17814                    removeCodePathLI(file);
17815                }
17816            }
17817        }
17818    }
17819
17820    /**
17821     * Reconcile all app data for the given user.
17822     * <p>
17823     * Verifies that directories exist and that ownership and labeling is
17824     * correct for all installed apps on all mounted volumes.
17825     */
17826    void reconcileAppsData(int userId, int flags) {
17827        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17828        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17829            final String volumeUuid = vol.getFsUuid();
17830            reconcileAppsData(volumeUuid, userId, flags);
17831        }
17832    }
17833
17834    /**
17835     * Reconcile all app data on given mounted volume.
17836     * <p>
17837     * Destroys app data that isn't expected, either due to uninstallation or
17838     * reinstallation on another volume.
17839     * <p>
17840     * Verifies that directories exist and that ownership and labeling is
17841     * correct for all installed apps.
17842     */
17843    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17844        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17845                + Integer.toHexString(flags));
17846
17847        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17848        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17849
17850        boolean restoreconNeeded = false;
17851
17852        // First look for stale data that doesn't belong, and check if things
17853        // have changed since we did our last restorecon
17854        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17855            if (!isUserKeyUnlocked(userId)) {
17856                throw new RuntimeException(
17857                        "Yikes, someone asked us to reconcile CE storage while " + userId
17858                                + " was still locked; this would have caused massive data loss!");
17859            }
17860
17861            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17862
17863            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17864            for (File file : files) {
17865                final String packageName = file.getName();
17866                try {
17867                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17868                } catch (PackageManagerException e) {
17869                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17870                    synchronized (mInstallLock) {
17871                        destroyAppDataLI(volumeUuid, packageName, userId,
17872                                StorageManager.FLAG_STORAGE_CE);
17873                    }
17874                }
17875            }
17876        }
17877        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17878            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17879
17880            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17881            for (File file : files) {
17882                final String packageName = file.getName();
17883                try {
17884                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17885                } catch (PackageManagerException e) {
17886                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17887                    synchronized (mInstallLock) {
17888                        destroyAppDataLI(volumeUuid, packageName, userId,
17889                                StorageManager.FLAG_STORAGE_DE);
17890                    }
17891                }
17892            }
17893        }
17894
17895        // Ensure that data directories are ready to roll for all packages
17896        // installed for this volume and user
17897        final List<PackageSetting> packages;
17898        synchronized (mPackages) {
17899            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17900        }
17901        int preparedCount = 0;
17902        for (PackageSetting ps : packages) {
17903            final String packageName = ps.name;
17904            if (ps.pkg == null) {
17905                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17906                // TODO: might be due to legacy ASEC apps; we should circle back
17907                // and reconcile again once they're scanned
17908                continue;
17909            }
17910
17911            if (ps.getInstalled(userId)) {
17912                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17913                preparedCount++;
17914            }
17915        }
17916
17917        if (restoreconNeeded) {
17918            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17919                SELinuxMMAC.setRestoreconDone(ceDir);
17920            }
17921            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17922                SELinuxMMAC.setRestoreconDone(deDir);
17923            }
17924        }
17925
17926        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17927                + " packages; restoreconNeeded was " + restoreconNeeded);
17928    }
17929
17930    /**
17931     * Prepare app data for the given app just after it was installed or
17932     * upgraded. This method carefully only touches users that it's installed
17933     * for, and it forces a restorecon to handle any seinfo changes.
17934     * <p>
17935     * Verifies that directories exist and that ownership and labeling is
17936     * correct for all installed apps. If there is an ownership mismatch, it
17937     * will try recovering system apps by wiping data; third-party app data is
17938     * left intact.
17939     */
17940    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17941        prepareAppDataAfterInstallInternal(pkg);
17942        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17943        for (int i = 0; i < childCount; i++) {
17944            PackageParser.Package childPackage = pkg.childPackages.get(i);
17945            prepareAppDataAfterInstallInternal(childPackage);
17946        }
17947    }
17948
17949    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17950        final PackageSetting ps;
17951        synchronized (mPackages) {
17952            ps = mSettings.mPackages.get(pkg.packageName);
17953        }
17954
17955        final UserManager um = mContext.getSystemService(UserManager.class);
17956        for (UserInfo user : um.getUsers()) {
17957            final int flags;
17958            if (um.isUserUnlocked(user.id)) {
17959                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17960            } else if (um.isUserRunning(user.id)) {
17961                flags = StorageManager.FLAG_STORAGE_DE;
17962            } else {
17963                continue;
17964            }
17965
17966            if (ps.getInstalled(user.id)) {
17967                // Whenever an app changes, force a restorecon of its data
17968                // TODO: when user data is locked, mark that we're still dirty
17969                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17970            }
17971        }
17972    }
17973
17974    /**
17975     * Prepare app data for the given app.
17976     * <p>
17977     * Verifies that directories exist and that ownership and labeling is
17978     * correct for all installed apps. If there is an ownership mismatch, this
17979     * will try recovering system apps by wiping data; third-party app data is
17980     * left intact.
17981     */
17982    private void prepareAppData(String volumeUuid, int userId, int flags,
17983            PackageParser.Package pkg, boolean restoreconNeeded) {
17984        if (DEBUG_APP_DATA) {
17985            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17986                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17987        }
17988
17989        final String packageName = pkg.packageName;
17990        final ApplicationInfo app = pkg.applicationInfo;
17991        final int appId = UserHandle.getAppId(app.uid);
17992
17993        Preconditions.checkNotNull(app.seinfo);
17994
17995        synchronized (mInstallLock) {
17996            try {
17997                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17998                        appId, app.seinfo, app.targetSdkVersion);
17999            } catch (InstallerException e) {
18000                if (app.isSystemApp()) {
18001                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18002                            + ", but trying to recover: " + e);
18003                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18004                    try {
18005                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18006                                appId, app.seinfo, app.targetSdkVersion);
18007                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18008                    } catch (InstallerException e2) {
18009                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18010                    }
18011                } else {
18012                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18013                }
18014            }
18015
18016            if (restoreconNeeded) {
18017                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18018            }
18019
18020            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18021                // Create a native library symlink only if we have native libraries
18022                // and if the native libraries are 32 bit libraries. We do not provide
18023                // this symlink for 64 bit libraries.
18024                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18025                    final String nativeLibPath = app.nativeLibraryDir;
18026                    try {
18027                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18028                                nativeLibPath, userId);
18029                    } catch (InstallerException e) {
18030                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18031                    }
18032                }
18033            }
18034        }
18035    }
18036
18037    private void unfreezePackage(String packageName) {
18038        synchronized (mPackages) {
18039            final PackageSetting ps = mSettings.mPackages.get(packageName);
18040            if (ps != null) {
18041                ps.frozen = false;
18042            }
18043        }
18044    }
18045
18046    @Override
18047    public int movePackage(final String packageName, final String volumeUuid) {
18048        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18049
18050        final int moveId = mNextMoveId.getAndIncrement();
18051        mHandler.post(new Runnable() {
18052            @Override
18053            public void run() {
18054                try {
18055                    movePackageInternal(packageName, volumeUuid, moveId);
18056                } catch (PackageManagerException e) {
18057                    Slog.w(TAG, "Failed to move " + packageName, e);
18058                    mMoveCallbacks.notifyStatusChanged(moveId,
18059                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18060                }
18061            }
18062        });
18063        return moveId;
18064    }
18065
18066    private void movePackageInternal(final String packageName, final String volumeUuid,
18067            final int moveId) throws PackageManagerException {
18068        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18069        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18070        final PackageManager pm = mContext.getPackageManager();
18071
18072        final boolean currentAsec;
18073        final String currentVolumeUuid;
18074        final File codeFile;
18075        final String installerPackageName;
18076        final String packageAbiOverride;
18077        final int appId;
18078        final String seinfo;
18079        final String label;
18080        final int targetSdkVersion;
18081
18082        // reader
18083        synchronized (mPackages) {
18084            final PackageParser.Package pkg = mPackages.get(packageName);
18085            final PackageSetting ps = mSettings.mPackages.get(packageName);
18086            if (pkg == null || ps == null) {
18087                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18088            }
18089
18090            if (pkg.applicationInfo.isSystemApp()) {
18091                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18092                        "Cannot move system application");
18093            }
18094
18095            if (pkg.applicationInfo.isExternalAsec()) {
18096                currentAsec = true;
18097                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18098            } else if (pkg.applicationInfo.isForwardLocked()) {
18099                currentAsec = true;
18100                currentVolumeUuid = "forward_locked";
18101            } else {
18102                currentAsec = false;
18103                currentVolumeUuid = ps.volumeUuid;
18104
18105                final File probe = new File(pkg.codePath);
18106                final File probeOat = new File(probe, "oat");
18107                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18108                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18109                            "Move only supported for modern cluster style installs");
18110                }
18111            }
18112
18113            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18114                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18115                        "Package already moved to " + volumeUuid);
18116            }
18117
18118            if (ps.frozen) {
18119                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18120                        "Failed to move already frozen package");
18121            }
18122            ps.frozen = true;
18123
18124            codeFile = new File(pkg.codePath);
18125            installerPackageName = ps.installerPackageName;
18126            packageAbiOverride = ps.cpuAbiOverrideString;
18127            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18128            seinfo = pkg.applicationInfo.seinfo;
18129            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18130            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18131        }
18132
18133        // Now that we're guarded by frozen state, kill app during move
18134        final long token = Binder.clearCallingIdentity();
18135        try {
18136            killApplication(packageName, appId, "move pkg");
18137        } finally {
18138            Binder.restoreCallingIdentity(token);
18139        }
18140
18141        final Bundle extras = new Bundle();
18142        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18143        extras.putString(Intent.EXTRA_TITLE, label);
18144        mMoveCallbacks.notifyCreated(moveId, extras);
18145
18146        int installFlags;
18147        final boolean moveCompleteApp;
18148        final File measurePath;
18149
18150        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18151            installFlags = INSTALL_INTERNAL;
18152            moveCompleteApp = !currentAsec;
18153            measurePath = Environment.getDataAppDirectory(volumeUuid);
18154        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18155            installFlags = INSTALL_EXTERNAL;
18156            moveCompleteApp = false;
18157            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18158        } else {
18159            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18160            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18161                    || !volume.isMountedWritable()) {
18162                unfreezePackage(packageName);
18163                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18164                        "Move location not mounted private volume");
18165            }
18166
18167            Preconditions.checkState(!currentAsec);
18168
18169            installFlags = INSTALL_INTERNAL;
18170            moveCompleteApp = true;
18171            measurePath = Environment.getDataAppDirectory(volumeUuid);
18172        }
18173
18174        final PackageStats stats = new PackageStats(null, -1);
18175        synchronized (mInstaller) {
18176            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18177                unfreezePackage(packageName);
18178                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18179                        "Failed to measure package size");
18180            }
18181        }
18182
18183        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18184                + stats.dataSize);
18185
18186        final long startFreeBytes = measurePath.getFreeSpace();
18187        final long sizeBytes;
18188        if (moveCompleteApp) {
18189            sizeBytes = stats.codeSize + stats.dataSize;
18190        } else {
18191            sizeBytes = stats.codeSize;
18192        }
18193
18194        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18195            unfreezePackage(packageName);
18196            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18197                    "Not enough free space to move");
18198        }
18199
18200        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18201
18202        final CountDownLatch installedLatch = new CountDownLatch(1);
18203        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18204            @Override
18205            public void onUserActionRequired(Intent intent) throws RemoteException {
18206                throw new IllegalStateException();
18207            }
18208
18209            @Override
18210            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18211                    Bundle extras) throws RemoteException {
18212                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18213                        + PackageManager.installStatusToString(returnCode, msg));
18214
18215                installedLatch.countDown();
18216
18217                // Regardless of success or failure of the move operation,
18218                // always unfreeze the package
18219                unfreezePackage(packageName);
18220
18221                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18222                switch (status) {
18223                    case PackageInstaller.STATUS_SUCCESS:
18224                        mMoveCallbacks.notifyStatusChanged(moveId,
18225                                PackageManager.MOVE_SUCCEEDED);
18226                        break;
18227                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18228                        mMoveCallbacks.notifyStatusChanged(moveId,
18229                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18230                        break;
18231                    default:
18232                        mMoveCallbacks.notifyStatusChanged(moveId,
18233                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18234                        break;
18235                }
18236            }
18237        };
18238
18239        final MoveInfo move;
18240        if (moveCompleteApp) {
18241            // Kick off a thread to report progress estimates
18242            new Thread() {
18243                @Override
18244                public void run() {
18245                    while (true) {
18246                        try {
18247                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18248                                break;
18249                            }
18250                        } catch (InterruptedException ignored) {
18251                        }
18252
18253                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18254                        final int progress = 10 + (int) MathUtils.constrain(
18255                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18256                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18257                    }
18258                }
18259            }.start();
18260
18261            final String dataAppName = codeFile.getName();
18262            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18263                    dataAppName, appId, seinfo, targetSdkVersion);
18264        } else {
18265            move = null;
18266        }
18267
18268        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18269
18270        final Message msg = mHandler.obtainMessage(INIT_COPY);
18271        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18272        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18273                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
18274        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18275        msg.obj = params;
18276
18277        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18278                System.identityHashCode(msg.obj));
18279        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18280                System.identityHashCode(msg.obj));
18281
18282        mHandler.sendMessage(msg);
18283    }
18284
18285    @Override
18286    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18287        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18288
18289        final int realMoveId = mNextMoveId.getAndIncrement();
18290        final Bundle extras = new Bundle();
18291        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18292        mMoveCallbacks.notifyCreated(realMoveId, extras);
18293
18294        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18295            @Override
18296            public void onCreated(int moveId, Bundle extras) {
18297                // Ignored
18298            }
18299
18300            @Override
18301            public void onStatusChanged(int moveId, int status, long estMillis) {
18302                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18303            }
18304        };
18305
18306        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18307        storage.setPrimaryStorageUuid(volumeUuid, callback);
18308        return realMoveId;
18309    }
18310
18311    @Override
18312    public int getMoveStatus(int moveId) {
18313        mContext.enforceCallingOrSelfPermission(
18314                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18315        return mMoveCallbacks.mLastStatus.get(moveId);
18316    }
18317
18318    @Override
18319    public void registerMoveCallback(IPackageMoveObserver callback) {
18320        mContext.enforceCallingOrSelfPermission(
18321                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18322        mMoveCallbacks.register(callback);
18323    }
18324
18325    @Override
18326    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18327        mContext.enforceCallingOrSelfPermission(
18328                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18329        mMoveCallbacks.unregister(callback);
18330    }
18331
18332    @Override
18333    public boolean setInstallLocation(int loc) {
18334        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18335                null);
18336        if (getInstallLocation() == loc) {
18337            return true;
18338        }
18339        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18340                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18341            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18342                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18343            return true;
18344        }
18345        return false;
18346   }
18347
18348    @Override
18349    public int getInstallLocation() {
18350        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18351                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18352                PackageHelper.APP_INSTALL_AUTO);
18353    }
18354
18355    /** Called by UserManagerService */
18356    void cleanUpUser(UserManagerService userManager, int userHandle) {
18357        synchronized (mPackages) {
18358            mDirtyUsers.remove(userHandle);
18359            mUserNeedsBadging.delete(userHandle);
18360            mSettings.removeUserLPw(userHandle);
18361            mPendingBroadcasts.remove(userHandle);
18362            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18363        }
18364        synchronized (mInstallLock) {
18365            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18366            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18367                final String volumeUuid = vol.getFsUuid();
18368                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18369                try {
18370                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18371                } catch (InstallerException e) {
18372                    Slog.w(TAG, "Failed to remove user data", e);
18373                }
18374            }
18375            synchronized (mPackages) {
18376                removeUnusedPackagesLILPw(userManager, userHandle);
18377            }
18378        }
18379    }
18380
18381    /**
18382     * We're removing userHandle and would like to remove any downloaded packages
18383     * that are no longer in use by any other user.
18384     * @param userHandle the user being removed
18385     */
18386    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18387        final boolean DEBUG_CLEAN_APKS = false;
18388        int [] users = userManager.getUserIds();
18389        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18390        while (psit.hasNext()) {
18391            PackageSetting ps = psit.next();
18392            if (ps.pkg == null) {
18393                continue;
18394            }
18395            final String packageName = ps.pkg.packageName;
18396            // Skip over if system app
18397            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18398                continue;
18399            }
18400            if (DEBUG_CLEAN_APKS) {
18401                Slog.i(TAG, "Checking package " + packageName);
18402            }
18403            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18404            if (keep) {
18405                if (DEBUG_CLEAN_APKS) {
18406                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18407                }
18408            } else {
18409                for (int i = 0; i < users.length; i++) {
18410                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18411                        keep = true;
18412                        if (DEBUG_CLEAN_APKS) {
18413                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18414                                    + users[i]);
18415                        }
18416                        break;
18417                    }
18418                }
18419            }
18420            if (!keep) {
18421                if (DEBUG_CLEAN_APKS) {
18422                    Slog.i(TAG, "  Removing package " + packageName);
18423                }
18424                mHandler.post(new Runnable() {
18425                    public void run() {
18426                        deletePackageX(packageName, userHandle, 0);
18427                    } //end run
18428                });
18429            }
18430        }
18431    }
18432
18433    /** Called by UserManagerService */
18434    void createNewUser(int userHandle) {
18435        synchronized (mInstallLock) {
18436            try {
18437                mInstaller.createUserConfig(userHandle);
18438            } catch (InstallerException e) {
18439                Slog.w(TAG, "Failed to create user config", e);
18440            }
18441            mSettings.createNewUserLI(this, mInstaller, userHandle);
18442        }
18443        synchronized (mPackages) {
18444            applyFactoryDefaultBrowserLPw(userHandle);
18445            primeDomainVerificationsLPw(userHandle);
18446        }
18447    }
18448
18449    void newUserCreated(final int userHandle) {
18450        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18451        // If permission review for legacy apps is required, we represent
18452        // dagerous permissions for such apps as always granted runtime
18453        // permissions to keep per user flag state whether review is needed.
18454        // Hence, if a new user is added we have to propagate dangerous
18455        // permission grants for these legacy apps.
18456        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18457            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18458                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18459        }
18460    }
18461
18462    @Override
18463    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18464        mContext.enforceCallingOrSelfPermission(
18465                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18466                "Only package verification agents can read the verifier device identity");
18467
18468        synchronized (mPackages) {
18469            return mSettings.getVerifierDeviceIdentityLPw();
18470        }
18471    }
18472
18473    @Override
18474    public void setPermissionEnforced(String permission, boolean enforced) {
18475        // TODO: Now that we no longer change GID for storage, this should to away.
18476        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18477                "setPermissionEnforced");
18478        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18479            synchronized (mPackages) {
18480                if (mSettings.mReadExternalStorageEnforced == null
18481                        || mSettings.mReadExternalStorageEnforced != enforced) {
18482                    mSettings.mReadExternalStorageEnforced = enforced;
18483                    mSettings.writeLPr();
18484                }
18485            }
18486            // kill any non-foreground processes so we restart them and
18487            // grant/revoke the GID.
18488            final IActivityManager am = ActivityManagerNative.getDefault();
18489            if (am != null) {
18490                final long token = Binder.clearCallingIdentity();
18491                try {
18492                    am.killProcessesBelowForeground("setPermissionEnforcement");
18493                } catch (RemoteException e) {
18494                } finally {
18495                    Binder.restoreCallingIdentity(token);
18496                }
18497            }
18498        } else {
18499            throw new IllegalArgumentException("No selective enforcement for " + permission);
18500        }
18501    }
18502
18503    @Override
18504    @Deprecated
18505    public boolean isPermissionEnforced(String permission) {
18506        return true;
18507    }
18508
18509    @Override
18510    public boolean isStorageLow() {
18511        final long token = Binder.clearCallingIdentity();
18512        try {
18513            final DeviceStorageMonitorInternal
18514                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18515            if (dsm != null) {
18516                return dsm.isMemoryLow();
18517            } else {
18518                return false;
18519            }
18520        } finally {
18521            Binder.restoreCallingIdentity(token);
18522        }
18523    }
18524
18525    @Override
18526    public IPackageInstaller getPackageInstaller() {
18527        return mInstallerService;
18528    }
18529
18530    private boolean userNeedsBadging(int userId) {
18531        int index = mUserNeedsBadging.indexOfKey(userId);
18532        if (index < 0) {
18533            final UserInfo userInfo;
18534            final long token = Binder.clearCallingIdentity();
18535            try {
18536                userInfo = sUserManager.getUserInfo(userId);
18537            } finally {
18538                Binder.restoreCallingIdentity(token);
18539            }
18540            final boolean b;
18541            if (userInfo != null && userInfo.isManagedProfile()) {
18542                b = true;
18543            } else {
18544                b = false;
18545            }
18546            mUserNeedsBadging.put(userId, b);
18547            return b;
18548        }
18549        return mUserNeedsBadging.valueAt(index);
18550    }
18551
18552    @Override
18553    public KeySet getKeySetByAlias(String packageName, String alias) {
18554        if (packageName == null || alias == null) {
18555            return null;
18556        }
18557        synchronized(mPackages) {
18558            final PackageParser.Package pkg = mPackages.get(packageName);
18559            if (pkg == null) {
18560                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18561                throw new IllegalArgumentException("Unknown package: " + packageName);
18562            }
18563            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18564            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18565        }
18566    }
18567
18568    @Override
18569    public KeySet getSigningKeySet(String packageName) {
18570        if (packageName == null) {
18571            return null;
18572        }
18573        synchronized(mPackages) {
18574            final PackageParser.Package pkg = mPackages.get(packageName);
18575            if (pkg == null) {
18576                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18577                throw new IllegalArgumentException("Unknown package: " + packageName);
18578            }
18579            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18580                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18581                throw new SecurityException("May not access signing KeySet of other apps.");
18582            }
18583            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18584            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18585        }
18586    }
18587
18588    @Override
18589    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18590        if (packageName == null || ks == null) {
18591            return false;
18592        }
18593        synchronized(mPackages) {
18594            final PackageParser.Package pkg = mPackages.get(packageName);
18595            if (pkg == null) {
18596                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18597                throw new IllegalArgumentException("Unknown package: " + packageName);
18598            }
18599            IBinder ksh = ks.getToken();
18600            if (ksh instanceof KeySetHandle) {
18601                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18602                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18603            }
18604            return false;
18605        }
18606    }
18607
18608    @Override
18609    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18610        if (packageName == null || ks == null) {
18611            return false;
18612        }
18613        synchronized(mPackages) {
18614            final PackageParser.Package pkg = mPackages.get(packageName);
18615            if (pkg == null) {
18616                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18617                throw new IllegalArgumentException("Unknown package: " + packageName);
18618            }
18619            IBinder ksh = ks.getToken();
18620            if (ksh instanceof KeySetHandle) {
18621                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18622                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18623            }
18624            return false;
18625        }
18626    }
18627
18628    private void deletePackageIfUnusedLPr(final String packageName) {
18629        PackageSetting ps = mSettings.mPackages.get(packageName);
18630        if (ps == null) {
18631            return;
18632        }
18633        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18634            // TODO Implement atomic delete if package is unused
18635            // It is currently possible that the package will be deleted even if it is installed
18636            // after this method returns.
18637            mHandler.post(new Runnable() {
18638                public void run() {
18639                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18640                }
18641            });
18642        }
18643    }
18644
18645    /**
18646     * Check and throw if the given before/after packages would be considered a
18647     * downgrade.
18648     */
18649    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18650            throws PackageManagerException {
18651        if (after.versionCode < before.mVersionCode) {
18652            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18653                    "Update version code " + after.versionCode + " is older than current "
18654                    + before.mVersionCode);
18655        } else if (after.versionCode == before.mVersionCode) {
18656            if (after.baseRevisionCode < before.baseRevisionCode) {
18657                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18658                        "Update base revision code " + after.baseRevisionCode
18659                        + " is older than current " + before.baseRevisionCode);
18660            }
18661
18662            if (!ArrayUtils.isEmpty(after.splitNames)) {
18663                for (int i = 0; i < after.splitNames.length; i++) {
18664                    final String splitName = after.splitNames[i];
18665                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18666                    if (j != -1) {
18667                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18668                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18669                                    "Update split " + splitName + " revision code "
18670                                    + after.splitRevisionCodes[i] + " is older than current "
18671                                    + before.splitRevisionCodes[j]);
18672                        }
18673                    }
18674                }
18675            }
18676        }
18677    }
18678
18679    private static class MoveCallbacks extends Handler {
18680        private static final int MSG_CREATED = 1;
18681        private static final int MSG_STATUS_CHANGED = 2;
18682
18683        private final RemoteCallbackList<IPackageMoveObserver>
18684                mCallbacks = new RemoteCallbackList<>();
18685
18686        private final SparseIntArray mLastStatus = new SparseIntArray();
18687
18688        public MoveCallbacks(Looper looper) {
18689            super(looper);
18690        }
18691
18692        public void register(IPackageMoveObserver callback) {
18693            mCallbacks.register(callback);
18694        }
18695
18696        public void unregister(IPackageMoveObserver callback) {
18697            mCallbacks.unregister(callback);
18698        }
18699
18700        @Override
18701        public void handleMessage(Message msg) {
18702            final SomeArgs args = (SomeArgs) msg.obj;
18703            final int n = mCallbacks.beginBroadcast();
18704            for (int i = 0; i < n; i++) {
18705                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18706                try {
18707                    invokeCallback(callback, msg.what, args);
18708                } catch (RemoteException ignored) {
18709                }
18710            }
18711            mCallbacks.finishBroadcast();
18712            args.recycle();
18713        }
18714
18715        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18716                throws RemoteException {
18717            switch (what) {
18718                case MSG_CREATED: {
18719                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18720                    break;
18721                }
18722                case MSG_STATUS_CHANGED: {
18723                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18724                    break;
18725                }
18726            }
18727        }
18728
18729        private void notifyCreated(int moveId, Bundle extras) {
18730            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18731
18732            final SomeArgs args = SomeArgs.obtain();
18733            args.argi1 = moveId;
18734            args.arg2 = extras;
18735            obtainMessage(MSG_CREATED, args).sendToTarget();
18736        }
18737
18738        private void notifyStatusChanged(int moveId, int status) {
18739            notifyStatusChanged(moveId, status, -1);
18740        }
18741
18742        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18743            Slog.v(TAG, "Move " + moveId + " status " + status);
18744
18745            final SomeArgs args = SomeArgs.obtain();
18746            args.argi1 = moveId;
18747            args.argi2 = status;
18748            args.arg3 = estMillis;
18749            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18750
18751            synchronized (mLastStatus) {
18752                mLastStatus.put(moveId, status);
18753            }
18754        }
18755    }
18756
18757    private final static class OnPermissionChangeListeners extends Handler {
18758        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18759
18760        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18761                new RemoteCallbackList<>();
18762
18763        public OnPermissionChangeListeners(Looper looper) {
18764            super(looper);
18765        }
18766
18767        @Override
18768        public void handleMessage(Message msg) {
18769            switch (msg.what) {
18770                case MSG_ON_PERMISSIONS_CHANGED: {
18771                    final int uid = msg.arg1;
18772                    handleOnPermissionsChanged(uid);
18773                } break;
18774            }
18775        }
18776
18777        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18778            mPermissionListeners.register(listener);
18779
18780        }
18781
18782        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18783            mPermissionListeners.unregister(listener);
18784        }
18785
18786        public void onPermissionsChanged(int uid) {
18787            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18788                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18789            }
18790        }
18791
18792        private void handleOnPermissionsChanged(int uid) {
18793            final int count = mPermissionListeners.beginBroadcast();
18794            try {
18795                for (int i = 0; i < count; i++) {
18796                    IOnPermissionsChangeListener callback = mPermissionListeners
18797                            .getBroadcastItem(i);
18798                    try {
18799                        callback.onPermissionsChanged(uid);
18800                    } catch (RemoteException e) {
18801                        Log.e(TAG, "Permission listener is dead", e);
18802                    }
18803                }
18804            } finally {
18805                mPermissionListeners.finishBroadcast();
18806            }
18807        }
18808    }
18809
18810    private class PackageManagerInternalImpl extends PackageManagerInternal {
18811        @Override
18812        public void setLocationPackagesProvider(PackagesProvider provider) {
18813            synchronized (mPackages) {
18814                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18815            }
18816        }
18817
18818        @Override
18819        public void setImePackagesProvider(PackagesProvider provider) {
18820            synchronized (mPackages) {
18821                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18822            }
18823        }
18824
18825        @Override
18826        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18827            synchronized (mPackages) {
18828                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18829            }
18830        }
18831
18832        @Override
18833        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18834            synchronized (mPackages) {
18835                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18836            }
18837        }
18838
18839        @Override
18840        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18841            synchronized (mPackages) {
18842                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18843            }
18844        }
18845
18846        @Override
18847        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18848            synchronized (mPackages) {
18849                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18850            }
18851        }
18852
18853        @Override
18854        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18855            synchronized (mPackages) {
18856                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18857            }
18858        }
18859
18860        @Override
18861        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18862            synchronized (mPackages) {
18863                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18864                        packageName, userId);
18865            }
18866        }
18867
18868        @Override
18869        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18870            synchronized (mPackages) {
18871                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18872                        packageName, userId);
18873            }
18874        }
18875
18876        @Override
18877        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18878            synchronized (mPackages) {
18879                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18880                        packageName, userId);
18881            }
18882        }
18883
18884        @Override
18885        public void setKeepUninstalledPackages(final List<String> packageList) {
18886            Preconditions.checkNotNull(packageList);
18887            List<String> removedFromList = null;
18888            synchronized (mPackages) {
18889                if (mKeepUninstalledPackages != null) {
18890                    final int packagesCount = mKeepUninstalledPackages.size();
18891                    for (int i = 0; i < packagesCount; i++) {
18892                        String oldPackage = mKeepUninstalledPackages.get(i);
18893                        if (packageList != null && packageList.contains(oldPackage)) {
18894                            continue;
18895                        }
18896                        if (removedFromList == null) {
18897                            removedFromList = new ArrayList<>();
18898                        }
18899                        removedFromList.add(oldPackage);
18900                    }
18901                }
18902                mKeepUninstalledPackages = new ArrayList<>(packageList);
18903                if (removedFromList != null) {
18904                    final int removedCount = removedFromList.size();
18905                    for (int i = 0; i < removedCount; i++) {
18906                        deletePackageIfUnusedLPr(removedFromList.get(i));
18907                    }
18908                }
18909            }
18910        }
18911
18912        @Override
18913        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18914            synchronized (mPackages) {
18915                // If we do not support permission review, done.
18916                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18917                    return false;
18918                }
18919
18920                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18921                if (packageSetting == null) {
18922                    return false;
18923                }
18924
18925                // Permission review applies only to apps not supporting the new permission model.
18926                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18927                    return false;
18928                }
18929
18930                // Legacy apps have the permission and get user consent on launch.
18931                PermissionsState permissionsState = packageSetting.getPermissionsState();
18932                return permissionsState.isPermissionReviewRequired(userId);
18933            }
18934        }
18935    }
18936
18937    @Override
18938    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18939        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18940        synchronized (mPackages) {
18941            final long identity = Binder.clearCallingIdentity();
18942            try {
18943                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18944                        packageNames, userId);
18945            } finally {
18946                Binder.restoreCallingIdentity(identity);
18947            }
18948        }
18949    }
18950
18951    private static void enforceSystemOrPhoneCaller(String tag) {
18952        int callingUid = Binder.getCallingUid();
18953        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18954            throw new SecurityException(
18955                    "Cannot call " + tag + " from UID " + callingUid);
18956        }
18957    }
18958
18959    boolean isHistoricalPackageUsageAvailable() {
18960        return mPackageUsage.isHistoricalPackageUsageAvailable();
18961    }
18962}
18963