PackageManagerService.java revision 9496df19ae7552370ec37cfb62cce3d919b0b116
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        if (!canSuspendPackageForUser(packageName, userId)) {
10682            return false;
10683        }
10684
10685        long callingId = Binder.clearCallingIdentity();
10686        try {
10687            boolean changed = false;
10688            boolean success = false;
10689            int appId = -1;
10690            synchronized (mPackages) {
10691                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10692                if (pkgSetting != null) {
10693                    if (pkgSetting.getSuspended(userId) != suspended) {
10694                        pkgSetting.setSuspended(suspended, userId);
10695                        mSettings.writePackageRestrictionsLPr(userId);
10696                        appId = pkgSetting.appId;
10697                        changed = true;
10698                    }
10699                    success = true;
10700                }
10701            }
10702
10703            if (changed) {
10704                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10705                if (suspended) {
10706                    killApplication(packageName, UserHandle.getUid(userId, appId),
10707                            "suspending package");
10708                }
10709            }
10710            return success;
10711        } finally {
10712            Binder.restoreCallingIdentity(callingId);
10713        }
10714    }
10715
10716    @Override
10717    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10718        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10719                false, "isPackageSuspendedForUser for user " + userId);
10720        synchronized (mPackages) {
10721            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10722            return pkgSetting != null && pkgSetting.getSuspended(userId);
10723        }
10724    }
10725
10726    // TODO: investigate and add more restrictions for suspending crucial packages.
10727    private boolean canSuspendPackageForUser(String packageName, int userId) {
10728        if (isPackageDeviceAdmin(packageName, userId)) {
10729            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10730                    + "\": has active device admin");
10731            return false;
10732        }
10733
10734        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10735        if (packageName.equals(activeLauncherPackageName)) {
10736            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10737                    + "\" because it is set as the active launcher");
10738            return false;
10739        }
10740
10741        return true;
10742    }
10743
10744    private String getActiveLauncherPackageName(int userId) {
10745        Intent intent = new Intent(Intent.ACTION_MAIN);
10746        intent.addCategory(Intent.CATEGORY_HOME);
10747        ResolveInfo resolveInfo = resolveIntent(
10748                intent,
10749                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10750                PackageManager.MATCH_DEFAULT_ONLY,
10751                userId);
10752
10753        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10754    }
10755
10756    @Override
10757    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10758        mContext.enforceCallingOrSelfPermission(
10759                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10760                "Only package verification agents can verify applications");
10761
10762        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10763        final PackageVerificationResponse response = new PackageVerificationResponse(
10764                verificationCode, Binder.getCallingUid());
10765        msg.arg1 = id;
10766        msg.obj = response;
10767        mHandler.sendMessage(msg);
10768    }
10769
10770    @Override
10771    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10772            long millisecondsToDelay) {
10773        mContext.enforceCallingOrSelfPermission(
10774                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10775                "Only package verification agents can extend verification timeouts");
10776
10777        final PackageVerificationState state = mPendingVerification.get(id);
10778        final PackageVerificationResponse response = new PackageVerificationResponse(
10779                verificationCodeAtTimeout, Binder.getCallingUid());
10780
10781        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10782            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10783        }
10784        if (millisecondsToDelay < 0) {
10785            millisecondsToDelay = 0;
10786        }
10787        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10788                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10789            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10790        }
10791
10792        if ((state != null) && !state.timeoutExtended()) {
10793            state.extendTimeout();
10794
10795            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10796            msg.arg1 = id;
10797            msg.obj = response;
10798            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10799        }
10800    }
10801
10802    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10803            int verificationCode, UserHandle user) {
10804        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10805        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10806        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10807        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10808        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10809
10810        mContext.sendBroadcastAsUser(intent, user,
10811                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10812    }
10813
10814    private ComponentName matchComponentForVerifier(String packageName,
10815            List<ResolveInfo> receivers) {
10816        ActivityInfo targetReceiver = null;
10817
10818        final int NR = receivers.size();
10819        for (int i = 0; i < NR; i++) {
10820            final ResolveInfo info = receivers.get(i);
10821            if (info.activityInfo == null) {
10822                continue;
10823            }
10824
10825            if (packageName.equals(info.activityInfo.packageName)) {
10826                targetReceiver = info.activityInfo;
10827                break;
10828            }
10829        }
10830
10831        if (targetReceiver == null) {
10832            return null;
10833        }
10834
10835        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10836    }
10837
10838    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10839            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10840        if (pkgInfo.verifiers.length == 0) {
10841            return null;
10842        }
10843
10844        final int N = pkgInfo.verifiers.length;
10845        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10846        for (int i = 0; i < N; i++) {
10847            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10848
10849            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10850                    receivers);
10851            if (comp == null) {
10852                continue;
10853            }
10854
10855            final int verifierUid = getUidForVerifier(verifierInfo);
10856            if (verifierUid == -1) {
10857                continue;
10858            }
10859
10860            if (DEBUG_VERIFY) {
10861                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10862                        + " with the correct signature");
10863            }
10864            sufficientVerifiers.add(comp);
10865            verificationState.addSufficientVerifier(verifierUid);
10866        }
10867
10868        return sufficientVerifiers;
10869    }
10870
10871    private int getUidForVerifier(VerifierInfo verifierInfo) {
10872        synchronized (mPackages) {
10873            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10874            if (pkg == null) {
10875                return -1;
10876            } else if (pkg.mSignatures.length != 1) {
10877                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10878                        + " has more than one signature; ignoring");
10879                return -1;
10880            }
10881
10882            /*
10883             * If the public key of the package's signature does not match
10884             * our expected public key, then this is a different package and
10885             * we should skip.
10886             */
10887
10888            final byte[] expectedPublicKey;
10889            try {
10890                final Signature verifierSig = pkg.mSignatures[0];
10891                final PublicKey publicKey = verifierSig.getPublicKey();
10892                expectedPublicKey = publicKey.getEncoded();
10893            } catch (CertificateException e) {
10894                return -1;
10895            }
10896
10897            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10898
10899            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10900                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10901                        + " does not have the expected public key; ignoring");
10902                return -1;
10903            }
10904
10905            return pkg.applicationInfo.uid;
10906        }
10907    }
10908
10909    @Override
10910    public void finishPackageInstall(int token) {
10911        enforceSystemOrRoot("Only the system is allowed to finish installs");
10912
10913        if (DEBUG_INSTALL) {
10914            Slog.v(TAG, "BM finishing package install for " + token);
10915        }
10916        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10917
10918        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10919        mHandler.sendMessage(msg);
10920    }
10921
10922    /**
10923     * Get the verification agent timeout.
10924     *
10925     * @return verification timeout in milliseconds
10926     */
10927    private long getVerificationTimeout() {
10928        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10929                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10930                DEFAULT_VERIFICATION_TIMEOUT);
10931    }
10932
10933    /**
10934     * Get the default verification agent response code.
10935     *
10936     * @return default verification response code
10937     */
10938    private int getDefaultVerificationResponse() {
10939        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10940                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10941                DEFAULT_VERIFICATION_RESPONSE);
10942    }
10943
10944    /**
10945     * Check whether or not package verification has been enabled.
10946     *
10947     * @return true if verification should be performed
10948     */
10949    private boolean isVerificationEnabled(int userId, int installFlags) {
10950        if (!DEFAULT_VERIFY_ENABLE) {
10951            return false;
10952        }
10953        // Ephemeral apps don't get the full verification treatment
10954        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10955            if (DEBUG_EPHEMERAL) {
10956                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10957            }
10958            return false;
10959        }
10960
10961        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10962
10963        // Check if installing from ADB
10964        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10965            // Do not run verification in a test harness environment
10966            if (ActivityManager.isRunningInTestHarness()) {
10967                return false;
10968            }
10969            if (ensureVerifyAppsEnabled) {
10970                return true;
10971            }
10972            // Check if the developer does not want package verification for ADB installs
10973            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10974                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10975                return false;
10976            }
10977        }
10978
10979        if (ensureVerifyAppsEnabled) {
10980            return true;
10981        }
10982
10983        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10984                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10985    }
10986
10987    @Override
10988    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10989            throws RemoteException {
10990        mContext.enforceCallingOrSelfPermission(
10991                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10992                "Only intentfilter verification agents can verify applications");
10993
10994        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10995        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10996                Binder.getCallingUid(), verificationCode, failedDomains);
10997        msg.arg1 = id;
10998        msg.obj = response;
10999        mHandler.sendMessage(msg);
11000    }
11001
11002    @Override
11003    public int getIntentVerificationStatus(String packageName, int userId) {
11004        synchronized (mPackages) {
11005            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11006        }
11007    }
11008
11009    @Override
11010    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11011        mContext.enforceCallingOrSelfPermission(
11012                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11013
11014        boolean result = false;
11015        synchronized (mPackages) {
11016            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11017        }
11018        if (result) {
11019            scheduleWritePackageRestrictionsLocked(userId);
11020        }
11021        return result;
11022    }
11023
11024    @Override
11025    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
11026        synchronized (mPackages) {
11027            return mSettings.getIntentFilterVerificationsLPr(packageName);
11028        }
11029    }
11030
11031    @Override
11032    public List<IntentFilter> getAllIntentFilters(String packageName) {
11033        if (TextUtils.isEmpty(packageName)) {
11034            return Collections.<IntentFilter>emptyList();
11035        }
11036        synchronized (mPackages) {
11037            PackageParser.Package pkg = mPackages.get(packageName);
11038            if (pkg == null || pkg.activities == null) {
11039                return Collections.<IntentFilter>emptyList();
11040            }
11041            final int count = pkg.activities.size();
11042            ArrayList<IntentFilter> result = new ArrayList<>();
11043            for (int n=0; n<count; n++) {
11044                PackageParser.Activity activity = pkg.activities.get(n);
11045                if (activity.intents != null && activity.intents.size() > 0) {
11046                    result.addAll(activity.intents);
11047                }
11048            }
11049            return result;
11050        }
11051    }
11052
11053    @Override
11054    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11055        mContext.enforceCallingOrSelfPermission(
11056                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11057
11058        synchronized (mPackages) {
11059            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11060            if (packageName != null) {
11061                result |= updateIntentVerificationStatus(packageName,
11062                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11063                        userId);
11064                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11065                        packageName, userId);
11066            }
11067            return result;
11068        }
11069    }
11070
11071    @Override
11072    public String getDefaultBrowserPackageName(int userId) {
11073        synchronized (mPackages) {
11074            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11075        }
11076    }
11077
11078    /**
11079     * Get the "allow unknown sources" setting.
11080     *
11081     * @return the current "allow unknown sources" setting
11082     */
11083    private int getUnknownSourcesSettings() {
11084        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11085                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11086                -1);
11087    }
11088
11089    @Override
11090    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11091        final int uid = Binder.getCallingUid();
11092        // writer
11093        synchronized (mPackages) {
11094            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11095            if (targetPackageSetting == null) {
11096                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11097            }
11098
11099            PackageSetting installerPackageSetting;
11100            if (installerPackageName != null) {
11101                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11102                if (installerPackageSetting == null) {
11103                    throw new IllegalArgumentException("Unknown installer package: "
11104                            + installerPackageName);
11105                }
11106            } else {
11107                installerPackageSetting = null;
11108            }
11109
11110            Signature[] callerSignature;
11111            Object obj = mSettings.getUserIdLPr(uid);
11112            if (obj != null) {
11113                if (obj instanceof SharedUserSetting) {
11114                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11115                } else if (obj instanceof PackageSetting) {
11116                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11117                } else {
11118                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11119                }
11120            } else {
11121                throw new SecurityException("Unknown calling UID: " + uid);
11122            }
11123
11124            // Verify: can't set installerPackageName to a package that is
11125            // not signed with the same cert as the caller.
11126            if (installerPackageSetting != null) {
11127                if (compareSignatures(callerSignature,
11128                        installerPackageSetting.signatures.mSignatures)
11129                        != PackageManager.SIGNATURE_MATCH) {
11130                    throw new SecurityException(
11131                            "Caller does not have same cert as new installer package "
11132                            + installerPackageName);
11133                }
11134            }
11135
11136            // Verify: if target already has an installer package, it must
11137            // be signed with the same cert as the caller.
11138            if (targetPackageSetting.installerPackageName != null) {
11139                PackageSetting setting = mSettings.mPackages.get(
11140                        targetPackageSetting.installerPackageName);
11141                // If the currently set package isn't valid, then it's always
11142                // okay to change it.
11143                if (setting != null) {
11144                    if (compareSignatures(callerSignature,
11145                            setting.signatures.mSignatures)
11146                            != PackageManager.SIGNATURE_MATCH) {
11147                        throw new SecurityException(
11148                                "Caller does not have same cert as old installer package "
11149                                + targetPackageSetting.installerPackageName);
11150                    }
11151                }
11152            }
11153
11154            // Okay!
11155            targetPackageSetting.installerPackageName = installerPackageName;
11156            scheduleWriteSettingsLocked();
11157        }
11158    }
11159
11160    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11161        // Queue up an async operation since the package installation may take a little while.
11162        mHandler.post(new Runnable() {
11163            public void run() {
11164                mHandler.removeCallbacks(this);
11165                 // Result object to be returned
11166                PackageInstalledInfo res = new PackageInstalledInfo();
11167                res.setReturnCode(currentStatus);
11168                res.uid = -1;
11169                res.pkg = null;
11170                res.removedInfo = null;
11171                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11172                    args.doPreInstall(res.returnCode);
11173                    synchronized (mInstallLock) {
11174                        installPackageTracedLI(args, res);
11175                    }
11176                    args.doPostInstall(res.returnCode, res.uid);
11177                }
11178
11179                // A restore should be performed at this point if (a) the install
11180                // succeeded, (b) the operation is not an update, and (c) the new
11181                // package has not opted out of backup participation.
11182                final boolean update = res.removedInfo != null
11183                        && res.removedInfo.removedPackage != null;
11184                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11185                boolean doRestore = !update
11186                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11187
11188                // Set up the post-install work request bookkeeping.  This will be used
11189                // and cleaned up by the post-install event handling regardless of whether
11190                // there's a restore pass performed.  Token values are >= 1.
11191                int token;
11192                if (mNextInstallToken < 0) mNextInstallToken = 1;
11193                token = mNextInstallToken++;
11194
11195                PostInstallData data = new PostInstallData(args, res);
11196                mRunningInstalls.put(token, data);
11197                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11198
11199                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11200                    // Pass responsibility to the Backup Manager.  It will perform a
11201                    // restore if appropriate, then pass responsibility back to the
11202                    // Package Manager to run the post-install observer callbacks
11203                    // and broadcasts.
11204                    IBackupManager bm = IBackupManager.Stub.asInterface(
11205                            ServiceManager.getService(Context.BACKUP_SERVICE));
11206                    if (bm != null) {
11207                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11208                                + " to BM for possible restore");
11209                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11210                        try {
11211                            // TODO: http://b/22388012
11212                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11213                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11214                            } else {
11215                                doRestore = false;
11216                            }
11217                        } catch (RemoteException e) {
11218                            // can't happen; the backup manager is local
11219                        } catch (Exception e) {
11220                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11221                            doRestore = false;
11222                        }
11223                    } else {
11224                        Slog.e(TAG, "Backup Manager not found!");
11225                        doRestore = false;
11226                    }
11227                }
11228
11229                if (!doRestore) {
11230                    // No restore possible, or the Backup Manager was mysteriously not
11231                    // available -- just fire the post-install work request directly.
11232                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11233
11234                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11235
11236                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11237                    mHandler.sendMessage(msg);
11238                }
11239            }
11240        });
11241    }
11242
11243    private abstract class HandlerParams {
11244        private static final int MAX_RETRIES = 4;
11245
11246        /**
11247         * Number of times startCopy() has been attempted and had a non-fatal
11248         * error.
11249         */
11250        private int mRetries = 0;
11251
11252        /** User handle for the user requesting the information or installation. */
11253        private final UserHandle mUser;
11254        String traceMethod;
11255        int traceCookie;
11256
11257        HandlerParams(UserHandle user) {
11258            mUser = user;
11259        }
11260
11261        UserHandle getUser() {
11262            return mUser;
11263        }
11264
11265        HandlerParams setTraceMethod(String traceMethod) {
11266            this.traceMethod = traceMethod;
11267            return this;
11268        }
11269
11270        HandlerParams setTraceCookie(int traceCookie) {
11271            this.traceCookie = traceCookie;
11272            return this;
11273        }
11274
11275        final boolean startCopy() {
11276            boolean res;
11277            try {
11278                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11279
11280                if (++mRetries > MAX_RETRIES) {
11281                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11282                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11283                    handleServiceError();
11284                    return false;
11285                } else {
11286                    handleStartCopy();
11287                    res = true;
11288                }
11289            } catch (RemoteException e) {
11290                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11291                mHandler.sendEmptyMessage(MCS_RECONNECT);
11292                res = false;
11293            }
11294            handleReturnCode();
11295            return res;
11296        }
11297
11298        final void serviceError() {
11299            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11300            handleServiceError();
11301            handleReturnCode();
11302        }
11303
11304        abstract void handleStartCopy() throws RemoteException;
11305        abstract void handleServiceError();
11306        abstract void handleReturnCode();
11307    }
11308
11309    class MeasureParams extends HandlerParams {
11310        private final PackageStats mStats;
11311        private boolean mSuccess;
11312
11313        private final IPackageStatsObserver mObserver;
11314
11315        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11316            super(new UserHandle(stats.userHandle));
11317            mObserver = observer;
11318            mStats = stats;
11319        }
11320
11321        @Override
11322        public String toString() {
11323            return "MeasureParams{"
11324                + Integer.toHexString(System.identityHashCode(this))
11325                + " " + mStats.packageName + "}";
11326        }
11327
11328        @Override
11329        void handleStartCopy() throws RemoteException {
11330            synchronized (mInstallLock) {
11331                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11332            }
11333
11334            if (mSuccess) {
11335                final boolean mounted;
11336                if (Environment.isExternalStorageEmulated()) {
11337                    mounted = true;
11338                } else {
11339                    final String status = Environment.getExternalStorageState();
11340                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11341                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11342                }
11343
11344                if (mounted) {
11345                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11346
11347                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11348                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11349
11350                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11351                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11352
11353                    // Always subtract cache size, since it's a subdirectory
11354                    mStats.externalDataSize -= mStats.externalCacheSize;
11355
11356                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11357                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11358
11359                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11360                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11361                }
11362            }
11363        }
11364
11365        @Override
11366        void handleReturnCode() {
11367            if (mObserver != null) {
11368                try {
11369                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11370                } catch (RemoteException e) {
11371                    Slog.i(TAG, "Observer no longer exists.");
11372                }
11373            }
11374        }
11375
11376        @Override
11377        void handleServiceError() {
11378            Slog.e(TAG, "Could not measure application " + mStats.packageName
11379                            + " external storage");
11380        }
11381    }
11382
11383    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11384            throws RemoteException {
11385        long result = 0;
11386        for (File path : paths) {
11387            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11388        }
11389        return result;
11390    }
11391
11392    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11393        for (File path : paths) {
11394            try {
11395                mcs.clearDirectory(path.getAbsolutePath());
11396            } catch (RemoteException e) {
11397            }
11398        }
11399    }
11400
11401    static class OriginInfo {
11402        /**
11403         * Location where install is coming from, before it has been
11404         * copied/renamed into place. This could be a single monolithic APK
11405         * file, or a cluster directory. This location may be untrusted.
11406         */
11407        final File file;
11408        final String cid;
11409
11410        /**
11411         * Flag indicating that {@link #file} or {@link #cid} has already been
11412         * staged, meaning downstream users don't need to defensively copy the
11413         * contents.
11414         */
11415        final boolean staged;
11416
11417        /**
11418         * Flag indicating that {@link #file} or {@link #cid} is an already
11419         * installed app that is being moved.
11420         */
11421        final boolean existing;
11422
11423        final String resolvedPath;
11424        final File resolvedFile;
11425
11426        static OriginInfo fromNothing() {
11427            return new OriginInfo(null, null, false, false);
11428        }
11429
11430        static OriginInfo fromUntrustedFile(File file) {
11431            return new OriginInfo(file, null, false, false);
11432        }
11433
11434        static OriginInfo fromExistingFile(File file) {
11435            return new OriginInfo(file, null, false, true);
11436        }
11437
11438        static OriginInfo fromStagedFile(File file) {
11439            return new OriginInfo(file, null, true, false);
11440        }
11441
11442        static OriginInfo fromStagedContainer(String cid) {
11443            return new OriginInfo(null, cid, true, false);
11444        }
11445
11446        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11447            this.file = file;
11448            this.cid = cid;
11449            this.staged = staged;
11450            this.existing = existing;
11451
11452            if (cid != null) {
11453                resolvedPath = PackageHelper.getSdDir(cid);
11454                resolvedFile = new File(resolvedPath);
11455            } else if (file != null) {
11456                resolvedPath = file.getAbsolutePath();
11457                resolvedFile = file;
11458            } else {
11459                resolvedPath = null;
11460                resolvedFile = null;
11461            }
11462        }
11463    }
11464
11465    static class MoveInfo {
11466        final int moveId;
11467        final String fromUuid;
11468        final String toUuid;
11469        final String packageName;
11470        final String dataAppName;
11471        final int appId;
11472        final String seinfo;
11473        final int targetSdkVersion;
11474
11475        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11476                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11477            this.moveId = moveId;
11478            this.fromUuid = fromUuid;
11479            this.toUuid = toUuid;
11480            this.packageName = packageName;
11481            this.dataAppName = dataAppName;
11482            this.appId = appId;
11483            this.seinfo = seinfo;
11484            this.targetSdkVersion = targetSdkVersion;
11485        }
11486    }
11487
11488    class InstallParams extends HandlerParams {
11489        final OriginInfo origin;
11490        final MoveInfo move;
11491        final IPackageInstallObserver2 observer;
11492        int installFlags;
11493        final String installerPackageName;
11494        final String volumeUuid;
11495        final VerificationParams verificationParams;
11496        private InstallArgs mArgs;
11497        private int mRet;
11498        final String packageAbiOverride;
11499        final String[] grantedRuntimePermissions;
11500
11501        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11502                int installFlags, String installerPackageName, String volumeUuid,
11503                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11504                String[] grantedPermissions) {
11505            super(user);
11506            this.origin = origin;
11507            this.move = move;
11508            this.observer = observer;
11509            this.installFlags = installFlags;
11510            this.installerPackageName = installerPackageName;
11511            this.volumeUuid = volumeUuid;
11512            this.verificationParams = verificationParams;
11513            this.packageAbiOverride = packageAbiOverride;
11514            this.grantedRuntimePermissions = grantedPermissions;
11515        }
11516
11517        @Override
11518        public String toString() {
11519            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11520                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11521        }
11522
11523        private int installLocationPolicy(PackageInfoLite pkgLite) {
11524            String packageName = pkgLite.packageName;
11525            int installLocation = pkgLite.installLocation;
11526            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11527            // reader
11528            synchronized (mPackages) {
11529                PackageParser.Package pkg = mPackages.get(packageName);
11530                if (pkg != null) {
11531                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11532                        // Check for downgrading.
11533                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11534                            try {
11535                                checkDowngrade(pkg, pkgLite);
11536                            } catch (PackageManagerException e) {
11537                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11538                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11539                            }
11540                        }
11541                        // Check for updated system application.
11542                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11543                            if (onSd) {
11544                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11545                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11546                            }
11547                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11548                        } else {
11549                            if (onSd) {
11550                                // Install flag overrides everything.
11551                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11552                            }
11553                            // If current upgrade specifies particular preference
11554                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11555                                // Application explicitly specified internal.
11556                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11557                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11558                                // App explictly prefers external. Let policy decide
11559                            } else {
11560                                // Prefer previous location
11561                                if (isExternal(pkg)) {
11562                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11563                                }
11564                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11565                            }
11566                        }
11567                    } else {
11568                        // Invalid install. Return error code
11569                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11570                    }
11571                }
11572            }
11573            // All the special cases have been taken care of.
11574            // Return result based on recommended install location.
11575            if (onSd) {
11576                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11577            }
11578            return pkgLite.recommendedInstallLocation;
11579        }
11580
11581        /*
11582         * Invoke remote method to get package information and install
11583         * location values. Override install location based on default
11584         * policy if needed and then create install arguments based
11585         * on the install location.
11586         */
11587        public void handleStartCopy() throws RemoteException {
11588            int ret = PackageManager.INSTALL_SUCCEEDED;
11589
11590            // If we're already staged, we've firmly committed to an install location
11591            if (origin.staged) {
11592                if (origin.file != null) {
11593                    installFlags |= PackageManager.INSTALL_INTERNAL;
11594                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11595                } else if (origin.cid != null) {
11596                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11597                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11598                } else {
11599                    throw new IllegalStateException("Invalid stage location");
11600                }
11601            }
11602
11603            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11604            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11605            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11606            PackageInfoLite pkgLite = null;
11607
11608            if (onInt && onSd) {
11609                // Check if both bits are set.
11610                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11611                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11612            } else if (onSd && ephemeral) {
11613                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11614                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11615            } else {
11616                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11617                        packageAbiOverride);
11618
11619                if (DEBUG_EPHEMERAL && ephemeral) {
11620                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11621                }
11622
11623                /*
11624                 * If we have too little free space, try to free cache
11625                 * before giving up.
11626                 */
11627                if (!origin.staged && pkgLite.recommendedInstallLocation
11628                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11629                    // TODO: focus freeing disk space on the target device
11630                    final StorageManager storage = StorageManager.from(mContext);
11631                    final long lowThreshold = storage.getStorageLowBytes(
11632                            Environment.getDataDirectory());
11633
11634                    final long sizeBytes = mContainerService.calculateInstalledSize(
11635                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11636
11637                    try {
11638                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11639                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11640                                installFlags, packageAbiOverride);
11641                    } catch (InstallerException e) {
11642                        Slog.w(TAG, "Failed to free cache", e);
11643                    }
11644
11645                    /*
11646                     * The cache free must have deleted the file we
11647                     * downloaded to install.
11648                     *
11649                     * TODO: fix the "freeCache" call to not delete
11650                     *       the file we care about.
11651                     */
11652                    if (pkgLite.recommendedInstallLocation
11653                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11654                        pkgLite.recommendedInstallLocation
11655                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11656                    }
11657                }
11658            }
11659
11660            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11661                int loc = pkgLite.recommendedInstallLocation;
11662                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11663                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11664                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11665                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11666                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11667                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11668                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11669                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11670                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11671                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11672                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11673                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11674                } else {
11675                    // Override with defaults if needed.
11676                    loc = installLocationPolicy(pkgLite);
11677                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11678                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11679                    } else if (!onSd && !onInt) {
11680                        // Override install location with flags
11681                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11682                            // Set the flag to install on external media.
11683                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11684                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11685                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11686                            if (DEBUG_EPHEMERAL) {
11687                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11688                            }
11689                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11690                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11691                                    |PackageManager.INSTALL_INTERNAL);
11692                        } else {
11693                            // Make sure the flag for installing on external
11694                            // media is unset
11695                            installFlags |= PackageManager.INSTALL_INTERNAL;
11696                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11697                        }
11698                    }
11699                }
11700            }
11701
11702            final InstallArgs args = createInstallArgs(this);
11703            mArgs = args;
11704
11705            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11706                // TODO: http://b/22976637
11707                // Apps installed for "all" users use the device owner to verify the app
11708                UserHandle verifierUser = getUser();
11709                if (verifierUser == UserHandle.ALL) {
11710                    verifierUser = UserHandle.SYSTEM;
11711                }
11712
11713                /*
11714                 * Determine if we have any installed package verifiers. If we
11715                 * do, then we'll defer to them to verify the packages.
11716                 */
11717                final int requiredUid = mRequiredVerifierPackage == null ? -1
11718                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11719                                verifierUser.getIdentifier());
11720                if (!origin.existing && requiredUid != -1
11721                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11722                    final Intent verification = new Intent(
11723                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11724                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11725                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11726                            PACKAGE_MIME_TYPE);
11727                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11728
11729                    // Query all live verifiers based on current user state
11730                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11731                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11732
11733                    if (DEBUG_VERIFY) {
11734                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11735                                + verification.toString() + " with " + pkgLite.verifiers.length
11736                                + " optional verifiers");
11737                    }
11738
11739                    final int verificationId = mPendingVerificationToken++;
11740
11741                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11742
11743                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11744                            installerPackageName);
11745
11746                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11747                            installFlags);
11748
11749                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11750                            pkgLite.packageName);
11751
11752                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11753                            pkgLite.versionCode);
11754
11755                    if (verificationParams != null) {
11756                        if (verificationParams.getVerificationURI() != null) {
11757                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11758                                 verificationParams.getVerificationURI());
11759                        }
11760                        if (verificationParams.getOriginatingURI() != null) {
11761                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11762                                  verificationParams.getOriginatingURI());
11763                        }
11764                        if (verificationParams.getReferrer() != null) {
11765                            verification.putExtra(Intent.EXTRA_REFERRER,
11766                                  verificationParams.getReferrer());
11767                        }
11768                        if (verificationParams.getOriginatingUid() >= 0) {
11769                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11770                                  verificationParams.getOriginatingUid());
11771                        }
11772                        if (verificationParams.getInstallerUid() >= 0) {
11773                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11774                                  verificationParams.getInstallerUid());
11775                        }
11776                    }
11777
11778                    final PackageVerificationState verificationState = new PackageVerificationState(
11779                            requiredUid, args);
11780
11781                    mPendingVerification.append(verificationId, verificationState);
11782
11783                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11784                            receivers, verificationState);
11785
11786                    /*
11787                     * If any sufficient verifiers were listed in the package
11788                     * manifest, attempt to ask them.
11789                     */
11790                    if (sufficientVerifiers != null) {
11791                        final int N = sufficientVerifiers.size();
11792                        if (N == 0) {
11793                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11794                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11795                        } else {
11796                            for (int i = 0; i < N; i++) {
11797                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11798
11799                                final Intent sufficientIntent = new Intent(verification);
11800                                sufficientIntent.setComponent(verifierComponent);
11801                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11802                            }
11803                        }
11804                    }
11805
11806                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11807                            mRequiredVerifierPackage, receivers);
11808                    if (ret == PackageManager.INSTALL_SUCCEEDED
11809                            && mRequiredVerifierPackage != null) {
11810                        Trace.asyncTraceBegin(
11811                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11812                        /*
11813                         * Send the intent to the required verification agent,
11814                         * but only start the verification timeout after the
11815                         * target BroadcastReceivers have run.
11816                         */
11817                        verification.setComponent(requiredVerifierComponent);
11818                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11819                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11820                                new BroadcastReceiver() {
11821                                    @Override
11822                                    public void onReceive(Context context, Intent intent) {
11823                                        final Message msg = mHandler
11824                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11825                                        msg.arg1 = verificationId;
11826                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11827                                    }
11828                                }, null, 0, null, null);
11829
11830                        /*
11831                         * We don't want the copy to proceed until verification
11832                         * succeeds, so null out this field.
11833                         */
11834                        mArgs = null;
11835                    }
11836                } else {
11837                    /*
11838                     * No package verification is enabled, so immediately start
11839                     * the remote call to initiate copy using temporary file.
11840                     */
11841                    ret = args.copyApk(mContainerService, true);
11842                }
11843            }
11844
11845            mRet = ret;
11846        }
11847
11848        @Override
11849        void handleReturnCode() {
11850            // If mArgs is null, then MCS couldn't be reached. When it
11851            // reconnects, it will try again to install. At that point, this
11852            // will succeed.
11853            if (mArgs != null) {
11854                processPendingInstall(mArgs, mRet);
11855            }
11856        }
11857
11858        @Override
11859        void handleServiceError() {
11860            mArgs = createInstallArgs(this);
11861            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11862        }
11863
11864        public boolean isForwardLocked() {
11865            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11866        }
11867    }
11868
11869    /**
11870     * Used during creation of InstallArgs
11871     *
11872     * @param installFlags package installation flags
11873     * @return true if should be installed on external storage
11874     */
11875    private static boolean installOnExternalAsec(int installFlags) {
11876        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11877            return false;
11878        }
11879        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11880            return true;
11881        }
11882        return false;
11883    }
11884
11885    /**
11886     * Used during creation of InstallArgs
11887     *
11888     * @param installFlags package installation flags
11889     * @return true if should be installed as forward locked
11890     */
11891    private static boolean installForwardLocked(int installFlags) {
11892        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11893    }
11894
11895    private InstallArgs createInstallArgs(InstallParams params) {
11896        if (params.move != null) {
11897            return new MoveInstallArgs(params);
11898        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11899            return new AsecInstallArgs(params);
11900        } else {
11901            return new FileInstallArgs(params);
11902        }
11903    }
11904
11905    /**
11906     * Create args that describe an existing installed package. Typically used
11907     * when cleaning up old installs, or used as a move source.
11908     */
11909    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11910            String resourcePath, String[] instructionSets) {
11911        final boolean isInAsec;
11912        if (installOnExternalAsec(installFlags)) {
11913            /* Apps on SD card are always in ASEC containers. */
11914            isInAsec = true;
11915        } else if (installForwardLocked(installFlags)
11916                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11917            /*
11918             * Forward-locked apps are only in ASEC containers if they're the
11919             * new style
11920             */
11921            isInAsec = true;
11922        } else {
11923            isInAsec = false;
11924        }
11925
11926        if (isInAsec) {
11927            return new AsecInstallArgs(codePath, instructionSets,
11928                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11929        } else {
11930            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11931        }
11932    }
11933
11934    static abstract class InstallArgs {
11935        /** @see InstallParams#origin */
11936        final OriginInfo origin;
11937        /** @see InstallParams#move */
11938        final MoveInfo move;
11939
11940        final IPackageInstallObserver2 observer;
11941        // Always refers to PackageManager flags only
11942        final int installFlags;
11943        final String installerPackageName;
11944        final String volumeUuid;
11945        final UserHandle user;
11946        final String abiOverride;
11947        final String[] installGrantPermissions;
11948        /** If non-null, drop an async trace when the install completes */
11949        final String traceMethod;
11950        final int traceCookie;
11951
11952        // The list of instruction sets supported by this app. This is currently
11953        // only used during the rmdex() phase to clean up resources. We can get rid of this
11954        // if we move dex files under the common app path.
11955        /* nullable */ String[] instructionSets;
11956
11957        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11958                int installFlags, String installerPackageName, String volumeUuid,
11959                UserHandle user, String[] instructionSets,
11960                String abiOverride, String[] installGrantPermissions,
11961                String traceMethod, int traceCookie) {
11962            this.origin = origin;
11963            this.move = move;
11964            this.installFlags = installFlags;
11965            this.observer = observer;
11966            this.installerPackageName = installerPackageName;
11967            this.volumeUuid = volumeUuid;
11968            this.user = user;
11969            this.instructionSets = instructionSets;
11970            this.abiOverride = abiOverride;
11971            this.installGrantPermissions = installGrantPermissions;
11972            this.traceMethod = traceMethod;
11973            this.traceCookie = traceCookie;
11974        }
11975
11976        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11977        abstract int doPreInstall(int status);
11978
11979        /**
11980         * Rename package into final resting place. All paths on the given
11981         * scanned package should be updated to reflect the rename.
11982         */
11983        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11984        abstract int doPostInstall(int status, int uid);
11985
11986        /** @see PackageSettingBase#codePathString */
11987        abstract String getCodePath();
11988        /** @see PackageSettingBase#resourcePathString */
11989        abstract String getResourcePath();
11990
11991        // Need installer lock especially for dex file removal.
11992        abstract void cleanUpResourcesLI();
11993        abstract boolean doPostDeleteLI(boolean delete);
11994
11995        /**
11996         * Called before the source arguments are copied. This is used mostly
11997         * for MoveParams when it needs to read the source file to put it in the
11998         * destination.
11999         */
12000        int doPreCopy() {
12001            return PackageManager.INSTALL_SUCCEEDED;
12002        }
12003
12004        /**
12005         * Called after the source arguments are copied. This is used mostly for
12006         * MoveParams when it needs to read the source file to put it in the
12007         * destination.
12008         *
12009         * @return
12010         */
12011        int doPostCopy(int uid) {
12012            return PackageManager.INSTALL_SUCCEEDED;
12013        }
12014
12015        protected boolean isFwdLocked() {
12016            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12017        }
12018
12019        protected boolean isExternalAsec() {
12020            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12021        }
12022
12023        protected boolean isEphemeral() {
12024            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12025        }
12026
12027        UserHandle getUser() {
12028            return user;
12029        }
12030    }
12031
12032    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12033        if (!allCodePaths.isEmpty()) {
12034            if (instructionSets == null) {
12035                throw new IllegalStateException("instructionSet == null");
12036            }
12037            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12038            for (String codePath : allCodePaths) {
12039                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12040                    try {
12041                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12042                    } catch (InstallerException ignored) {
12043                    }
12044                }
12045            }
12046        }
12047    }
12048
12049    /**
12050     * Logic to handle installation of non-ASEC applications, including copying
12051     * and renaming logic.
12052     */
12053    class FileInstallArgs extends InstallArgs {
12054        private File codeFile;
12055        private File resourceFile;
12056
12057        // Example topology:
12058        // /data/app/com.example/base.apk
12059        // /data/app/com.example/split_foo.apk
12060        // /data/app/com.example/lib/arm/libfoo.so
12061        // /data/app/com.example/lib/arm64/libfoo.so
12062        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12063
12064        /** New install */
12065        FileInstallArgs(InstallParams params) {
12066            super(params.origin, params.move, params.observer, params.installFlags,
12067                    params.installerPackageName, params.volumeUuid,
12068                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12069                    params.grantedRuntimePermissions,
12070                    params.traceMethod, params.traceCookie);
12071            if (isFwdLocked()) {
12072                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12073            }
12074        }
12075
12076        /** Existing install */
12077        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12078            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12079                    null, null, null, 0);
12080            this.codeFile = (codePath != null) ? new File(codePath) : null;
12081            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12082        }
12083
12084        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12085            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12086            try {
12087                return doCopyApk(imcs, temp);
12088            } finally {
12089                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12090            }
12091        }
12092
12093        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12094            if (origin.staged) {
12095                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12096                codeFile = origin.file;
12097                resourceFile = origin.file;
12098                return PackageManager.INSTALL_SUCCEEDED;
12099            }
12100
12101            try {
12102                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12103                final File tempDir =
12104                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12105                codeFile = tempDir;
12106                resourceFile = tempDir;
12107            } catch (IOException e) {
12108                Slog.w(TAG, "Failed to create copy file: " + e);
12109                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12110            }
12111
12112            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12113                @Override
12114                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12115                    if (!FileUtils.isValidExtFilename(name)) {
12116                        throw new IllegalArgumentException("Invalid filename: " + name);
12117                    }
12118                    try {
12119                        final File file = new File(codeFile, name);
12120                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12121                                O_RDWR | O_CREAT, 0644);
12122                        Os.chmod(file.getAbsolutePath(), 0644);
12123                        return new ParcelFileDescriptor(fd);
12124                    } catch (ErrnoException e) {
12125                        throw new RemoteException("Failed to open: " + e.getMessage());
12126                    }
12127                }
12128            };
12129
12130            int ret = PackageManager.INSTALL_SUCCEEDED;
12131            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12132            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12133                Slog.e(TAG, "Failed to copy package");
12134                return ret;
12135            }
12136
12137            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12138            NativeLibraryHelper.Handle handle = null;
12139            try {
12140                handle = NativeLibraryHelper.Handle.create(codeFile);
12141                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12142                        abiOverride);
12143            } catch (IOException e) {
12144                Slog.e(TAG, "Copying native libraries failed", e);
12145                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12146            } finally {
12147                IoUtils.closeQuietly(handle);
12148            }
12149
12150            return ret;
12151        }
12152
12153        int doPreInstall(int status) {
12154            if (status != PackageManager.INSTALL_SUCCEEDED) {
12155                cleanUp();
12156            }
12157            return status;
12158        }
12159
12160        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12161            if (status != PackageManager.INSTALL_SUCCEEDED) {
12162                cleanUp();
12163                return false;
12164            }
12165
12166            final File targetDir = codeFile.getParentFile();
12167            final File beforeCodeFile = codeFile;
12168            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12169
12170            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12171            try {
12172                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12173            } catch (ErrnoException e) {
12174                Slog.w(TAG, "Failed to rename", e);
12175                return false;
12176            }
12177
12178            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12179                Slog.w(TAG, "Failed to restorecon");
12180                return false;
12181            }
12182
12183            // Reflect the rename internally
12184            codeFile = afterCodeFile;
12185            resourceFile = afterCodeFile;
12186
12187            // Reflect the rename in scanned details
12188            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12189            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12190                    afterCodeFile, pkg.baseCodePath));
12191            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12192                    afterCodeFile, pkg.splitCodePaths));
12193
12194            // Reflect the rename in app info
12195            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12196            pkg.setApplicationInfoCodePath(pkg.codePath);
12197            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12198            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12199            pkg.setApplicationInfoResourcePath(pkg.codePath);
12200            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12201            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12202
12203            return true;
12204        }
12205
12206        int doPostInstall(int status, int uid) {
12207            if (status != PackageManager.INSTALL_SUCCEEDED) {
12208                cleanUp();
12209            }
12210            return status;
12211        }
12212
12213        @Override
12214        String getCodePath() {
12215            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12216        }
12217
12218        @Override
12219        String getResourcePath() {
12220            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12221        }
12222
12223        private boolean cleanUp() {
12224            if (codeFile == null || !codeFile.exists()) {
12225                return false;
12226            }
12227
12228            removeCodePathLI(codeFile);
12229
12230            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12231                resourceFile.delete();
12232            }
12233
12234            return true;
12235        }
12236
12237        void cleanUpResourcesLI() {
12238            // Try enumerating all code paths before deleting
12239            List<String> allCodePaths = Collections.EMPTY_LIST;
12240            if (codeFile != null && codeFile.exists()) {
12241                try {
12242                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12243                    allCodePaths = pkg.getAllCodePaths();
12244                } catch (PackageParserException e) {
12245                    // Ignored; we tried our best
12246                }
12247            }
12248
12249            cleanUp();
12250            removeDexFiles(allCodePaths, instructionSets);
12251        }
12252
12253        boolean doPostDeleteLI(boolean delete) {
12254            // XXX err, shouldn't we respect the delete flag?
12255            cleanUpResourcesLI();
12256            return true;
12257        }
12258    }
12259
12260    private boolean isAsecExternal(String cid) {
12261        final String asecPath = PackageHelper.getSdFilesystem(cid);
12262        return !asecPath.startsWith(mAsecInternalPath);
12263    }
12264
12265    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12266            PackageManagerException {
12267        if (copyRet < 0) {
12268            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12269                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12270                throw new PackageManagerException(copyRet, message);
12271            }
12272        }
12273    }
12274
12275    /**
12276     * Extract the MountService "container ID" from the full code path of an
12277     * .apk.
12278     */
12279    static String cidFromCodePath(String fullCodePath) {
12280        int eidx = fullCodePath.lastIndexOf("/");
12281        String subStr1 = fullCodePath.substring(0, eidx);
12282        int sidx = subStr1.lastIndexOf("/");
12283        return subStr1.substring(sidx+1, eidx);
12284    }
12285
12286    /**
12287     * Logic to handle installation of ASEC applications, including copying and
12288     * renaming logic.
12289     */
12290    class AsecInstallArgs extends InstallArgs {
12291        static final String RES_FILE_NAME = "pkg.apk";
12292        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12293
12294        String cid;
12295        String packagePath;
12296        String resourcePath;
12297
12298        /** New install */
12299        AsecInstallArgs(InstallParams params) {
12300            super(params.origin, params.move, params.observer, params.installFlags,
12301                    params.installerPackageName, params.volumeUuid,
12302                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12303                    params.grantedRuntimePermissions,
12304                    params.traceMethod, params.traceCookie);
12305        }
12306
12307        /** Existing install */
12308        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12309                        boolean isExternal, boolean isForwardLocked) {
12310            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12311                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12312                    instructionSets, null, null, null, 0);
12313            // Hackily pretend we're still looking at a full code path
12314            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12315                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12316            }
12317
12318            // Extract cid from fullCodePath
12319            int eidx = fullCodePath.lastIndexOf("/");
12320            String subStr1 = fullCodePath.substring(0, eidx);
12321            int sidx = subStr1.lastIndexOf("/");
12322            cid = subStr1.substring(sidx+1, eidx);
12323            setMountPath(subStr1);
12324        }
12325
12326        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12327            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12328                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12329                    instructionSets, null, null, null, 0);
12330            this.cid = cid;
12331            setMountPath(PackageHelper.getSdDir(cid));
12332        }
12333
12334        void createCopyFile() {
12335            cid = mInstallerService.allocateExternalStageCidLegacy();
12336        }
12337
12338        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12339            if (origin.staged && origin.cid != null) {
12340                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12341                cid = origin.cid;
12342                setMountPath(PackageHelper.getSdDir(cid));
12343                return PackageManager.INSTALL_SUCCEEDED;
12344            }
12345
12346            if (temp) {
12347                createCopyFile();
12348            } else {
12349                /*
12350                 * Pre-emptively destroy the container since it's destroyed if
12351                 * copying fails due to it existing anyway.
12352                 */
12353                PackageHelper.destroySdDir(cid);
12354            }
12355
12356            final String newMountPath = imcs.copyPackageToContainer(
12357                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12358                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12359
12360            if (newMountPath != null) {
12361                setMountPath(newMountPath);
12362                return PackageManager.INSTALL_SUCCEEDED;
12363            } else {
12364                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12365            }
12366        }
12367
12368        @Override
12369        String getCodePath() {
12370            return packagePath;
12371        }
12372
12373        @Override
12374        String getResourcePath() {
12375            return resourcePath;
12376        }
12377
12378        int doPreInstall(int status) {
12379            if (status != PackageManager.INSTALL_SUCCEEDED) {
12380                // Destroy container
12381                PackageHelper.destroySdDir(cid);
12382            } else {
12383                boolean mounted = PackageHelper.isContainerMounted(cid);
12384                if (!mounted) {
12385                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12386                            Process.SYSTEM_UID);
12387                    if (newMountPath != null) {
12388                        setMountPath(newMountPath);
12389                    } else {
12390                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12391                    }
12392                }
12393            }
12394            return status;
12395        }
12396
12397        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12398            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12399            String newMountPath = null;
12400            if (PackageHelper.isContainerMounted(cid)) {
12401                // Unmount the container
12402                if (!PackageHelper.unMountSdDir(cid)) {
12403                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12404                    return false;
12405                }
12406            }
12407            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12408                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12409                        " which might be stale. Will try to clean up.");
12410                // Clean up the stale container and proceed to recreate.
12411                if (!PackageHelper.destroySdDir(newCacheId)) {
12412                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12413                    return false;
12414                }
12415                // Successfully cleaned up stale container. Try to rename again.
12416                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12417                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12418                            + " inspite of cleaning it up.");
12419                    return false;
12420                }
12421            }
12422            if (!PackageHelper.isContainerMounted(newCacheId)) {
12423                Slog.w(TAG, "Mounting container " + newCacheId);
12424                newMountPath = PackageHelper.mountSdDir(newCacheId,
12425                        getEncryptKey(), Process.SYSTEM_UID);
12426            } else {
12427                newMountPath = PackageHelper.getSdDir(newCacheId);
12428            }
12429            if (newMountPath == null) {
12430                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12431                return false;
12432            }
12433            Log.i(TAG, "Succesfully renamed " + cid +
12434                    " to " + newCacheId +
12435                    " at new path: " + newMountPath);
12436            cid = newCacheId;
12437
12438            final File beforeCodeFile = new File(packagePath);
12439            setMountPath(newMountPath);
12440            final File afterCodeFile = new File(packagePath);
12441
12442            // Reflect the rename in scanned details
12443            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12444            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12445                    afterCodeFile, pkg.baseCodePath));
12446            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12447                    afterCodeFile, pkg.splitCodePaths));
12448
12449            // Reflect the rename in app info
12450            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12451            pkg.setApplicationInfoCodePath(pkg.codePath);
12452            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12453            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12454            pkg.setApplicationInfoResourcePath(pkg.codePath);
12455            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12456            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12457
12458            return true;
12459        }
12460
12461        private void setMountPath(String mountPath) {
12462            final File mountFile = new File(mountPath);
12463
12464            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12465            if (monolithicFile.exists()) {
12466                packagePath = monolithicFile.getAbsolutePath();
12467                if (isFwdLocked()) {
12468                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12469                } else {
12470                    resourcePath = packagePath;
12471                }
12472            } else {
12473                packagePath = mountFile.getAbsolutePath();
12474                resourcePath = packagePath;
12475            }
12476        }
12477
12478        int doPostInstall(int status, int uid) {
12479            if (status != PackageManager.INSTALL_SUCCEEDED) {
12480                cleanUp();
12481            } else {
12482                final int groupOwner;
12483                final String protectedFile;
12484                if (isFwdLocked()) {
12485                    groupOwner = UserHandle.getSharedAppGid(uid);
12486                    protectedFile = RES_FILE_NAME;
12487                } else {
12488                    groupOwner = -1;
12489                    protectedFile = null;
12490                }
12491
12492                if (uid < Process.FIRST_APPLICATION_UID
12493                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12494                    Slog.e(TAG, "Failed to finalize " + cid);
12495                    PackageHelper.destroySdDir(cid);
12496                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12497                }
12498
12499                boolean mounted = PackageHelper.isContainerMounted(cid);
12500                if (!mounted) {
12501                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12502                }
12503            }
12504            return status;
12505        }
12506
12507        private void cleanUp() {
12508            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12509
12510            // Destroy secure container
12511            PackageHelper.destroySdDir(cid);
12512        }
12513
12514        private List<String> getAllCodePaths() {
12515            final File codeFile = new File(getCodePath());
12516            if (codeFile != null && codeFile.exists()) {
12517                try {
12518                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12519                    return pkg.getAllCodePaths();
12520                } catch (PackageParserException e) {
12521                    // Ignored; we tried our best
12522                }
12523            }
12524            return Collections.EMPTY_LIST;
12525        }
12526
12527        void cleanUpResourcesLI() {
12528            // Enumerate all code paths before deleting
12529            cleanUpResourcesLI(getAllCodePaths());
12530        }
12531
12532        private void cleanUpResourcesLI(List<String> allCodePaths) {
12533            cleanUp();
12534            removeDexFiles(allCodePaths, instructionSets);
12535        }
12536
12537        String getPackageName() {
12538            return getAsecPackageName(cid);
12539        }
12540
12541        boolean doPostDeleteLI(boolean delete) {
12542            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12543            final List<String> allCodePaths = getAllCodePaths();
12544            boolean mounted = PackageHelper.isContainerMounted(cid);
12545            if (mounted) {
12546                // Unmount first
12547                if (PackageHelper.unMountSdDir(cid)) {
12548                    mounted = false;
12549                }
12550            }
12551            if (!mounted && delete) {
12552                cleanUpResourcesLI(allCodePaths);
12553            }
12554            return !mounted;
12555        }
12556
12557        @Override
12558        int doPreCopy() {
12559            if (isFwdLocked()) {
12560                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12561                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12562                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12563                }
12564            }
12565
12566            return PackageManager.INSTALL_SUCCEEDED;
12567        }
12568
12569        @Override
12570        int doPostCopy(int uid) {
12571            if (isFwdLocked()) {
12572                if (uid < Process.FIRST_APPLICATION_UID
12573                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12574                                RES_FILE_NAME)) {
12575                    Slog.e(TAG, "Failed to finalize " + cid);
12576                    PackageHelper.destroySdDir(cid);
12577                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12578                }
12579            }
12580
12581            return PackageManager.INSTALL_SUCCEEDED;
12582        }
12583    }
12584
12585    /**
12586     * Logic to handle movement of existing installed applications.
12587     */
12588    class MoveInstallArgs extends InstallArgs {
12589        private File codeFile;
12590        private File resourceFile;
12591
12592        /** New install */
12593        MoveInstallArgs(InstallParams params) {
12594            super(params.origin, params.move, params.observer, params.installFlags,
12595                    params.installerPackageName, params.volumeUuid,
12596                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12597                    params.grantedRuntimePermissions,
12598                    params.traceMethod, params.traceCookie);
12599        }
12600
12601        int copyApk(IMediaContainerService imcs, boolean temp) {
12602            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12603                    + move.fromUuid + " to " + move.toUuid);
12604            synchronized (mInstaller) {
12605                try {
12606                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12607                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12608                } catch (InstallerException e) {
12609                    Slog.w(TAG, "Failed to move app", e);
12610                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12611                }
12612            }
12613
12614            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12615            resourceFile = codeFile;
12616            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12617
12618            return PackageManager.INSTALL_SUCCEEDED;
12619        }
12620
12621        int doPreInstall(int status) {
12622            if (status != PackageManager.INSTALL_SUCCEEDED) {
12623                cleanUp(move.toUuid);
12624            }
12625            return status;
12626        }
12627
12628        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12629            if (status != PackageManager.INSTALL_SUCCEEDED) {
12630                cleanUp(move.toUuid);
12631                return false;
12632            }
12633
12634            // Reflect the move in app info
12635            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12636            pkg.setApplicationInfoCodePath(pkg.codePath);
12637            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12638            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12639            pkg.setApplicationInfoResourcePath(pkg.codePath);
12640            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12641            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12642
12643            return true;
12644        }
12645
12646        int doPostInstall(int status, int uid) {
12647            if (status == PackageManager.INSTALL_SUCCEEDED) {
12648                cleanUp(move.fromUuid);
12649            } else {
12650                cleanUp(move.toUuid);
12651            }
12652            return status;
12653        }
12654
12655        @Override
12656        String getCodePath() {
12657            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12658        }
12659
12660        @Override
12661        String getResourcePath() {
12662            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12663        }
12664
12665        private boolean cleanUp(String volumeUuid) {
12666            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12667                    move.dataAppName);
12668            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12669            synchronized (mInstallLock) {
12670                // Clean up both app data and code
12671                removeDataDirsLI(volumeUuid, move.packageName);
12672                removeCodePathLI(codeFile);
12673            }
12674            return true;
12675        }
12676
12677        void cleanUpResourcesLI() {
12678            throw new UnsupportedOperationException();
12679        }
12680
12681        boolean doPostDeleteLI(boolean delete) {
12682            throw new UnsupportedOperationException();
12683        }
12684    }
12685
12686    static String getAsecPackageName(String packageCid) {
12687        int idx = packageCid.lastIndexOf("-");
12688        if (idx == -1) {
12689            return packageCid;
12690        }
12691        return packageCid.substring(0, idx);
12692    }
12693
12694    // Utility method used to create code paths based on package name and available index.
12695    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12696        String idxStr = "";
12697        int idx = 1;
12698        // Fall back to default value of idx=1 if prefix is not
12699        // part of oldCodePath
12700        if (oldCodePath != null) {
12701            String subStr = oldCodePath;
12702            // Drop the suffix right away
12703            if (suffix != null && subStr.endsWith(suffix)) {
12704                subStr = subStr.substring(0, subStr.length() - suffix.length());
12705            }
12706            // If oldCodePath already contains prefix find out the
12707            // ending index to either increment or decrement.
12708            int sidx = subStr.lastIndexOf(prefix);
12709            if (sidx != -1) {
12710                subStr = subStr.substring(sidx + prefix.length());
12711                if (subStr != null) {
12712                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12713                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12714                    }
12715                    try {
12716                        idx = Integer.parseInt(subStr);
12717                        if (idx <= 1) {
12718                            idx++;
12719                        } else {
12720                            idx--;
12721                        }
12722                    } catch(NumberFormatException e) {
12723                    }
12724                }
12725            }
12726        }
12727        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12728        return prefix + idxStr;
12729    }
12730
12731    private File getNextCodePath(File targetDir, String packageName) {
12732        int suffix = 1;
12733        File result;
12734        do {
12735            result = new File(targetDir, packageName + "-" + suffix);
12736            suffix++;
12737        } while (result.exists());
12738        return result;
12739    }
12740
12741    // Utility method that returns the relative package path with respect
12742    // to the installation directory. Like say for /data/data/com.test-1.apk
12743    // string com.test-1 is returned.
12744    static String deriveCodePathName(String codePath) {
12745        if (codePath == null) {
12746            return null;
12747        }
12748        final File codeFile = new File(codePath);
12749        final String name = codeFile.getName();
12750        if (codeFile.isDirectory()) {
12751            return name;
12752        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12753            final int lastDot = name.lastIndexOf('.');
12754            return name.substring(0, lastDot);
12755        } else {
12756            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12757            return null;
12758        }
12759    }
12760
12761    static class PackageInstalledInfo {
12762        String name;
12763        int uid;
12764        // The set of users that originally had this package installed.
12765        int[] origUsers;
12766        // The set of users that now have this package installed.
12767        int[] newUsers;
12768        PackageParser.Package pkg;
12769        int returnCode;
12770        String returnMsg;
12771        PackageRemovedInfo removedInfo;
12772        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12773
12774        public void setError(int code, String msg) {
12775            setReturnCode(code);
12776            setReturnMessage(msg);
12777            Slog.w(TAG, msg);
12778        }
12779
12780        public void setError(String msg, PackageParserException e) {
12781            setReturnCode(e.error);
12782            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12783            Slog.w(TAG, msg, e);
12784        }
12785
12786        public void setError(String msg, PackageManagerException e) {
12787            returnCode = e.error;
12788            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12789            Slog.w(TAG, msg, e);
12790        }
12791
12792        public void setReturnCode(int returnCode) {
12793            this.returnCode = returnCode;
12794            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12795            for (int i = 0; i < childCount; i++) {
12796                addedChildPackages.valueAt(i).returnCode = returnCode;
12797            }
12798        }
12799
12800        private void setReturnMessage(String returnMsg) {
12801            this.returnMsg = returnMsg;
12802            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12803            for (int i = 0; i < childCount; i++) {
12804                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12805            }
12806        }
12807
12808        // In some error cases we want to convey more info back to the observer
12809        String origPackage;
12810        String origPermission;
12811    }
12812
12813    /*
12814     * Install a non-existing package.
12815     */
12816    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12817            UserHandle user, String installerPackageName, String volumeUuid,
12818            PackageInstalledInfo res) {
12819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12820
12821        // Remember this for later, in case we need to rollback this install
12822        String pkgName = pkg.packageName;
12823
12824        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12825
12826        synchronized(mPackages) {
12827            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12828                // A package with the same name is already installed, though
12829                // it has been renamed to an older name.  The package we
12830                // are trying to install should be installed as an update to
12831                // the existing one, but that has not been requested, so bail.
12832                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12833                        + " without first uninstalling package running as "
12834                        + mSettings.mRenamedPackages.get(pkgName));
12835                return;
12836            }
12837            if (mPackages.containsKey(pkgName)) {
12838                // Don't allow installation over an existing package with the same name.
12839                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12840                        + " without first uninstalling.");
12841                return;
12842            }
12843        }
12844
12845        try {
12846            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12847                    System.currentTimeMillis(), user);
12848
12849            updateSettingsLI(newPackage, installerPackageName, null, res, user);
12850
12851            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12852                prepareAppDataAfterInstall(newPackage);
12853
12854            } else {
12855                // Remove package from internal structures, but keep around any
12856                // data that might have already existed
12857                deletePackageLI(pkgName, UserHandle.ALL, false, null,
12858                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
12859            }
12860        } catch (PackageManagerException e) {
12861            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12862        }
12863
12864        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12865    }
12866
12867    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12868        // Can't rotate keys during boot or if sharedUser.
12869        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12870                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12871            return false;
12872        }
12873        // app is using upgradeKeySets; make sure all are valid
12874        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12875        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12876        for (int i = 0; i < upgradeKeySets.length; i++) {
12877            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12878                Slog.wtf(TAG, "Package "
12879                         + (oldPs.name != null ? oldPs.name : "<null>")
12880                         + " contains upgrade-key-set reference to unknown key-set: "
12881                         + upgradeKeySets[i]
12882                         + " reverting to signatures check.");
12883                return false;
12884            }
12885        }
12886        return true;
12887    }
12888
12889    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12890        // Upgrade keysets are being used.  Determine if new package has a superset of the
12891        // required keys.
12892        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12893        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12894        for (int i = 0; i < upgradeKeySets.length; i++) {
12895            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12896            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12897                return true;
12898            }
12899        }
12900        return false;
12901    }
12902
12903    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12904            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
12905        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12906
12907        final PackageParser.Package oldPackage;
12908        final String pkgName = pkg.packageName;
12909        final int[] allUsers;
12910
12911        // First find the old package info and check signatures
12912        synchronized(mPackages) {
12913            oldPackage = mPackages.get(pkgName);
12914            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12915            if (isEphemeral && !oldIsEphemeral) {
12916                // can't downgrade from full to ephemeral
12917                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12918                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
12919                return;
12920            }
12921            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12922            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12923            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12924                if (!checkUpgradeKeySetLP(ps, pkg)) {
12925                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12926                            "New package not signed by keys specified by upgrade-keysets: "
12927                                    + pkgName);
12928                    return;
12929                }
12930            } else {
12931                // default to original signature matching
12932                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12933                        != PackageManager.SIGNATURE_MATCH) {
12934                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12935                            "New package has a different signature: " + pkgName);
12936                    return;
12937                }
12938            }
12939
12940            // In case of rollback, remember per-user/profile install state
12941            allUsers = sUserManager.getUserIds();
12942        }
12943
12944        // Update what is removed
12945        res.removedInfo = new PackageRemovedInfo();
12946        res.removedInfo.uid = oldPackage.applicationInfo.uid;
12947        res.removedInfo.removedPackage = oldPackage.packageName;
12948        res.removedInfo.isUpdate = true;
12949        final int childCount = (oldPackage.childPackages != null)
12950                ? oldPackage.childPackages.size() : 0;
12951        for (int i = 0; i < childCount; i++) {
12952            boolean childPackageUpdated = false;
12953            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
12954            if (res.addedChildPackages != null) {
12955                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
12956                if (childRes != null) {
12957                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
12958                    childRes.removedInfo.removedPackage = childPkg.packageName;
12959                    childRes.removedInfo.isUpdate = true;
12960                    childPackageUpdated = true;
12961                }
12962            }
12963            if (!childPackageUpdated) {
12964                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
12965                childRemovedRes.removedPackage = childPkg.packageName;
12966                childRemovedRes.isUpdate = false;
12967                childRemovedRes.dataRemoved = true;
12968                synchronized (mPackages) {
12969                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
12970                    if (childPs != null) {
12971                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
12972                    }
12973                }
12974                if (res.removedInfo.removedChildPackages == null) {
12975                    res.removedInfo.removedChildPackages = new ArrayMap<>();
12976                }
12977                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
12978            }
12979        }
12980
12981        boolean sysPkg = (isSystemApp(oldPackage));
12982        if (sysPkg) {
12983            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12984                    user, allUsers, installerPackageName, res);
12985        } else {
12986            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12987                    user, allUsers, installerPackageName, res);
12988        }
12989    }
12990
12991    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12992            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12993            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
12994        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12995                + deletedPackage);
12996
12997        String pkgName = deletedPackage.packageName;
12998        boolean deletedPkg = true;
12999        boolean addedPkg = false;
13000
13001        final long origUpdateTime = (pkg.mExtras != null)
13002                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13003
13004        // First delete the existing package while retaining the data directory
13005        if (!deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13006                res.removedInfo, true, pkg)) {
13007            // If the existing package wasn't successfully deleted
13008            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13009            deletedPkg = false;
13010        } else {
13011            // Successfully deleted the old package; proceed with replace.
13012
13013            // If deleted package lived in a container, give users a chance to
13014            // relinquish resources before killing.
13015            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13016                if (DEBUG_INSTALL) {
13017                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13018                }
13019                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13020                final ArrayList<String> pkgList = new ArrayList<String>(1);
13021                pkgList.add(deletedPackage.applicationInfo.packageName);
13022                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13023            }
13024
13025            deleteCodeCacheDirsLI(pkg);
13026
13027            try {
13028                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13029                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13030                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13031                prepareAppDataAfterInstall(newPackage);
13032                addedPkg = true;
13033            } catch (PackageManagerException e) {
13034                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13035            }
13036        }
13037
13038        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13039            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13040
13041            // Revert all internal state mutations and added folders for the failed install
13042            if (addedPkg) {
13043                deletePackageLI(pkgName, null, true, allUsers, PackageManager.DELETE_KEEP_DATA,
13044                        res.removedInfo, true, null);
13045            }
13046
13047            // Restore the old package
13048            if (deletedPkg) {
13049                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13050                File restoreFile = new File(deletedPackage.codePath);
13051                // Parse old package
13052                boolean oldExternal = isExternal(deletedPackage);
13053                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13054                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13055                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13056                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13057                try {
13058                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13059                            null);
13060                } catch (PackageManagerException e) {
13061                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13062                            + e.getMessage());
13063                    return;
13064                }
13065
13066                synchronized (mPackages) {
13067                    // Ensure the installer package name up to date
13068                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13069
13070                    // Update permissions for restored package
13071                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13072
13073                    mSettings.writeLPr();
13074                }
13075
13076                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13077            }
13078        } else {
13079            synchronized (mPackages) {
13080                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13081                if (ps != null) {
13082                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13083                    if (res.removedInfo.removedChildPackages != null) {
13084                        final int childCount = res.removedInfo.removedChildPackages.size();
13085                        // Iterate in reverse as we may modify the collection
13086                        for (int i = childCount - 1; i >= 0; i--) {
13087                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13088                            if (res.addedChildPackages.containsKey(childPackageName)) {
13089                                res.removedInfo.removedChildPackages.removeAt(i);
13090                            } else {
13091                                PackageRemovedInfo childInfo = res.removedInfo
13092                                        .removedChildPackages.valueAt(i);
13093                                childInfo.removedForAllUsers = mPackages.get(
13094                                        childInfo.removedPackage) == null;
13095                            }
13096                        }
13097                    }
13098                }
13099            }
13100        }
13101    }
13102
13103    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13104            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13105            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13106        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13107                + ", old=" + deletedPackage);
13108
13109        final boolean disabledSystem;
13110
13111        // Set the system/privileged flags as needed
13112        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13113        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13114                != 0) {
13115            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13116        }
13117
13118        // Kill package processes including services, providers, etc.
13119        killPackage(deletedPackage, "replace sys pkg");
13120
13121        // Remove existing system package
13122        removePackageLI(deletedPackage, true);
13123
13124        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13125        if (!disabledSystem) {
13126            // We didn't need to disable the .apk as a current system package,
13127            // which means we are replacing another update that is already
13128            // installed.  We need to make sure to delete the older one's .apk.
13129            res.removedInfo.args = createInstallArgsForExisting(0,
13130                    deletedPackage.applicationInfo.getCodePath(),
13131                    deletedPackage.applicationInfo.getResourcePath(),
13132                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13133        } else {
13134            res.removedInfo.args = null;
13135        }
13136
13137        // Successfully disabled the old package. Now proceed with re-installation
13138        deleteCodeCacheDirsLI(pkg);
13139
13140        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13141        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13142                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13143
13144        PackageParser.Package newPackage = null;
13145        try {
13146            // Add the package to the internal data structures
13147            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13148
13149            // Set the update and install times
13150            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13151            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13152                    System.currentTimeMillis());
13153
13154            // Check for shared user id changes
13155            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13156                    deletedPackage, newPackage);
13157            if (invalidPackageName != null) {
13158                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13159                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13160                                + " to " + invalidPackageName);
13161            }
13162
13163            // Update the package dynamic state if succeeded
13164            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13165                // Now that the install succeeded make sure we remove data
13166                // directories for any child package the update removed.
13167                final int deletedChildCount = (deletedPackage.childPackages != null)
13168                        ? deletedPackage.childPackages.size() : 0;
13169                final int newChildCount = (newPackage.childPackages != null)
13170                        ? newPackage.childPackages.size() : 0;
13171                for (int i = 0; i < deletedChildCount; i++) {
13172                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13173                    boolean childPackageDeleted = true;
13174                    for (int j = 0; j < newChildCount; j++) {
13175                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13176                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13177                            childPackageDeleted = false;
13178                            break;
13179                        }
13180                    }
13181                    if (childPackageDeleted) {
13182                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13183                                deletedChildPkg.packageName);
13184                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13185                            PackageRemovedInfo removedChildRes = res.removedInfo
13186                                    .removedChildPackages.get(deletedChildPkg.packageName);
13187                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13188                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13189                        }
13190                    }
13191                }
13192
13193                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13194                prepareAppDataAfterInstall(newPackage);
13195            }
13196        } catch (PackageManagerException e) {
13197            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13198            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13199        }
13200
13201        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13202            // Re installation failed. Restore old information
13203            // Remove new pkg information
13204            if (newPackage != null) {
13205                removeInstalledPackageLI(newPackage, true);
13206            }
13207            // Add back the old system package
13208            try {
13209                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13210            } catch (PackageManagerException e) {
13211                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13212            }
13213
13214            synchronized (mPackages) {
13215                if (disabledSystem) {
13216                    enableSystemPackageLPw(deletedPackage);
13217                }
13218
13219                // Ensure the installer package name up to date
13220                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13221
13222                // Update permissions for restored package
13223                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13224
13225                mSettings.writeLPr();
13226            }
13227
13228            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13229                    + " after failed upgrade");
13230        }
13231    }
13232
13233    /**
13234     * Checks whether the parent or any of the child packages have a change shared
13235     * user. For a package to be a valid update the shred users of the parent and
13236     * the children should match. We may later support changing child shared users.
13237     * @param oldPkg The updated package.
13238     * @param newPkg The update package.
13239     * @return The shared user that change between the versions.
13240     */
13241    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13242            PackageParser.Package newPkg) {
13243        // Check parent shared user
13244        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13245            return newPkg.packageName;
13246        }
13247        // Check child shared users
13248        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13249        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13250        for (int i = 0; i < newChildCount; i++) {
13251            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13252            // If this child was present, did it have the same shared user?
13253            for (int j = 0; j < oldChildCount; j++) {
13254                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13255                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13256                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13257                    return newChildPkg.packageName;
13258                }
13259            }
13260        }
13261        return null;
13262    }
13263
13264    private void removeNativeBinariesLI(PackageParser.Package pkg) {
13265        // Remove the lib path for the parent package
13266        PackageSetting ps = (PackageSetting) pkg.mExtras;
13267        if (ps != null) {
13268            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13269        }
13270        // Remove the lib path for the child packages
13271        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13272        for (int i = 0; i < childCount; i++) {
13273            ps = (PackageSetting) pkg.childPackages.get(i).mExtras;
13274            if (ps != null) {
13275                NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13276            }
13277        }
13278    }
13279
13280    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13281        // Enable the parent package
13282        mSettings.enableSystemPackageLPw(pkg.packageName);
13283        // Enable the child packages
13284        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13285        for (int i = 0; i < childCount; i++) {
13286            PackageParser.Package childPkg = pkg.childPackages.get(i);
13287            mSettings.enableSystemPackageLPw(childPkg.packageName);
13288        }
13289    }
13290
13291    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13292            PackageParser.Package newPkg) {
13293        // Disable the parent package (parent always replaced)
13294        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13295        // Disable the child packages
13296        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13297        for (int i = 0; i < childCount; i++) {
13298            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13299            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13300            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13301        }
13302        return disabled;
13303    }
13304
13305    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13306            String installerPackageName) {
13307        // Enable the parent package
13308        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13309        // Enable the child packages
13310        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13311        for (int i = 0; i < childCount; i++) {
13312            PackageParser.Package childPkg = pkg.childPackages.get(i);
13313            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13314        }
13315    }
13316
13317    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13318        // Collect all used permissions in the UID
13319        ArraySet<String> usedPermissions = new ArraySet<>();
13320        final int packageCount = su.packages.size();
13321        for (int i = 0; i < packageCount; i++) {
13322            PackageSetting ps = su.packages.valueAt(i);
13323            if (ps.pkg == null) {
13324                continue;
13325            }
13326            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13327            for (int j = 0; j < requestedPermCount; j++) {
13328                String permission = ps.pkg.requestedPermissions.get(j);
13329                BasePermission bp = mSettings.mPermissions.get(permission);
13330                if (bp != null) {
13331                    usedPermissions.add(permission);
13332                }
13333            }
13334        }
13335
13336        PermissionsState permissionsState = su.getPermissionsState();
13337        // Prune install permissions
13338        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13339        final int installPermCount = installPermStates.size();
13340        for (int i = installPermCount - 1; i >= 0;  i--) {
13341            PermissionState permissionState = installPermStates.get(i);
13342            if (!usedPermissions.contains(permissionState.getName())) {
13343                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13344                if (bp != null) {
13345                    permissionsState.revokeInstallPermission(bp);
13346                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13347                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13348                }
13349            }
13350        }
13351
13352        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13353
13354        // Prune runtime permissions
13355        for (int userId : allUserIds) {
13356            List<PermissionState> runtimePermStates = permissionsState
13357                    .getRuntimePermissionStates(userId);
13358            final int runtimePermCount = runtimePermStates.size();
13359            for (int i = runtimePermCount - 1; i >= 0; i--) {
13360                PermissionState permissionState = runtimePermStates.get(i);
13361                if (!usedPermissions.contains(permissionState.getName())) {
13362                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13363                    if (bp != null) {
13364                        permissionsState.revokeRuntimePermission(bp, userId);
13365                        permissionsState.updatePermissionFlags(bp, userId,
13366                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13367                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13368                                runtimePermissionChangedUserIds, userId);
13369                    }
13370                }
13371            }
13372        }
13373
13374        return runtimePermissionChangedUserIds;
13375    }
13376
13377    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13378            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13379        // Update the parent package setting
13380        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13381                res, user);
13382        // Update the child packages setting
13383        final int childCount = (newPackage.childPackages != null)
13384                ? newPackage.childPackages.size() : 0;
13385        for (int i = 0; i < childCount; i++) {
13386            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13387            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13388            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13389                    childRes.origUsers, childRes, user);
13390        }
13391    }
13392
13393    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13394            String installerPackageName, int[] allUsers, int[] installedForUsers,
13395            PackageInstalledInfo res, UserHandle user) {
13396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13397
13398        String pkgName = newPackage.packageName;
13399        synchronized (mPackages) {
13400            //write settings. the installStatus will be incomplete at this stage.
13401            //note that the new package setting would have already been
13402            //added to mPackages. It hasn't been persisted yet.
13403            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13404            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13405            mSettings.writeLPr();
13406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13407        }
13408
13409        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13410        synchronized (mPackages) {
13411            updatePermissionsLPw(newPackage.packageName, newPackage,
13412                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13413                            ? UPDATE_PERMISSIONS_ALL : 0));
13414            // For system-bundled packages, we assume that installing an upgraded version
13415            // of the package implies that the user actually wants to run that new code,
13416            // so we enable the package.
13417            PackageSetting ps = mSettings.mPackages.get(pkgName);
13418            final int userId = user.getIdentifier();
13419            if (ps != null) {
13420                if (isSystemApp(newPackage)) {
13421                    if (DEBUG_INSTALL) {
13422                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13423                    }
13424                    // Enable system package for requested users
13425                    if (res.origUsers != null) {
13426                        for (int origUserId : res.origUsers) {
13427                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13428                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13429                                        origUserId, installerPackageName);
13430                            }
13431                        }
13432                    }
13433                    // Also convey the prior install/uninstall state
13434                    if (allUsers != null && installedForUsers != null) {
13435                        for (int currentUserId : allUsers) {
13436                            final boolean installed = ArrayUtils.contains(
13437                                    installedForUsers, currentUserId);
13438                            if (DEBUG_INSTALL) {
13439                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13440                            }
13441                            ps.setInstalled(installed, currentUserId);
13442                        }
13443                        // these install state changes will be persisted in the
13444                        // upcoming call to mSettings.writeLPr().
13445                    }
13446                }
13447                // It's implied that when a user requests installation, they want the app to be
13448                // installed and enabled.
13449                if (userId != UserHandle.USER_ALL) {
13450                    ps.setInstalled(true, userId);
13451                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13452                }
13453            }
13454            res.name = pkgName;
13455            res.uid = newPackage.applicationInfo.uid;
13456            res.pkg = newPackage;
13457            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13458            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13459            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13460            //to update install status
13461            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13462            mSettings.writeLPr();
13463            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13464        }
13465
13466        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13467    }
13468
13469    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13470        try {
13471            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13472            installPackageLI(args, res);
13473        } finally {
13474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13475        }
13476    }
13477
13478    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13479        final int installFlags = args.installFlags;
13480        final String installerPackageName = args.installerPackageName;
13481        final String volumeUuid = args.volumeUuid;
13482        final File tmpPackageFile = new File(args.getCodePath());
13483        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13484        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13485                || (args.volumeUuid != null));
13486        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13487        boolean replace = false;
13488        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13489        if (args.move != null) {
13490            // moving a complete application; perform an initial scan on the new install location
13491            scanFlags |= SCAN_INITIAL;
13492        }
13493
13494        // Result object to be returned
13495        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13496
13497        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13498
13499        // Sanity check
13500        if (ephemeral && (forwardLocked || onExternal)) {
13501            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13502                    + " external=" + onExternal);
13503            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13504            return;
13505        }
13506
13507        // Retrieve PackageSettings and parse package
13508        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13509                | PackageParser.PARSE_ENFORCE_CODE
13510                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13511                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13512                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13513        PackageParser pp = new PackageParser();
13514        pp.setSeparateProcesses(mSeparateProcesses);
13515        pp.setDisplayMetrics(mMetrics);
13516
13517        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13518        final PackageParser.Package pkg;
13519        try {
13520            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13521        } catch (PackageParserException e) {
13522            res.setError("Failed parse during installPackageLI", e);
13523            return;
13524        } finally {
13525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13526        }
13527
13528        // If we are installing a clustered package add results for the children
13529        if (pkg.childPackages != null) {
13530            synchronized (mPackages) {
13531                final int childCount = pkg.childPackages.size();
13532                for (int i = 0; i < childCount; i++) {
13533                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13534                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13535                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13536                    childRes.pkg = childPkg;
13537                    childRes.name = childPkg.packageName;
13538                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13539                    if (childPs != null) {
13540                        childRes.origUsers = childPs.queryInstalledUsers(
13541                                sUserManager.getUserIds(), true);
13542                    }
13543                    if ((mPackages.containsKey(childPkg.packageName))) {
13544                        childRes.removedInfo = new PackageRemovedInfo();
13545                        childRes.removedInfo.removedPackage = childPkg.packageName;
13546                    }
13547                    if (res.addedChildPackages == null) {
13548                        res.addedChildPackages = new ArrayMap<>();
13549                    }
13550                    res.addedChildPackages.put(childPkg.packageName, childRes);
13551                }
13552            }
13553        }
13554
13555        // If package doesn't declare API override, mark that we have an install
13556        // time CPU ABI override.
13557        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13558            pkg.cpuAbiOverride = args.abiOverride;
13559        }
13560
13561        String pkgName = res.name = pkg.packageName;
13562        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13563            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13564                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13565                return;
13566            }
13567        }
13568
13569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13570        try {
13571            PackageParser.collectCertificates(pkg, parseFlags);
13572        } catch (PackageParserException e) {
13573            res.setError("Failed collect during installPackageLI", e);
13574            return;
13575        } finally {
13576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13577        }
13578
13579        // Get rid of all references to package scan path via parser.
13580        pp = null;
13581        String oldCodePath = null;
13582        boolean systemApp = false;
13583        synchronized (mPackages) {
13584            // Check if installing already existing package
13585            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13586                String oldName = mSettings.mRenamedPackages.get(pkgName);
13587                if (pkg.mOriginalPackages != null
13588                        && pkg.mOriginalPackages.contains(oldName)
13589                        && mPackages.containsKey(oldName)) {
13590                    // This package is derived from an original package,
13591                    // and this device has been updating from that original
13592                    // name.  We must continue using the original name, so
13593                    // rename the new package here.
13594                    pkg.setPackageName(oldName);
13595                    pkgName = pkg.packageName;
13596                    replace = true;
13597                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13598                            + oldName + " pkgName=" + pkgName);
13599                } else if (mPackages.containsKey(pkgName)) {
13600                    // This package, under its official name, already exists
13601                    // on the device; we should replace it.
13602                    replace = true;
13603                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13604                }
13605
13606                // Child packages are installed through the parent package
13607                if (pkg.parentPackage != null) {
13608                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13609                            "Package " + pkg.packageName + " is child of package "
13610                                    + pkg.parentPackage.parentPackage + ". Child packages "
13611                                    + "can be updated only through the parent package.");
13612                    return;
13613                }
13614
13615                if (replace) {
13616                    // Prevent apps opting out from runtime permissions
13617                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13618                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13619                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13620                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13621                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13622                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13623                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13624                                        + " doesn't support runtime permissions but the old"
13625                                        + " target SDK " + oldTargetSdk + " does.");
13626                        return;
13627                    }
13628
13629                    // Prevent installing of child packages
13630                    if (oldPackage.parentPackage != null) {
13631                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13632                                "Package " + pkg.packageName + " is child of package "
13633                                        + oldPackage.parentPackage + ". Child packages "
13634                                        + "can be updated only through the parent package.");
13635                        return;
13636                    }
13637                }
13638            }
13639
13640            PackageSetting ps = mSettings.mPackages.get(pkgName);
13641            if (ps != null) {
13642                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13643
13644                // Quick sanity check that we're signed correctly if updating;
13645                // we'll check this again later when scanning, but we want to
13646                // bail early here before tripping over redefined permissions.
13647                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13648                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13649                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13650                                + pkg.packageName + " upgrade keys do not match the "
13651                                + "previously installed version");
13652                        return;
13653                    }
13654                } else {
13655                    try {
13656                        verifySignaturesLP(ps, pkg);
13657                    } catch (PackageManagerException e) {
13658                        res.setError(e.error, e.getMessage());
13659                        return;
13660                    }
13661                }
13662
13663                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13664                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13665                    systemApp = (ps.pkg.applicationInfo.flags &
13666                            ApplicationInfo.FLAG_SYSTEM) != 0;
13667                }
13668                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13669            }
13670
13671            // Check whether the newly-scanned package wants to define an already-defined perm
13672            int N = pkg.permissions.size();
13673            for (int i = N-1; i >= 0; i--) {
13674                PackageParser.Permission perm = pkg.permissions.get(i);
13675                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13676                if (bp != null) {
13677                    // If the defining package is signed with our cert, it's okay.  This
13678                    // also includes the "updating the same package" case, of course.
13679                    // "updating same package" could also involve key-rotation.
13680                    final boolean sigsOk;
13681                    if (bp.sourcePackage.equals(pkg.packageName)
13682                            && (bp.packageSetting instanceof PackageSetting)
13683                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13684                                    scanFlags))) {
13685                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13686                    } else {
13687                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13688                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13689                    }
13690                    if (!sigsOk) {
13691                        // If the owning package is the system itself, we log but allow
13692                        // install to proceed; we fail the install on all other permission
13693                        // redefinitions.
13694                        if (!bp.sourcePackage.equals("android")) {
13695                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13696                                    + pkg.packageName + " attempting to redeclare permission "
13697                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13698                            res.origPermission = perm.info.name;
13699                            res.origPackage = bp.sourcePackage;
13700                            return;
13701                        } else {
13702                            Slog.w(TAG, "Package " + pkg.packageName
13703                                    + " attempting to redeclare system permission "
13704                                    + perm.info.name + "; ignoring new declaration");
13705                            pkg.permissions.remove(i);
13706                        }
13707                    }
13708                }
13709            }
13710        }
13711
13712        if (systemApp) {
13713            if (onExternal) {
13714                // Abort update; system app can't be replaced with app on sdcard
13715                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13716                        "Cannot install updates to system apps on sdcard");
13717                return;
13718            } else if (ephemeral) {
13719                // Abort update; system app can't be replaced with an ephemeral app
13720                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13721                        "Cannot update a system app with an ephemeral app");
13722                return;
13723            }
13724        }
13725
13726        if (args.move != null) {
13727            // We did an in-place move, so dex is ready to roll
13728            scanFlags |= SCAN_NO_DEX;
13729            scanFlags |= SCAN_MOVE;
13730
13731            synchronized (mPackages) {
13732                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13733                if (ps == null) {
13734                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13735                            "Missing settings for moved package " + pkgName);
13736                }
13737
13738                // We moved the entire application as-is, so bring over the
13739                // previously derived ABI information.
13740                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13741                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13742            }
13743
13744        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13745            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13746            scanFlags |= SCAN_NO_DEX;
13747
13748            try {
13749                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13750                    args.abiOverride : pkg.cpuAbiOverride);
13751                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13752                        true /* extract libs */);
13753            } catch (PackageManagerException pme) {
13754                Slog.e(TAG, "Error deriving application ABI", pme);
13755                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13756                return;
13757            }
13758
13759            // Extract package to save the VM unzipping the APK in memory during
13760            // launch. Only do this if profile-guided compilation is enabled because
13761            // otherwise BackgroundDexOptService will not dexopt the package later.
13762            if (mUseJitProfiles) {
13763                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13764                // Do not run PackageDexOptimizer through the local performDexOpt
13765                // method because `pkg` is not in `mPackages` yet.
13766                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13767                        false /* useProfiles */, true /* extractOnly */);
13768                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13769                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13770                    String msg = "Extracking package failed for " + pkgName;
13771                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13772                    return;
13773                }
13774            }
13775        }
13776
13777        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13778            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13779            return;
13780        }
13781
13782        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13783
13784        if (replace) {
13785            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13786                    installerPackageName, res);
13787        } else {
13788            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13789                    args.user, installerPackageName, volumeUuid, res);
13790        }
13791        synchronized (mPackages) {
13792            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13793            if (ps != null) {
13794                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13795            }
13796
13797            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13798            for (int i = 0; i < childCount; i++) {
13799                PackageParser.Package childPkg = pkg.childPackages.get(i);
13800                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13801                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13802                if (childPs != null) {
13803                    childRes.newUsers = childPs.queryInstalledUsers(
13804                            sUserManager.getUserIds(), true);
13805                }
13806            }
13807        }
13808    }
13809
13810    private void startIntentFilterVerifications(int userId, boolean replacing,
13811            PackageParser.Package pkg) {
13812        if (mIntentFilterVerifierComponent == null) {
13813            Slog.w(TAG, "No IntentFilter verification will not be done as "
13814                    + "there is no IntentFilterVerifier available!");
13815            return;
13816        }
13817
13818        final int verifierUid = getPackageUid(
13819                mIntentFilterVerifierComponent.getPackageName(),
13820                MATCH_DEBUG_TRIAGED_MISSING,
13821                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13822
13823        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13824        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13825        mHandler.sendMessage(msg);
13826
13827        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13828        for (int i = 0; i < childCount; i++) {
13829            PackageParser.Package childPkg = pkg.childPackages.get(i);
13830            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13831            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
13832            mHandler.sendMessage(msg);
13833        }
13834    }
13835
13836    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13837            PackageParser.Package pkg) {
13838        int size = pkg.activities.size();
13839        if (size == 0) {
13840            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13841                    "No activity, so no need to verify any IntentFilter!");
13842            return;
13843        }
13844
13845        final boolean hasDomainURLs = hasDomainURLs(pkg);
13846        if (!hasDomainURLs) {
13847            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13848                    "No domain URLs, so no need to verify any IntentFilter!");
13849            return;
13850        }
13851
13852        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13853                + " if any IntentFilter from the " + size
13854                + " Activities needs verification ...");
13855
13856        int count = 0;
13857        final String packageName = pkg.packageName;
13858
13859        synchronized (mPackages) {
13860            // If this is a new install and we see that we've already run verification for this
13861            // package, we have nothing to do: it means the state was restored from backup.
13862            if (!replacing) {
13863                IntentFilterVerificationInfo ivi =
13864                        mSettings.getIntentFilterVerificationLPr(packageName);
13865                if (ivi != null) {
13866                    if (DEBUG_DOMAIN_VERIFICATION) {
13867                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13868                                + ivi.getStatusString());
13869                    }
13870                    return;
13871                }
13872            }
13873
13874            // If any filters need to be verified, then all need to be.
13875            boolean needToVerify = false;
13876            for (PackageParser.Activity a : pkg.activities) {
13877                for (ActivityIntentInfo filter : a.intents) {
13878                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13879                        if (DEBUG_DOMAIN_VERIFICATION) {
13880                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13881                        }
13882                        needToVerify = true;
13883                        break;
13884                    }
13885                }
13886            }
13887
13888            if (needToVerify) {
13889                final int verificationId = mIntentFilterVerificationToken++;
13890                for (PackageParser.Activity a : pkg.activities) {
13891                    for (ActivityIntentInfo filter : a.intents) {
13892                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13893                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13894                                    "Verification needed for IntentFilter:" + filter.toString());
13895                            mIntentFilterVerifier.addOneIntentFilterVerification(
13896                                    verifierUid, userId, verificationId, filter, packageName);
13897                            count++;
13898                        }
13899                    }
13900                }
13901            }
13902        }
13903
13904        if (count > 0) {
13905            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13906                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13907                    +  " for userId:" + userId);
13908            mIntentFilterVerifier.startVerifications(userId);
13909        } else {
13910            if (DEBUG_DOMAIN_VERIFICATION) {
13911                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13912            }
13913        }
13914    }
13915
13916    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13917        final ComponentName cn  = filter.activity.getComponentName();
13918        final String packageName = cn.getPackageName();
13919
13920        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13921                packageName);
13922        if (ivi == null) {
13923            return true;
13924        }
13925        int status = ivi.getStatus();
13926        switch (status) {
13927            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13928            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13929                return true;
13930
13931            default:
13932                // Nothing to do
13933                return false;
13934        }
13935    }
13936
13937    private static boolean isMultiArch(ApplicationInfo info) {
13938        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13939    }
13940
13941    private static boolean isExternal(PackageParser.Package pkg) {
13942        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13943    }
13944
13945    private static boolean isExternal(PackageSetting ps) {
13946        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13947    }
13948
13949    private static boolean isEphemeral(PackageParser.Package pkg) {
13950        return pkg.applicationInfo.isEphemeralApp();
13951    }
13952
13953    private static boolean isEphemeral(PackageSetting ps) {
13954        return ps.pkg != null && isEphemeral(ps.pkg);
13955    }
13956
13957    private static boolean isSystemApp(PackageParser.Package pkg) {
13958        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13959    }
13960
13961    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13962        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13963    }
13964
13965    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13966        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13967    }
13968
13969    private static boolean isSystemApp(PackageSetting ps) {
13970        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13971    }
13972
13973    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13974        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13975    }
13976
13977    private int packageFlagsToInstallFlags(PackageSetting ps) {
13978        int installFlags = 0;
13979        if (isEphemeral(ps)) {
13980            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13981        }
13982        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13983            // This existing package was an external ASEC install when we have
13984            // the external flag without a UUID
13985            installFlags |= PackageManager.INSTALL_EXTERNAL;
13986        }
13987        if (ps.isForwardLocked()) {
13988            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13989        }
13990        return installFlags;
13991    }
13992
13993    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13994        if (isExternal(pkg)) {
13995            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13996                return StorageManager.UUID_PRIMARY_PHYSICAL;
13997            } else {
13998                return pkg.volumeUuid;
13999            }
14000        } else {
14001            return StorageManager.UUID_PRIVATE_INTERNAL;
14002        }
14003    }
14004
14005    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14006        if (isExternal(pkg)) {
14007            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14008                return mSettings.getExternalVersion();
14009            } else {
14010                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14011            }
14012        } else {
14013            return mSettings.getInternalVersion();
14014        }
14015    }
14016
14017    private void deleteTempPackageFiles() {
14018        final FilenameFilter filter = new FilenameFilter() {
14019            public boolean accept(File dir, String name) {
14020                return name.startsWith("vmdl") && name.endsWith(".tmp");
14021            }
14022        };
14023        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14024            file.delete();
14025        }
14026    }
14027
14028    @Override
14029    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14030            int flags) {
14031        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14032                flags);
14033    }
14034
14035    @Override
14036    public void deletePackage(final String packageName,
14037            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14038        mContext.enforceCallingOrSelfPermission(
14039                android.Manifest.permission.DELETE_PACKAGES, null);
14040        Preconditions.checkNotNull(packageName);
14041        Preconditions.checkNotNull(observer);
14042        final int uid = Binder.getCallingUid();
14043        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14044        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14045        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14046            mContext.enforceCallingOrSelfPermission(
14047                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14048                    "deletePackage for user " + userId);
14049        }
14050
14051        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14052            try {
14053                observer.onPackageDeleted(packageName,
14054                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14055            } catch (RemoteException re) {
14056            }
14057            return;
14058        }
14059
14060        for (int currentUserId : users) {
14061            if (getBlockUninstallForUser(packageName, currentUserId)) {
14062                try {
14063                    observer.onPackageDeleted(packageName,
14064                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14065                } catch (RemoteException re) {
14066                }
14067                return;
14068            }
14069        }
14070
14071        if (DEBUG_REMOVE) {
14072            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
14073        }
14074        // Queue up an async operation since the package deletion may take a little while.
14075        mHandler.post(new Runnable() {
14076            public void run() {
14077                mHandler.removeCallbacks(this);
14078                final int returnCode = deletePackageX(packageName, userId, flags);
14079                try {
14080                    observer.onPackageDeleted(packageName, returnCode, null);
14081                } catch (RemoteException e) {
14082                    Log.i(TAG, "Observer no longer exists.");
14083                } //end catch
14084            } //end run
14085        });
14086    }
14087
14088    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14089        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14090                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14091        try {
14092            if (dpm != null) {
14093                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14094                        /* callingUserOnly =*/ false);
14095                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14096                        : deviceOwnerComponentName.getPackageName();
14097                // Does the package contains the device owner?
14098                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14099                // this check is probably not needed, since DO should be registered as a device
14100                // admin on some user too. (Original bug for this: b/17657954)
14101                if (packageName.equals(deviceOwnerPackageName)) {
14102                    return true;
14103                }
14104                // Does it contain a device admin for any user?
14105                int[] users;
14106                if (userId == UserHandle.USER_ALL) {
14107                    users = sUserManager.getUserIds();
14108                } else {
14109                    users = new int[]{userId};
14110                }
14111                for (int i = 0; i < users.length; ++i) {
14112                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14113                        return true;
14114                    }
14115                }
14116            }
14117        } catch (RemoteException e) {
14118        }
14119        return false;
14120    }
14121
14122    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14123        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14124    }
14125
14126    /**
14127     *  This method is an internal method that could be get invoked either
14128     *  to delete an installed package or to clean up a failed installation.
14129     *  After deleting an installed package, a broadcast is sent to notify any
14130     *  listeners that the package has been installed. For cleaning up a failed
14131     *  installation, the broadcast is not necessary since the package's
14132     *  installation wouldn't have sent the initial broadcast either
14133     *  The key steps in deleting a package are
14134     *  deleting the package information in internal structures like mPackages,
14135     *  deleting the packages base directories through installd
14136     *  updating mSettings to reflect current status
14137     *  persisting settings for later use
14138     *  sending a broadcast if necessary
14139     */
14140    private int deletePackageX(String packageName, int userId, int flags) {
14141        final PackageRemovedInfo info = new PackageRemovedInfo();
14142        final boolean res;
14143
14144        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14145                ? UserHandle.ALL : new UserHandle(userId);
14146
14147        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14148            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14149            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14150        }
14151
14152        PackageSetting uninstalledPs = null;
14153
14154        // for the uninstall-updates case and restricted profiles, remember the per-
14155        // user handle installed state
14156        int[] allUsers;
14157        synchronized (mPackages) {
14158            uninstalledPs = mSettings.mPackages.get(packageName);
14159            if (uninstalledPs == null) {
14160                Slog.w(TAG, "Not removing non-existent package " + packageName);
14161                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14162            }
14163            allUsers = sUserManager.getUserIds();
14164            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14165        }
14166
14167        synchronized (mInstallLock) {
14168            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14169            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14170                    flags | REMOVE_CHATTY, info, true, null);
14171            synchronized (mPackages) {
14172                if (res) {
14173                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14174                }
14175            }
14176        }
14177
14178        if (res) {
14179            info.sendPackageRemovedBroadcasts();
14180            info.sendSystemPackageUpdatedBroadcasts();
14181            info.sendSystemPackageAppearedBroadcasts();
14182        }
14183        // Force a gc here.
14184        Runtime.getRuntime().gc();
14185        // Delete the resources here after sending the broadcast to let
14186        // other processes clean up before deleting resources.
14187        if (info.args != null) {
14188            synchronized (mInstallLock) {
14189                info.args.doPostDeleteLI(true);
14190            }
14191        }
14192
14193        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14194    }
14195
14196    class PackageRemovedInfo {
14197        String removedPackage;
14198        int uid = -1;
14199        int removedAppId = -1;
14200        int[] origUsers;
14201        int[] removedUsers = null;
14202        boolean isRemovedPackageSystemUpdate = false;
14203        boolean isUpdate;
14204        boolean dataRemoved;
14205        boolean removedForAllUsers;
14206        // Clean up resources deleted packages.
14207        InstallArgs args = null;
14208        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14209        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14210
14211        void sendPackageRemovedBroadcasts() {
14212            sendPackageRemovedBroadcastInternal();
14213            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14214            for (int i = 0; i < childCount; i++) {
14215                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14216                childInfo.sendPackageRemovedBroadcastInternal();
14217            }
14218        }
14219
14220        void sendSystemPackageUpdatedBroadcasts() {
14221            if (isRemovedPackageSystemUpdate) {
14222                sendSystemPackageUpdatedBroadcastsInternal();
14223                final int childCount = (removedChildPackages != null)
14224                        ? removedChildPackages.size() : 0;
14225                for (int i = 0; i < childCount; i++) {
14226                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14227                    if (childInfo.isRemovedPackageSystemUpdate) {
14228                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14229                    }
14230                }
14231            }
14232        }
14233
14234        void sendSystemPackageAppearedBroadcasts() {
14235            final int packageCount = (appearedChildPackages != null)
14236                    ? appearedChildPackages.size() : 0;
14237            for (int i = 0; i < packageCount; i++) {
14238                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14239                for (int userId : installedInfo.newUsers) {
14240                    sendPackageAddedForUser(installedInfo.name, true,
14241                            UserHandle.getAppId(installedInfo.uid), userId);
14242                }
14243            }
14244        }
14245
14246        private void sendSystemPackageUpdatedBroadcastsInternal() {
14247            Bundle extras = new Bundle(2);
14248            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14249            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14250            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14251                    extras, 0, null, null, null);
14252            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14253                    extras, 0, null, null, null);
14254            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14255                    null, 0, removedPackage, null, null);
14256        }
14257
14258        private void sendPackageRemovedBroadcastInternal() {
14259            Bundle extras = new Bundle(2);
14260            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14261            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14262            if (isUpdate || isRemovedPackageSystemUpdate) {
14263                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14264            }
14265            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14266            if (removedPackage != null) {
14267                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14268                        extras, 0, null, null, removedUsers);
14269                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14270                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14271                            removedPackage, extras, 0, null, null, removedUsers);
14272                }
14273            }
14274            if (removedAppId >= 0) {
14275                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14276                        removedUsers);
14277            }
14278        }
14279    }
14280
14281    /*
14282     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14283     * flag is not set, the data directory is removed as well.
14284     * make sure this flag is set for partially installed apps. If not its meaningless to
14285     * delete a partially installed application.
14286     */
14287    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14288            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14289        String packageName = ps.name;
14290        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14291        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14292        // Retrieve object to delete permissions for shared user later on
14293        final PackageSetting deletedPs;
14294        // reader
14295        synchronized (mPackages) {
14296            deletedPs = mSettings.mPackages.get(packageName);
14297            if (outInfo != null) {
14298                outInfo.removedPackage = packageName;
14299                outInfo.removedUsers = deletedPs != null
14300                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14301                        : null;
14302            }
14303        }
14304        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14305            removeDataDirsLI(ps.volumeUuid, packageName);
14306            if (outInfo != null) {
14307                outInfo.dataRemoved = true;
14308            }
14309            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14310        }
14311        // writer
14312        synchronized (mPackages) {
14313            if (deletedPs != null) {
14314                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14315                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14316                    clearDefaultBrowserIfNeeded(packageName);
14317                    if (outInfo != null) {
14318                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14319                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14320                    }
14321                    updatePermissionsLPw(deletedPs.name, null, 0);
14322                    if (deletedPs.sharedUser != null) {
14323                        // Remove permissions associated with package. Since runtime
14324                        // permissions are per user we have to kill the removed package
14325                        // or packages running under the shared user of the removed
14326                        // package if revoking the permissions requested only by the removed
14327                        // package is successful and this causes a change in gids.
14328                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14329                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14330                                    userId);
14331                            if (userIdToKill == UserHandle.USER_ALL
14332                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14333                                // If gids changed for this user, kill all affected packages.
14334                                mHandler.post(new Runnable() {
14335                                    @Override
14336                                    public void run() {
14337                                        // This has to happen with no lock held.
14338                                        killApplication(deletedPs.name, deletedPs.appId,
14339                                                KILL_APP_REASON_GIDS_CHANGED);
14340                                    }
14341                                });
14342                                break;
14343                            }
14344                        }
14345                    }
14346                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14347                }
14348                // make sure to preserve per-user disabled state if this removal was just
14349                // a downgrade of a system app to the factory package
14350                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14351                    if (DEBUG_REMOVE) {
14352                        Slog.d(TAG, "Propagating install state across downgrade");
14353                    }
14354                    for (int userId : allUserHandles) {
14355                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14356                        if (DEBUG_REMOVE) {
14357                            Slog.d(TAG, "    user " + userId + " => " + installed);
14358                        }
14359                        ps.setInstalled(installed, userId);
14360                    }
14361                }
14362            }
14363            // can downgrade to reader
14364            if (writeSettings) {
14365                // Save settings now
14366                mSettings.writeLPr();
14367            }
14368        }
14369        if (outInfo != null) {
14370            // A user ID was deleted here. Go through all users and remove it
14371            // from KeyStore.
14372            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14373        }
14374    }
14375
14376    static boolean locationIsPrivileged(File path) {
14377        try {
14378            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14379                    .getCanonicalPath();
14380            return path.getCanonicalPath().startsWith(privilegedAppDir);
14381        } catch (IOException e) {
14382            Slog.e(TAG, "Unable to access code path " + path);
14383        }
14384        return false;
14385    }
14386
14387    /*
14388     * Tries to delete system package.
14389     */
14390    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14391            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14392            boolean writeSettings) {
14393        if (deletedPkg.parentPackage != null) {
14394            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14395            return false;
14396        }
14397
14398        final boolean applyUserRestrictions
14399                = (allUserHandles != null) && (outInfo.origUsers != null);
14400        final PackageSetting disabledPs;
14401        // Confirm if the system package has been updated
14402        // An updated system app can be deleted. This will also have to restore
14403        // the system pkg from system partition
14404        // reader
14405        synchronized (mPackages) {
14406            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName);
14407        }
14408
14409        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14410                + " disabledPs=" + disabledPs);
14411
14412        if (disabledPs == null) {
14413            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14414            return false;
14415        } else if (DEBUG_REMOVE) {
14416            Slog.d(TAG, "Deleting system pkg from data partition");
14417        }
14418
14419        if (DEBUG_REMOVE) {
14420            if (applyUserRestrictions) {
14421                Slog.d(TAG, "Remembering install states:");
14422                for (int userId : allUserHandles) {
14423                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14424                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14425                }
14426            }
14427        }
14428
14429        // Delete the updated package
14430        outInfo.isRemovedPackageSystemUpdate = true;
14431        if (outInfo.removedChildPackages != null) {
14432            final int childCount = (deletedPkg.childPackages != null)
14433                    ? deletedPkg.childPackages.size() : 0;
14434            for (int i = 0; i < childCount; i++) {
14435                String childPackageName = deletedPkg.childPackages.get(i).packageName;
14436                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14437                        .contains(childPackageName)) {
14438                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14439                            childPackageName);
14440                    if (childInfo != null) {
14441                        childInfo.isRemovedPackageSystemUpdate = true;
14442                    }
14443                }
14444            }
14445        }
14446
14447        if (disabledPs.versionCode < deletedPs.versionCode) {
14448            // Delete data for downgrades
14449            flags &= ~PackageManager.DELETE_KEEP_DATA;
14450        } else {
14451            // Preserve data by setting flag
14452            flags |= PackageManager.DELETE_KEEP_DATA;
14453        }
14454
14455        boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles,
14456                outInfo, writeSettings, disabledPs.pkg);
14457        if (!ret) {
14458            return false;
14459        }
14460
14461        // writer
14462        synchronized (mPackages) {
14463            // Reinstate the old system package
14464            enableSystemPackageLPw(disabledPs.pkg);
14465            // Remove any native libraries from the upgraded package.
14466            removeNativeBinariesLI(deletedPkg);
14467        }
14468
14469        // Install the system package
14470        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14471        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14472        if (locationIsPrivileged(disabledPs.codePath)) {
14473            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14474        }
14475
14476        final PackageParser.Package newPkg;
14477        try {
14478            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14479        } catch (PackageManagerException e) {
14480            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14481                    + e.getMessage());
14482            return false;
14483        }
14484
14485        prepareAppDataAfterInstall(newPkg);
14486
14487        // writer
14488        synchronized (mPackages) {
14489            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14490
14491            // Propagate the permissions state as we do not want to drop on the floor
14492            // runtime permissions. The update permissions method below will take
14493            // care of removing obsolete permissions and grant install permissions.
14494            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14495            updatePermissionsLPw(newPkg.packageName, newPkg,
14496                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14497
14498            if (applyUserRestrictions) {
14499                if (DEBUG_REMOVE) {
14500                    Slog.d(TAG, "Propagating install state across reinstall");
14501                }
14502                for (int userId : allUserHandles) {
14503                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14504                    if (DEBUG_REMOVE) {
14505                        Slog.d(TAG, "    user " + userId + " => " + installed);
14506                    }
14507                    ps.setInstalled(installed, userId);
14508
14509                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14510                }
14511                // Regardless of writeSettings we need to ensure that this restriction
14512                // state propagation is persisted
14513                mSettings.writeAllUsersPackageRestrictionsLPr();
14514            }
14515            // can downgrade to reader here
14516            if (writeSettings) {
14517                mSettings.writeLPr();
14518            }
14519        }
14520        return true;
14521    }
14522
14523    private boolean deleteInstalledPackageLI(PackageParser.Package pkg,
14524            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14525            PackageRemovedInfo outInfo, boolean writeSettings,
14526            PackageParser.Package replacingPackage) {
14527        PackageSetting ps = null;
14528
14529        synchronized (mPackages) {
14530            pkg = mPackages.get(pkg.packageName);
14531            if (pkg == null) {
14532                return false;
14533            }
14534
14535            ps = mSettings.mPackages.get(pkg.packageName);
14536            if (ps == null) {
14537                return false;
14538            }
14539
14540            if (outInfo != null) {
14541                outInfo.uid = ps.appId;
14542            }
14543
14544            if (outInfo != null && outInfo.removedChildPackages != null) {
14545                final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14546                for (int i = 0; i < childCount; i++) {
14547                    String childPackageName = ps.childPackageNames.get(i);
14548                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14549                    if (childPs == null) {
14550                        return false;
14551                    }
14552                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14553                            childPackageName);
14554                    if (childInfo != null) {
14555                        childInfo.uid = childPs.appId;
14556                    }
14557                }
14558            }
14559        }
14560
14561        // Delete package data from internal structures and also remove data if flag is set
14562        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14563
14564        // Delete the child packages data
14565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14566        for (int i = 0; i < childCount; i++) {
14567            PackageSetting childPs;
14568            synchronized (mPackages) {
14569                childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName);
14570            }
14571            if (childPs != null) {
14572                PackageRemovedInfo childOutInfo = (outInfo != null
14573                        && outInfo.removedChildPackages != null)
14574                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14575                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14576                        && (replacingPackage != null
14577                        && !replacingPackage.hasChildPackage(childPs.name))
14578                        ? flags & ~DELETE_KEEP_DATA : flags;
14579                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14580                        deleteFlags, writeSettings);
14581            }
14582        }
14583
14584        // Delete application code and resources only for parent packages
14585        if (ps.pkg.parentPackage == null) {
14586            if (deleteCodeAndResources && (outInfo != null)) {
14587                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14588                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14589                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14590            }
14591        }
14592
14593        return true;
14594    }
14595
14596    @Override
14597    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14598            int userId) {
14599        mContext.enforceCallingOrSelfPermission(
14600                android.Manifest.permission.DELETE_PACKAGES, null);
14601        synchronized (mPackages) {
14602            PackageSetting ps = mSettings.mPackages.get(packageName);
14603            if (ps == null) {
14604                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14605                return false;
14606            }
14607            if (!ps.getInstalled(userId)) {
14608                // Can't block uninstall for an app that is not installed or enabled.
14609                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14610                return false;
14611            }
14612            ps.setBlockUninstall(blockUninstall, userId);
14613            mSettings.writePackageRestrictionsLPr(userId);
14614        }
14615        return true;
14616    }
14617
14618    @Override
14619    public boolean getBlockUninstallForUser(String packageName, int userId) {
14620        synchronized (mPackages) {
14621            PackageSetting ps = mSettings.mPackages.get(packageName);
14622            if (ps == null) {
14623                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14624                return false;
14625            }
14626            return ps.getBlockUninstall(userId);
14627        }
14628    }
14629
14630    @Override
14631    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14632        int callingUid = Binder.getCallingUid();
14633        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14634            throw new SecurityException(
14635                    "setRequiredForSystemUser can only be run by the system or root");
14636        }
14637        synchronized (mPackages) {
14638            PackageSetting ps = mSettings.mPackages.get(packageName);
14639            if (ps == null) {
14640                Log.w(TAG, "Package doesn't exist: " + packageName);
14641                return false;
14642            }
14643            if (systemUserApp) {
14644                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14645            } else {
14646                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14647            }
14648            mSettings.writeLPr();
14649        }
14650        return true;
14651    }
14652
14653    /*
14654     * This method handles package deletion in general
14655     */
14656    private boolean deletePackageLI(String packageName, UserHandle user,
14657            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14658            PackageRemovedInfo outInfo, boolean writeSettings,
14659            PackageParser.Package replacingPackage) {
14660        if (packageName == null) {
14661            Slog.w(TAG, "Attempt to delete null packageName.");
14662            return false;
14663        }
14664
14665        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14666
14667        PackageSetting ps;
14668
14669        synchronized (mPackages) {
14670            ps = mSettings.mPackages.get(packageName);
14671            if (ps == null) {
14672                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14673                return false;
14674            }
14675
14676            if (ps.pkg.parentPackage != null && (!isSystemApp(ps)
14677                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14678                if (DEBUG_REMOVE) {
14679                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14680                            + ((user == null) ? UserHandle.USER_ALL : user));
14681                }
14682                final int removedUserId = (user != null) ? user.getIdentifier()
14683                        : UserHandle.USER_ALL;
14684                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14685                    return false;
14686                }
14687                markPackageUninstalledForUserLPw(ps, user);
14688                scheduleWritePackageRestrictionsLocked(user);
14689                return true;
14690            }
14691        }
14692
14693        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14694                && user.getIdentifier() != UserHandle.USER_ALL)) {
14695            // The caller is asking that the package only be deleted for a single
14696            // user.  To do this, we just mark its uninstalled state and delete
14697            // its data. If this is a system app, we only allow this to happen if
14698            // they have set the special DELETE_SYSTEM_APP which requests different
14699            // semantics than normal for uninstalling system apps.
14700            markPackageUninstalledForUserLPw(ps, user);
14701
14702            if (!isSystemApp(ps)) {
14703                // Do not uninstall the APK if an app should be cached
14704                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14705                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14706                    // Other user still have this package installed, so all
14707                    // we need to do is clear this user's data and save that
14708                    // it is uninstalled.
14709                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14710                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14711                        return false;
14712                    }
14713                    scheduleWritePackageRestrictionsLocked(user);
14714                    return true;
14715                } else {
14716                    // We need to set it back to 'installed' so the uninstall
14717                    // broadcasts will be sent correctly.
14718                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14719                    ps.setInstalled(true, user.getIdentifier());
14720                }
14721            } else {
14722                // This is a system app, so we assume that the
14723                // other users still have this package installed, so all
14724                // we need to do is clear this user's data and save that
14725                // it is uninstalled.
14726                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14727                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14728                    return false;
14729                }
14730                scheduleWritePackageRestrictionsLocked(user);
14731                return true;
14732            }
14733        }
14734
14735        // If we are deleting a composite package for all users, keep track
14736        // of result for each child.
14737        if (ps.childPackageNames != null && outInfo != null) {
14738            synchronized (mPackages) {
14739                final int childCount = ps.childPackageNames.size();
14740                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14741                for (int i = 0; i < childCount; i++) {
14742                    String childPackageName = ps.childPackageNames.get(i);
14743                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14744                    childInfo.removedPackage = childPackageName;
14745                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14746                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14747                    if (childPs != null) {
14748                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14749                    }
14750                }
14751            }
14752        }
14753
14754        boolean ret = false;
14755        if (isSystemApp(ps)) {
14756            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14757            // When an updated system application is deleted we delete the existing resources
14758            // as well and fall back to existing code in system partition
14759            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14760        } else {
14761            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14762            // Kill application pre-emptively especially for apps on sd.
14763            killApplication(packageName, ps.appId, "uninstall pkg");
14764            ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles,
14765                    outInfo, writeSettings, replacingPackage);
14766        }
14767
14768        // Take a note whether we deleted the package for all users
14769        if (outInfo != null) {
14770            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14771            if (outInfo.removedChildPackages != null) {
14772                synchronized (mPackages) {
14773                    final int childCount = outInfo.removedChildPackages.size();
14774                    for (int i = 0; i < childCount; i++) {
14775                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
14776                        if (childInfo != null) {
14777                            childInfo.removedForAllUsers = mPackages.get(
14778                                    childInfo.removedPackage) == null;
14779                        }
14780                    }
14781                }
14782            }
14783            // If we uninstalled an update to a system app there may be some
14784            // child packages that appeared as they are declared in the system
14785            // app but were not declared in the update.
14786            if (isSystemApp(ps)) {
14787                synchronized (mPackages) {
14788                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
14789                    final int childCount = (updatedPs.childPackageNames != null)
14790                            ? updatedPs.childPackageNames.size() : 0;
14791                    for (int i = 0; i < childCount; i++) {
14792                        String childPackageName = updatedPs.childPackageNames.get(i);
14793                        if (outInfo.removedChildPackages == null
14794                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
14795                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14796                            if (childPs == null) {
14797                                continue;
14798                            }
14799                            PackageInstalledInfo installRes = new PackageInstalledInfo();
14800                            installRes.name = childPackageName;
14801                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
14802                            installRes.pkg = mPackages.get(childPackageName);
14803                            installRes.uid = childPs.pkg.applicationInfo.uid;
14804                            if (outInfo.appearedChildPackages == null) {
14805                                outInfo.appearedChildPackages = new ArrayMap<>();
14806                            }
14807                            outInfo.appearedChildPackages.put(childPackageName, installRes);
14808                        }
14809                    }
14810                }
14811            }
14812        }
14813
14814        return ret;
14815    }
14816
14817    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
14818        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
14819                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
14820        for (int nextUserId : userIds) {
14821            if (DEBUG_REMOVE) {
14822                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
14823            }
14824            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
14825                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
14826                    false /*hidden*/, false /*suspended*/, null, null, null,
14827                    false /*blockUninstall*/,
14828                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
14829        }
14830    }
14831
14832    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
14833            PackageRemovedInfo outInfo) {
14834        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14835                : new int[] {userId};
14836        for (int nextUserId : userIds) {
14837            if (DEBUG_REMOVE) {
14838                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
14839                        + nextUserId);
14840            }
14841            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
14842            try {
14843                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
14844            } catch (InstallerException e) {
14845                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
14846                return false;
14847            }
14848            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
14849            schedulePackageCleaning(ps.name, nextUserId, false);
14850            synchronized (mPackages) {
14851                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
14852                    scheduleWritePackageRestrictionsLocked(nextUserId);
14853                }
14854                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
14855            }
14856        }
14857
14858        if (outInfo != null) {
14859            outInfo.removedPackage = ps.name;
14860            outInfo.removedAppId = ps.appId;
14861            outInfo.removedUsers = userIds;
14862        }
14863
14864        return true;
14865    }
14866
14867    private final class ClearStorageConnection implements ServiceConnection {
14868        IMediaContainerService mContainerService;
14869
14870        @Override
14871        public void onServiceConnected(ComponentName name, IBinder service) {
14872            synchronized (this) {
14873                mContainerService = IMediaContainerService.Stub.asInterface(service);
14874                notifyAll();
14875            }
14876        }
14877
14878        @Override
14879        public void onServiceDisconnected(ComponentName name) {
14880        }
14881    }
14882
14883    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14884        final boolean mounted;
14885        if (Environment.isExternalStorageEmulated()) {
14886            mounted = true;
14887        } else {
14888            final String status = Environment.getExternalStorageState();
14889
14890            mounted = status.equals(Environment.MEDIA_MOUNTED)
14891                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14892        }
14893
14894        if (!mounted) {
14895            return;
14896        }
14897
14898        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14899        int[] users;
14900        if (userId == UserHandle.USER_ALL) {
14901            users = sUserManager.getUserIds();
14902        } else {
14903            users = new int[] { userId };
14904        }
14905        final ClearStorageConnection conn = new ClearStorageConnection();
14906        if (mContext.bindServiceAsUser(
14907                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14908            try {
14909                for (int curUser : users) {
14910                    long timeout = SystemClock.uptimeMillis() + 5000;
14911                    synchronized (conn) {
14912                        long now = SystemClock.uptimeMillis();
14913                        while (conn.mContainerService == null && now < timeout) {
14914                            try {
14915                                conn.wait(timeout - now);
14916                            } catch (InterruptedException e) {
14917                            }
14918                        }
14919                    }
14920                    if (conn.mContainerService == null) {
14921                        return;
14922                    }
14923
14924                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14925                    clearDirectory(conn.mContainerService,
14926                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14927                    if (allData) {
14928                        clearDirectory(conn.mContainerService,
14929                                userEnv.buildExternalStorageAppDataDirs(packageName));
14930                        clearDirectory(conn.mContainerService,
14931                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14932                    }
14933                }
14934            } finally {
14935                mContext.unbindService(conn);
14936            }
14937        }
14938    }
14939
14940    @Override
14941    public void clearApplicationUserData(final String packageName,
14942            final IPackageDataObserver observer, final int userId) {
14943        mContext.enforceCallingOrSelfPermission(
14944                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14945        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14946        // Queue up an async operation since the package deletion may take a little while.
14947        mHandler.post(new Runnable() {
14948            public void run() {
14949                mHandler.removeCallbacks(this);
14950                final boolean succeeded;
14951                synchronized (mInstallLock) {
14952                    succeeded = clearApplicationUserDataLI(packageName, userId);
14953                }
14954                clearExternalStorageDataSync(packageName, userId, true);
14955                if (succeeded) {
14956                    // invoke DeviceStorageMonitor's update method to clear any notifications
14957                    DeviceStorageMonitorInternal
14958                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14959                    if (dsm != null) {
14960                        dsm.checkMemory();
14961                    }
14962                }
14963                if(observer != null) {
14964                    try {
14965                        observer.onRemoveCompleted(packageName, succeeded);
14966                    } catch (RemoteException e) {
14967                        Log.i(TAG, "Observer no longer exists.");
14968                    }
14969                } //end if observer
14970            } //end run
14971        });
14972    }
14973
14974    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14975        if (packageName == null) {
14976            Slog.w(TAG, "Attempt to delete null packageName.");
14977            return false;
14978        }
14979
14980        // Try finding details about the requested package
14981        PackageParser.Package pkg;
14982        synchronized (mPackages) {
14983            pkg = mPackages.get(packageName);
14984            if (pkg == null) {
14985                final PackageSetting ps = mSettings.mPackages.get(packageName);
14986                if (ps != null) {
14987                    pkg = ps.pkg;
14988                }
14989            }
14990
14991            if (pkg == null) {
14992                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14993                return false;
14994            }
14995
14996            PackageSetting ps = (PackageSetting) pkg.mExtras;
14997            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14998        }
14999
15000        // Always delete data directories for package, even if we found no other
15001        // record of app. This helps users recover from UID mismatches without
15002        // resorting to a full data wipe.
15003        // TODO: triage flags as part of 26466827
15004        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15005        try {
15006            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15007        } catch (InstallerException e) {
15008            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15009            return false;
15010        }
15011
15012        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15013        removeKeystoreDataIfNeeded(userId, appId);
15014
15015        // Create a native library symlink only if we have native libraries
15016        // and if the native libraries are 32 bit libraries. We do not provide
15017        // this symlink for 64 bit libraries.
15018        if (pkg.applicationInfo.primaryCpuAbi != null &&
15019                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15020            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15021            try {
15022                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15023                        nativeLibPath, userId);
15024            } catch (InstallerException e) {
15025                Slog.w(TAG, "Failed linking native library dir", e);
15026                return false;
15027            }
15028        }
15029
15030        return true;
15031    }
15032
15033    /**
15034     * Reverts user permission state changes (permissions and flags) in
15035     * all packages for a given user.
15036     *
15037     * @param userId The device user for which to do a reset.
15038     */
15039    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15040        final int packageCount = mPackages.size();
15041        for (int i = 0; i < packageCount; i++) {
15042            PackageParser.Package pkg = mPackages.valueAt(i);
15043            PackageSetting ps = (PackageSetting) pkg.mExtras;
15044            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15045        }
15046    }
15047
15048    /**
15049     * Reverts user permission state changes (permissions and flags).
15050     *
15051     * @param ps The package for which to reset.
15052     * @param userId The device user for which to do a reset.
15053     */
15054    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15055            final PackageSetting ps, final int userId) {
15056        if (ps.pkg == null) {
15057            return;
15058        }
15059
15060        // These are flags that can change base on user actions.
15061        final int userSettableMask = FLAG_PERMISSION_USER_SET
15062                | FLAG_PERMISSION_USER_FIXED
15063                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15064                | FLAG_PERMISSION_REVIEW_REQUIRED;
15065
15066        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15067                | FLAG_PERMISSION_POLICY_FIXED;
15068
15069        boolean writeInstallPermissions = false;
15070        boolean writeRuntimePermissions = false;
15071
15072        final int permissionCount = ps.pkg.requestedPermissions.size();
15073        for (int i = 0; i < permissionCount; i++) {
15074            String permission = ps.pkg.requestedPermissions.get(i);
15075
15076            BasePermission bp = mSettings.mPermissions.get(permission);
15077            if (bp == null) {
15078                continue;
15079            }
15080
15081            // If shared user we just reset the state to which only this app contributed.
15082            if (ps.sharedUser != null) {
15083                boolean used = false;
15084                final int packageCount = ps.sharedUser.packages.size();
15085                for (int j = 0; j < packageCount; j++) {
15086                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15087                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15088                            && pkg.pkg.requestedPermissions.contains(permission)) {
15089                        used = true;
15090                        break;
15091                    }
15092                }
15093                if (used) {
15094                    continue;
15095                }
15096            }
15097
15098            PermissionsState permissionsState = ps.getPermissionsState();
15099
15100            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15101
15102            // Always clear the user settable flags.
15103            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15104                    bp.name) != null;
15105            // If permission review is enabled and this is a legacy app, mark the
15106            // permission as requiring a review as this is the initial state.
15107            int flags = 0;
15108            if (Build.PERMISSIONS_REVIEW_REQUIRED
15109                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15110                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15111            }
15112            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15113                if (hasInstallState) {
15114                    writeInstallPermissions = true;
15115                } else {
15116                    writeRuntimePermissions = true;
15117                }
15118            }
15119
15120            // Below is only runtime permission handling.
15121            if (!bp.isRuntime()) {
15122                continue;
15123            }
15124
15125            // Never clobber system or policy.
15126            if ((oldFlags & policyOrSystemFlags) != 0) {
15127                continue;
15128            }
15129
15130            // If this permission was granted by default, make sure it is.
15131            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15132                if (permissionsState.grantRuntimePermission(bp, userId)
15133                        != PERMISSION_OPERATION_FAILURE) {
15134                    writeRuntimePermissions = true;
15135                }
15136            // If permission review is enabled the permissions for a legacy apps
15137            // are represented as constantly granted runtime ones, so don't revoke.
15138            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15139                // Otherwise, reset the permission.
15140                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15141                switch (revokeResult) {
15142                    case PERMISSION_OPERATION_SUCCESS: {
15143                        writeRuntimePermissions = true;
15144                    } break;
15145
15146                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15147                        writeRuntimePermissions = true;
15148                        final int appId = ps.appId;
15149                        mHandler.post(new Runnable() {
15150                            @Override
15151                            public void run() {
15152                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15153                            }
15154                        });
15155                    } break;
15156                }
15157            }
15158        }
15159
15160        // Synchronously write as we are taking permissions away.
15161        if (writeRuntimePermissions) {
15162            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15163        }
15164
15165        // Synchronously write as we are taking permissions away.
15166        if (writeInstallPermissions) {
15167            mSettings.writeLPr();
15168        }
15169    }
15170
15171    /**
15172     * Remove entries from the keystore daemon. Will only remove it if the
15173     * {@code appId} is valid.
15174     */
15175    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15176        if (appId < 0) {
15177            return;
15178        }
15179
15180        final KeyStore keyStore = KeyStore.getInstance();
15181        if (keyStore != null) {
15182            if (userId == UserHandle.USER_ALL) {
15183                for (final int individual : sUserManager.getUserIds()) {
15184                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15185                }
15186            } else {
15187                keyStore.clearUid(UserHandle.getUid(userId, appId));
15188            }
15189        } else {
15190            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15191        }
15192    }
15193
15194    @Override
15195    public void deleteApplicationCacheFiles(final String packageName,
15196            final IPackageDataObserver observer) {
15197        mContext.enforceCallingOrSelfPermission(
15198                android.Manifest.permission.DELETE_CACHE_FILES, null);
15199        // Queue up an async operation since the package deletion may take a little while.
15200        final int userId = UserHandle.getCallingUserId();
15201        mHandler.post(new Runnable() {
15202            public void run() {
15203                mHandler.removeCallbacks(this);
15204                final boolean succeded;
15205                synchronized (mInstallLock) {
15206                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15207                }
15208                clearExternalStorageDataSync(packageName, userId, false);
15209                if (observer != null) {
15210                    try {
15211                        observer.onRemoveCompleted(packageName, succeded);
15212                    } catch (RemoteException e) {
15213                        Log.i(TAG, "Observer no longer exists.");
15214                    }
15215                } //end if observer
15216            } //end run
15217        });
15218    }
15219
15220    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15221        if (packageName == null) {
15222            Slog.w(TAG, "Attempt to delete null packageName.");
15223            return false;
15224        }
15225        PackageParser.Package p;
15226        synchronized (mPackages) {
15227            p = mPackages.get(packageName);
15228        }
15229        if (p == null) {
15230            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15231            return false;
15232        }
15233        final ApplicationInfo applicationInfo = p.applicationInfo;
15234        if (applicationInfo == null) {
15235            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15236            return false;
15237        }
15238        // TODO: triage flags as part of 26466827
15239        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15240        try {
15241            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15242                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15243        } catch (InstallerException e) {
15244            Slog.w(TAG, "Couldn't remove cache files for package "
15245                    + packageName + " u" + userId, e);
15246            return false;
15247        }
15248        return true;
15249    }
15250
15251    @Override
15252    public void getPackageSizeInfo(final String packageName, int userHandle,
15253            final IPackageStatsObserver observer) {
15254        mContext.enforceCallingOrSelfPermission(
15255                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15256        if (packageName == null) {
15257            throw new IllegalArgumentException("Attempt to get size of null packageName");
15258        }
15259
15260        PackageStats stats = new PackageStats(packageName, userHandle);
15261
15262        /*
15263         * Queue up an async operation since the package measurement may take a
15264         * little while.
15265         */
15266        Message msg = mHandler.obtainMessage(INIT_COPY);
15267        msg.obj = new MeasureParams(stats, observer);
15268        mHandler.sendMessage(msg);
15269    }
15270
15271    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15272            PackageStats pStats) {
15273        if (packageName == null) {
15274            Slog.w(TAG, "Attempt to get size of null packageName.");
15275            return false;
15276        }
15277        PackageParser.Package p;
15278        boolean dataOnly = false;
15279        String libDirRoot = null;
15280        String asecPath = null;
15281        PackageSetting ps = null;
15282        synchronized (mPackages) {
15283            p = mPackages.get(packageName);
15284            ps = mSettings.mPackages.get(packageName);
15285            if(p == null) {
15286                dataOnly = true;
15287                if((ps == null) || (ps.pkg == null)) {
15288                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15289                    return false;
15290                }
15291                p = ps.pkg;
15292            }
15293            if (ps != null) {
15294                libDirRoot = ps.legacyNativeLibraryPathString;
15295            }
15296            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15297                final long token = Binder.clearCallingIdentity();
15298                try {
15299                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15300                    if (secureContainerId != null) {
15301                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15302                    }
15303                } finally {
15304                    Binder.restoreCallingIdentity(token);
15305                }
15306            }
15307        }
15308        String publicSrcDir = null;
15309        if(!dataOnly) {
15310            final ApplicationInfo applicationInfo = p.applicationInfo;
15311            if (applicationInfo == null) {
15312                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15313                return false;
15314            }
15315            if (p.isForwardLocked()) {
15316                publicSrcDir = applicationInfo.getBaseResourcePath();
15317            }
15318        }
15319        // TODO: extend to measure size of split APKs
15320        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15321        // not just the first level.
15322        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15323        // just the primary.
15324        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15325
15326        String apkPath;
15327        File packageDir = new File(p.codePath);
15328
15329        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15330            apkPath = packageDir.getAbsolutePath();
15331            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15332            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15333                libDirRoot = null;
15334            }
15335        } else {
15336            apkPath = p.baseCodePath;
15337        }
15338
15339        // TODO: triage flags as part of 26466827
15340        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15341        try {
15342            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15343                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15344        } catch (InstallerException e) {
15345            return false;
15346        }
15347
15348        // Fix-up for forward-locked applications in ASEC containers.
15349        if (!isExternal(p)) {
15350            pStats.codeSize += pStats.externalCodeSize;
15351            pStats.externalCodeSize = 0L;
15352        }
15353
15354        return true;
15355    }
15356
15357
15358    @Override
15359    public void addPackageToPreferred(String packageName) {
15360        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
15361    }
15362
15363    @Override
15364    public void removePackageFromPreferred(String packageName) {
15365        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
15366    }
15367
15368    @Override
15369    public List<PackageInfo> getPreferredPackages(int flags) {
15370        return new ArrayList<PackageInfo>();
15371    }
15372
15373    private int getUidTargetSdkVersionLockedLPr(int uid) {
15374        Object obj = mSettings.getUserIdLPr(uid);
15375        if (obj instanceof SharedUserSetting) {
15376            final SharedUserSetting sus = (SharedUserSetting) obj;
15377            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15378            final Iterator<PackageSetting> it = sus.packages.iterator();
15379            while (it.hasNext()) {
15380                final PackageSetting ps = it.next();
15381                if (ps.pkg != null) {
15382                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15383                    if (v < vers) vers = v;
15384                }
15385            }
15386            return vers;
15387        } else if (obj instanceof PackageSetting) {
15388            final PackageSetting ps = (PackageSetting) obj;
15389            if (ps.pkg != null) {
15390                return ps.pkg.applicationInfo.targetSdkVersion;
15391            }
15392        }
15393        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15394    }
15395
15396    @Override
15397    public void addPreferredActivity(IntentFilter filter, int match,
15398            ComponentName[] set, ComponentName activity, int userId) {
15399        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15400                "Adding preferred");
15401    }
15402
15403    private void addPreferredActivityInternal(IntentFilter filter, int match,
15404            ComponentName[] set, ComponentName activity, boolean always, int userId,
15405            String opname) {
15406        // writer
15407        int callingUid = Binder.getCallingUid();
15408        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
15409        if (filter.countActions() == 0) {
15410            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15411            return;
15412        }
15413        synchronized (mPackages) {
15414            if (mContext.checkCallingOrSelfPermission(
15415                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15416                    != PackageManager.PERMISSION_GRANTED) {
15417                if (getUidTargetSdkVersionLockedLPr(callingUid)
15418                        < Build.VERSION_CODES.FROYO) {
15419                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15420                            + callingUid);
15421                    return;
15422                }
15423                mContext.enforceCallingOrSelfPermission(
15424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15425            }
15426
15427            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15428            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15429                    + userId + ":");
15430            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15431            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15432            scheduleWritePackageRestrictionsLocked(userId);
15433        }
15434    }
15435
15436    @Override
15437    public void replacePreferredActivity(IntentFilter filter, int match,
15438            ComponentName[] set, ComponentName activity, int userId) {
15439        if (filter.countActions() != 1) {
15440            throw new IllegalArgumentException(
15441                    "replacePreferredActivity expects filter to have only 1 action.");
15442        }
15443        if (filter.countDataAuthorities() != 0
15444                || filter.countDataPaths() != 0
15445                || filter.countDataSchemes() > 1
15446                || filter.countDataTypes() != 0) {
15447            throw new IllegalArgumentException(
15448                    "replacePreferredActivity expects filter to have no data authorities, " +
15449                    "paths, or types; and at most one scheme.");
15450        }
15451
15452        final int callingUid = Binder.getCallingUid();
15453        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
15454        synchronized (mPackages) {
15455            if (mContext.checkCallingOrSelfPermission(
15456                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15457                    != PackageManager.PERMISSION_GRANTED) {
15458                if (getUidTargetSdkVersionLockedLPr(callingUid)
15459                        < Build.VERSION_CODES.FROYO) {
15460                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15461                            + Binder.getCallingUid());
15462                    return;
15463                }
15464                mContext.enforceCallingOrSelfPermission(
15465                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15466            }
15467
15468            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15469            if (pir != null) {
15470                // Get all of the existing entries that exactly match this filter.
15471                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15472                if (existing != null && existing.size() == 1) {
15473                    PreferredActivity cur = existing.get(0);
15474                    if (DEBUG_PREFERRED) {
15475                        Slog.i(TAG, "Checking replace of preferred:");
15476                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15477                        if (!cur.mPref.mAlways) {
15478                            Slog.i(TAG, "  -- CUR; not mAlways!");
15479                        } else {
15480                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15481                            Slog.i(TAG, "  -- CUR: mSet="
15482                                    + Arrays.toString(cur.mPref.mSetComponents));
15483                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15484                            Slog.i(TAG, "  -- NEW: mMatch="
15485                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15486                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15487                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15488                        }
15489                    }
15490                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15491                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15492                            && cur.mPref.sameSet(set)) {
15493                        // Setting the preferred activity to what it happens to be already
15494                        if (DEBUG_PREFERRED) {
15495                            Slog.i(TAG, "Replacing with same preferred activity "
15496                                    + cur.mPref.mShortComponent + " for user "
15497                                    + userId + ":");
15498                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15499                        }
15500                        return;
15501                    }
15502                }
15503
15504                if (existing != null) {
15505                    if (DEBUG_PREFERRED) {
15506                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15507                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15508                    }
15509                    for (int i = 0; i < existing.size(); i++) {
15510                        PreferredActivity pa = existing.get(i);
15511                        if (DEBUG_PREFERRED) {
15512                            Slog.i(TAG, "Removing existing preferred activity "
15513                                    + pa.mPref.mComponent + ":");
15514                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15515                        }
15516                        pir.removeFilter(pa);
15517                    }
15518                }
15519            }
15520            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15521                    "Replacing preferred");
15522        }
15523    }
15524
15525    @Override
15526    public void clearPackagePreferredActivities(String packageName) {
15527        final int uid = Binder.getCallingUid();
15528        // writer
15529        synchronized (mPackages) {
15530            PackageParser.Package pkg = mPackages.get(packageName);
15531            if (pkg == null || pkg.applicationInfo.uid != uid) {
15532                if (mContext.checkCallingOrSelfPermission(
15533                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15534                        != PackageManager.PERMISSION_GRANTED) {
15535                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15536                            < Build.VERSION_CODES.FROYO) {
15537                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15538                                + Binder.getCallingUid());
15539                        return;
15540                    }
15541                    mContext.enforceCallingOrSelfPermission(
15542                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15543                }
15544            }
15545
15546            int user = UserHandle.getCallingUserId();
15547            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15548                scheduleWritePackageRestrictionsLocked(user);
15549            }
15550        }
15551    }
15552
15553    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15554    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15555        ArrayList<PreferredActivity> removed = null;
15556        boolean changed = false;
15557        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15558            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15559            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15560            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15561                continue;
15562            }
15563            Iterator<PreferredActivity> it = pir.filterIterator();
15564            while (it.hasNext()) {
15565                PreferredActivity pa = it.next();
15566                // Mark entry for removal only if it matches the package name
15567                // and the entry is of type "always".
15568                if (packageName == null ||
15569                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15570                                && pa.mPref.mAlways)) {
15571                    if (removed == null) {
15572                        removed = new ArrayList<PreferredActivity>();
15573                    }
15574                    removed.add(pa);
15575                }
15576            }
15577            if (removed != null) {
15578                for (int j=0; j<removed.size(); j++) {
15579                    PreferredActivity pa = removed.get(j);
15580                    pir.removeFilter(pa);
15581                }
15582                changed = true;
15583            }
15584        }
15585        return changed;
15586    }
15587
15588    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15589    private void clearIntentFilterVerificationsLPw(int userId) {
15590        final int packageCount = mPackages.size();
15591        for (int i = 0; i < packageCount; i++) {
15592            PackageParser.Package pkg = mPackages.valueAt(i);
15593            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15594        }
15595    }
15596
15597    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15598    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15599        if (userId == UserHandle.USER_ALL) {
15600            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15601                    sUserManager.getUserIds())) {
15602                for (int oneUserId : sUserManager.getUserIds()) {
15603                    scheduleWritePackageRestrictionsLocked(oneUserId);
15604                }
15605            }
15606        } else {
15607            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15608                scheduleWritePackageRestrictionsLocked(userId);
15609            }
15610        }
15611    }
15612
15613    void clearDefaultBrowserIfNeeded(String packageName) {
15614        for (int oneUserId : sUserManager.getUserIds()) {
15615            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15616            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15617            if (packageName.equals(defaultBrowserPackageName)) {
15618                setDefaultBrowserPackageName(null, oneUserId);
15619            }
15620        }
15621    }
15622
15623    @Override
15624    public void resetApplicationPreferences(int userId) {
15625        mContext.enforceCallingOrSelfPermission(
15626                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15627        // writer
15628        synchronized (mPackages) {
15629            final long identity = Binder.clearCallingIdentity();
15630            try {
15631                clearPackagePreferredActivitiesLPw(null, userId);
15632                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15633                // TODO: We have to reset the default SMS and Phone. This requires
15634                // significant refactoring to keep all default apps in the package
15635                // manager (cleaner but more work) or have the services provide
15636                // callbacks to the package manager to request a default app reset.
15637                applyFactoryDefaultBrowserLPw(userId);
15638                clearIntentFilterVerificationsLPw(userId);
15639                primeDomainVerificationsLPw(userId);
15640                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15641                scheduleWritePackageRestrictionsLocked(userId);
15642            } finally {
15643                Binder.restoreCallingIdentity(identity);
15644            }
15645        }
15646    }
15647
15648    @Override
15649    public int getPreferredActivities(List<IntentFilter> outFilters,
15650            List<ComponentName> outActivities, String packageName) {
15651
15652        int num = 0;
15653        final int userId = UserHandle.getCallingUserId();
15654        // reader
15655        synchronized (mPackages) {
15656            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15657            if (pir != null) {
15658                final Iterator<PreferredActivity> it = pir.filterIterator();
15659                while (it.hasNext()) {
15660                    final PreferredActivity pa = it.next();
15661                    if (packageName == null
15662                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15663                                    && pa.mPref.mAlways)) {
15664                        if (outFilters != null) {
15665                            outFilters.add(new IntentFilter(pa));
15666                        }
15667                        if (outActivities != null) {
15668                            outActivities.add(pa.mPref.mComponent);
15669                        }
15670                    }
15671                }
15672            }
15673        }
15674
15675        return num;
15676    }
15677
15678    @Override
15679    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15680            int userId) {
15681        int callingUid = Binder.getCallingUid();
15682        if (callingUid != Process.SYSTEM_UID) {
15683            throw new SecurityException(
15684                    "addPersistentPreferredActivity can only be run by the system");
15685        }
15686        if (filter.countActions() == 0) {
15687            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15688            return;
15689        }
15690        synchronized (mPackages) {
15691            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15692                    ":");
15693            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15694            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15695                    new PersistentPreferredActivity(filter, activity));
15696            scheduleWritePackageRestrictionsLocked(userId);
15697        }
15698    }
15699
15700    @Override
15701    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15702        int callingUid = Binder.getCallingUid();
15703        if (callingUid != Process.SYSTEM_UID) {
15704            throw new SecurityException(
15705                    "clearPackagePersistentPreferredActivities can only be run by the system");
15706        }
15707        ArrayList<PersistentPreferredActivity> removed = null;
15708        boolean changed = false;
15709        synchronized (mPackages) {
15710            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15711                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15712                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15713                        .valueAt(i);
15714                if (userId != thisUserId) {
15715                    continue;
15716                }
15717                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15718                while (it.hasNext()) {
15719                    PersistentPreferredActivity ppa = it.next();
15720                    // Mark entry for removal only if it matches the package name.
15721                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15722                        if (removed == null) {
15723                            removed = new ArrayList<PersistentPreferredActivity>();
15724                        }
15725                        removed.add(ppa);
15726                    }
15727                }
15728                if (removed != null) {
15729                    for (int j=0; j<removed.size(); j++) {
15730                        PersistentPreferredActivity ppa = removed.get(j);
15731                        ppir.removeFilter(ppa);
15732                    }
15733                    changed = true;
15734                }
15735            }
15736
15737            if (changed) {
15738                scheduleWritePackageRestrictionsLocked(userId);
15739            }
15740        }
15741    }
15742
15743    /**
15744     * Common machinery for picking apart a restored XML blob and passing
15745     * it to a caller-supplied functor to be applied to the running system.
15746     */
15747    private void restoreFromXml(XmlPullParser parser, int userId,
15748            String expectedStartTag, BlobXmlRestorer functor)
15749            throws IOException, XmlPullParserException {
15750        int type;
15751        while ((type = parser.next()) != XmlPullParser.START_TAG
15752                && type != XmlPullParser.END_DOCUMENT) {
15753        }
15754        if (type != XmlPullParser.START_TAG) {
15755            // oops didn't find a start tag?!
15756            if (DEBUG_BACKUP) {
15757                Slog.e(TAG, "Didn't find start tag during restore");
15758            }
15759            return;
15760        }
15761Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
15762        // this is supposed to be TAG_PREFERRED_BACKUP
15763        if (!expectedStartTag.equals(parser.getName())) {
15764            if (DEBUG_BACKUP) {
15765                Slog.e(TAG, "Found unexpected tag " + parser.getName());
15766            }
15767            return;
15768        }
15769
15770        // skip interfering stuff, then we're aligned with the backing implementation
15771        while ((type = parser.next()) == XmlPullParser.TEXT) { }
15772Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
15773        functor.apply(parser, userId);
15774    }
15775
15776    private interface BlobXmlRestorer {
15777        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
15778    }
15779
15780    /**
15781     * Non-Binder method, support for the backup/restore mechanism: write the
15782     * full set of preferred activities in its canonical XML format.  Returns the
15783     * XML output as a byte array, or null if there is none.
15784     */
15785    @Override
15786    public byte[] getPreferredActivityBackup(int userId) {
15787        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15788            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
15789        }
15790
15791        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15792        try {
15793            final XmlSerializer serializer = new FastXmlSerializer();
15794            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15795            serializer.startDocument(null, true);
15796            serializer.startTag(null, TAG_PREFERRED_BACKUP);
15797
15798            synchronized (mPackages) {
15799                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
15800            }
15801
15802            serializer.endTag(null, TAG_PREFERRED_BACKUP);
15803            serializer.endDocument();
15804            serializer.flush();
15805        } catch (Exception e) {
15806            if (DEBUG_BACKUP) {
15807                Slog.e(TAG, "Unable to write preferred activities for backup", e);
15808            }
15809            return null;
15810        }
15811
15812        return dataStream.toByteArray();
15813    }
15814
15815    @Override
15816    public void restorePreferredActivities(byte[] backup, int userId) {
15817        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15818            throw new SecurityException("Only the system may call restorePreferredActivities()");
15819        }
15820
15821        try {
15822            final XmlPullParser parser = Xml.newPullParser();
15823            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15824            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
15825                    new BlobXmlRestorer() {
15826                        @Override
15827                        public void apply(XmlPullParser parser, int userId)
15828                                throws XmlPullParserException, IOException {
15829                            synchronized (mPackages) {
15830                                mSettings.readPreferredActivitiesLPw(parser, userId);
15831                            }
15832                        }
15833                    } );
15834        } catch (Exception e) {
15835            if (DEBUG_BACKUP) {
15836                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15837            }
15838        }
15839    }
15840
15841    /**
15842     * Non-Binder method, support for the backup/restore mechanism: write the
15843     * default browser (etc) settings in its canonical XML format.  Returns the default
15844     * browser XML representation as a byte array, or null if there is none.
15845     */
15846    @Override
15847    public byte[] getDefaultAppsBackup(int userId) {
15848        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15849            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
15850        }
15851
15852        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15853        try {
15854            final XmlSerializer serializer = new FastXmlSerializer();
15855            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15856            serializer.startDocument(null, true);
15857            serializer.startTag(null, TAG_DEFAULT_APPS);
15858
15859            synchronized (mPackages) {
15860                mSettings.writeDefaultAppsLPr(serializer, userId);
15861            }
15862
15863            serializer.endTag(null, TAG_DEFAULT_APPS);
15864            serializer.endDocument();
15865            serializer.flush();
15866        } catch (Exception e) {
15867            if (DEBUG_BACKUP) {
15868                Slog.e(TAG, "Unable to write default apps for backup", e);
15869            }
15870            return null;
15871        }
15872
15873        return dataStream.toByteArray();
15874    }
15875
15876    @Override
15877    public void restoreDefaultApps(byte[] backup, int userId) {
15878        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15879            throw new SecurityException("Only the system may call restoreDefaultApps()");
15880        }
15881
15882        try {
15883            final XmlPullParser parser = Xml.newPullParser();
15884            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15885            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15886                    new BlobXmlRestorer() {
15887                        @Override
15888                        public void apply(XmlPullParser parser, int userId)
15889                                throws XmlPullParserException, IOException {
15890                            synchronized (mPackages) {
15891                                mSettings.readDefaultAppsLPw(parser, userId);
15892                            }
15893                        }
15894                    } );
15895        } catch (Exception e) {
15896            if (DEBUG_BACKUP) {
15897                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15898            }
15899        }
15900    }
15901
15902    @Override
15903    public byte[] getIntentFilterVerificationBackup(int userId) {
15904        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15905            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15906        }
15907
15908        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15909        try {
15910            final XmlSerializer serializer = new FastXmlSerializer();
15911            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15912            serializer.startDocument(null, true);
15913            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15914
15915            synchronized (mPackages) {
15916                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15917            }
15918
15919            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15920            serializer.endDocument();
15921            serializer.flush();
15922        } catch (Exception e) {
15923            if (DEBUG_BACKUP) {
15924                Slog.e(TAG, "Unable to write default apps for backup", e);
15925            }
15926            return null;
15927        }
15928
15929        return dataStream.toByteArray();
15930    }
15931
15932    @Override
15933    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15934        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15935            throw new SecurityException("Only the system may call restorePreferredActivities()");
15936        }
15937
15938        try {
15939            final XmlPullParser parser = Xml.newPullParser();
15940            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15941            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15942                    new BlobXmlRestorer() {
15943                        @Override
15944                        public void apply(XmlPullParser parser, int userId)
15945                                throws XmlPullParserException, IOException {
15946                            synchronized (mPackages) {
15947                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15948                                mSettings.writeLPr();
15949                            }
15950                        }
15951                    } );
15952        } catch (Exception e) {
15953            if (DEBUG_BACKUP) {
15954                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15955            }
15956        }
15957    }
15958
15959    @Override
15960    public byte[] getPermissionGrantBackup(int userId) {
15961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15962            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15963        }
15964
15965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15966        try {
15967            final XmlSerializer serializer = new FastXmlSerializer();
15968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15969            serializer.startDocument(null, true);
15970            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15971
15972            synchronized (mPackages) {
15973                serializeRuntimePermissionGrantsLPr(serializer, userId);
15974            }
15975
15976            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15977            serializer.endDocument();
15978            serializer.flush();
15979        } catch (Exception e) {
15980            if (DEBUG_BACKUP) {
15981                Slog.e(TAG, "Unable to write default apps for backup", e);
15982            }
15983            return null;
15984        }
15985
15986        return dataStream.toByteArray();
15987    }
15988
15989    @Override
15990    public void restorePermissionGrants(byte[] backup, int userId) {
15991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15992            throw new SecurityException("Only the system may call restorePermissionGrants()");
15993        }
15994
15995        try {
15996            final XmlPullParser parser = Xml.newPullParser();
15997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15998            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15999                    new BlobXmlRestorer() {
16000                        @Override
16001                        public void apply(XmlPullParser parser, int userId)
16002                                throws XmlPullParserException, IOException {
16003                            synchronized (mPackages) {
16004                                processRestoredPermissionGrantsLPr(parser, userId);
16005                            }
16006                        }
16007                    } );
16008        } catch (Exception e) {
16009            if (DEBUG_BACKUP) {
16010                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16011            }
16012        }
16013    }
16014
16015    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16016            throws IOException {
16017        serializer.startTag(null, TAG_ALL_GRANTS);
16018
16019        final int N = mSettings.mPackages.size();
16020        for (int i = 0; i < N; i++) {
16021            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16022            boolean pkgGrantsKnown = false;
16023
16024            PermissionsState packagePerms = ps.getPermissionsState();
16025
16026            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16027                final int grantFlags = state.getFlags();
16028                // only look at grants that are not system/policy fixed
16029                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16030                    final boolean isGranted = state.isGranted();
16031                    // And only back up the user-twiddled state bits
16032                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16033                        final String packageName = mSettings.mPackages.keyAt(i);
16034                        if (!pkgGrantsKnown) {
16035                            serializer.startTag(null, TAG_GRANT);
16036                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16037                            pkgGrantsKnown = true;
16038                        }
16039
16040                        final boolean userSet =
16041                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16042                        final boolean userFixed =
16043                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16044                        final boolean revoke =
16045                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16046
16047                        serializer.startTag(null, TAG_PERMISSION);
16048                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16049                        if (isGranted) {
16050                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16051                        }
16052                        if (userSet) {
16053                            serializer.attribute(null, ATTR_USER_SET, "true");
16054                        }
16055                        if (userFixed) {
16056                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16057                        }
16058                        if (revoke) {
16059                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16060                        }
16061                        serializer.endTag(null, TAG_PERMISSION);
16062                    }
16063                }
16064            }
16065
16066            if (pkgGrantsKnown) {
16067                serializer.endTag(null, TAG_GRANT);
16068            }
16069        }
16070
16071        serializer.endTag(null, TAG_ALL_GRANTS);
16072    }
16073
16074    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16075            throws XmlPullParserException, IOException {
16076        String pkgName = null;
16077        int outerDepth = parser.getDepth();
16078        int type;
16079        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16080                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16081            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16082                continue;
16083            }
16084
16085            final String tagName = parser.getName();
16086            if (tagName.equals(TAG_GRANT)) {
16087                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16088                if (DEBUG_BACKUP) {
16089                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16090                }
16091            } else if (tagName.equals(TAG_PERMISSION)) {
16092
16093                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16094                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16095
16096                int newFlagSet = 0;
16097                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16098                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16099                }
16100                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16101                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16102                }
16103                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16104                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16105                }
16106                if (DEBUG_BACKUP) {
16107                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16108                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16109                }
16110                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16111                if (ps != null) {
16112                    // Already installed so we apply the grant immediately
16113                    if (DEBUG_BACKUP) {
16114                        Slog.v(TAG, "        + already installed; applying");
16115                    }
16116                    PermissionsState perms = ps.getPermissionsState();
16117                    BasePermission bp = mSettings.mPermissions.get(permName);
16118                    if (bp != null) {
16119                        if (isGranted) {
16120                            perms.grantRuntimePermission(bp, userId);
16121                        }
16122                        if (newFlagSet != 0) {
16123                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16124                        }
16125                    }
16126                } else {
16127                    // Need to wait for post-restore install to apply the grant
16128                    if (DEBUG_BACKUP) {
16129                        Slog.v(TAG, "        - not yet installed; saving for later");
16130                    }
16131                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16132                            isGranted, newFlagSet, userId);
16133                }
16134            } else {
16135                PackageManagerService.reportSettingsProblem(Log.WARN,
16136                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16137                XmlUtils.skipCurrentTag(parser);
16138            }
16139        }
16140
16141        scheduleWriteSettingsLocked();
16142        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16143    }
16144
16145    @Override
16146    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16147            int sourceUserId, int targetUserId, int flags) {
16148        mContext.enforceCallingOrSelfPermission(
16149                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16150        int callingUid = Binder.getCallingUid();
16151        enforceOwnerRights(ownerPackage, callingUid);
16152        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16153        if (intentFilter.countActions() == 0) {
16154            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16155            return;
16156        }
16157        synchronized (mPackages) {
16158            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16159                    ownerPackage, targetUserId, flags);
16160            CrossProfileIntentResolver resolver =
16161                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16162            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16163            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16164            if (existing != null) {
16165                int size = existing.size();
16166                for (int i = 0; i < size; i++) {
16167                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16168                        return;
16169                    }
16170                }
16171            }
16172            resolver.addFilter(newFilter);
16173            scheduleWritePackageRestrictionsLocked(sourceUserId);
16174        }
16175    }
16176
16177    @Override
16178    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16179        mContext.enforceCallingOrSelfPermission(
16180                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16181        int callingUid = Binder.getCallingUid();
16182        enforceOwnerRights(ownerPackage, callingUid);
16183        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16184        synchronized (mPackages) {
16185            CrossProfileIntentResolver resolver =
16186                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16187            ArraySet<CrossProfileIntentFilter> set =
16188                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16189            for (CrossProfileIntentFilter filter : set) {
16190                if (filter.getOwnerPackage().equals(ownerPackage)) {
16191                    resolver.removeFilter(filter);
16192                }
16193            }
16194            scheduleWritePackageRestrictionsLocked(sourceUserId);
16195        }
16196    }
16197
16198    // Enforcing that callingUid is owning pkg on userId
16199    private void enforceOwnerRights(String pkg, int callingUid) {
16200        // The system owns everything.
16201        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16202            return;
16203        }
16204        int callingUserId = UserHandle.getUserId(callingUid);
16205        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16206        if (pi == null) {
16207            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16208                    + callingUserId);
16209        }
16210        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16211            throw new SecurityException("Calling uid " + callingUid
16212                    + " does not own package " + pkg);
16213        }
16214    }
16215
16216    @Override
16217    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16218        Intent intent = new Intent(Intent.ACTION_MAIN);
16219        intent.addCategory(Intent.CATEGORY_HOME);
16220
16221        final int callingUserId = UserHandle.getCallingUserId();
16222        List<ResolveInfo> list = queryIntentActivities(intent, null,
16223                PackageManager.GET_META_DATA, callingUserId);
16224        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16225                true, false, false, callingUserId);
16226
16227        allHomeCandidates.clear();
16228        if (list != null) {
16229            for (ResolveInfo ri : list) {
16230                allHomeCandidates.add(ri);
16231            }
16232        }
16233        return (preferred == null || preferred.activityInfo == null)
16234                ? null
16235                : new ComponentName(preferred.activityInfo.packageName,
16236                        preferred.activityInfo.name);
16237    }
16238
16239    @Override
16240    public void setApplicationEnabledSetting(String appPackageName,
16241            int newState, int flags, int userId, String callingPackage) {
16242        if (!sUserManager.exists(userId)) return;
16243        if (callingPackage == null) {
16244            callingPackage = Integer.toString(Binder.getCallingUid());
16245        }
16246        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16247    }
16248
16249    @Override
16250    public void setComponentEnabledSetting(ComponentName componentName,
16251            int newState, int flags, int userId) {
16252        if (!sUserManager.exists(userId)) return;
16253        setEnabledSetting(componentName.getPackageName(),
16254                componentName.getClassName(), newState, flags, userId, null);
16255    }
16256
16257    private void setEnabledSetting(final String packageName, String className, int newState,
16258            final int flags, int userId, String callingPackage) {
16259        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16260              || newState == COMPONENT_ENABLED_STATE_ENABLED
16261              || newState == COMPONENT_ENABLED_STATE_DISABLED
16262              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16263              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16264            throw new IllegalArgumentException("Invalid new component state: "
16265                    + newState);
16266        }
16267        PackageSetting pkgSetting;
16268        final int uid = Binder.getCallingUid();
16269        final int permission = mContext.checkCallingOrSelfPermission(
16270                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16271        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
16272        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16273        boolean sendNow = false;
16274        boolean isApp = (className == null);
16275        String componentName = isApp ? packageName : className;
16276        int packageUid = -1;
16277        ArrayList<String> components;
16278
16279        // writer
16280        synchronized (mPackages) {
16281            pkgSetting = mSettings.mPackages.get(packageName);
16282            if (pkgSetting == null) {
16283                if (className == null) {
16284                    throw new IllegalArgumentException("Unknown package: " + packageName);
16285                }
16286                throw new IllegalArgumentException(
16287                        "Unknown component: " + packageName + "/" + className);
16288            }
16289            // Allow root and verify that userId is not being specified by a different user
16290            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16291                throw new SecurityException(
16292                        "Permission Denial: attempt to change component state from pid="
16293                        + Binder.getCallingPid()
16294                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16295            }
16296            if (className == null) {
16297                // We're dealing with an application/package level state change
16298                if (pkgSetting.getEnabled(userId) == newState) {
16299                    // Nothing to do
16300                    return;
16301                }
16302                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16303                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16304                    // Don't care about who enables an app.
16305                    callingPackage = null;
16306                }
16307                pkgSetting.setEnabled(newState, userId, callingPackage);
16308                // pkgSetting.pkg.mSetEnabled = newState;
16309            } else {
16310                // We're dealing with a component level state change
16311                // First, verify that this is a valid class name.
16312                PackageParser.Package pkg = pkgSetting.pkg;
16313                if (pkg == null || !pkg.hasComponentClassName(className)) {
16314                    if (pkg != null &&
16315                            pkg.applicationInfo.targetSdkVersion >=
16316                                    Build.VERSION_CODES.JELLY_BEAN) {
16317                        throw new IllegalArgumentException("Component class " + className
16318                                + " does not exist in " + packageName);
16319                    } else {
16320                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16321                                + className + " does not exist in " + packageName);
16322                    }
16323                }
16324                switch (newState) {
16325                case COMPONENT_ENABLED_STATE_ENABLED:
16326                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16327                        return;
16328                    }
16329                    break;
16330                case COMPONENT_ENABLED_STATE_DISABLED:
16331                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16332                        return;
16333                    }
16334                    break;
16335                case COMPONENT_ENABLED_STATE_DEFAULT:
16336                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16337                        return;
16338                    }
16339                    break;
16340                default:
16341                    Slog.e(TAG, "Invalid new component state: " + newState);
16342                    return;
16343                }
16344            }
16345            scheduleWritePackageRestrictionsLocked(userId);
16346            components = mPendingBroadcasts.get(userId, packageName);
16347            final boolean newPackage = components == null;
16348            if (newPackage) {
16349                components = new ArrayList<String>();
16350            }
16351            if (!components.contains(componentName)) {
16352                components.add(componentName);
16353            }
16354            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16355                sendNow = true;
16356                // Purge entry from pending broadcast list if another one exists already
16357                // since we are sending one right away.
16358                mPendingBroadcasts.remove(userId, packageName);
16359            } else {
16360                if (newPackage) {
16361                    mPendingBroadcasts.put(userId, packageName, components);
16362                }
16363                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16364                    // Schedule a message
16365                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16366                }
16367            }
16368        }
16369
16370        long callingId = Binder.clearCallingIdentity();
16371        try {
16372            if (sendNow) {
16373                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16374                sendPackageChangedBroadcast(packageName,
16375                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16376            }
16377        } finally {
16378            Binder.restoreCallingIdentity(callingId);
16379        }
16380    }
16381
16382    private void sendPackageChangedBroadcast(String packageName,
16383            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16384        if (DEBUG_INSTALL)
16385            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16386                    + componentNames);
16387        Bundle extras = new Bundle(4);
16388        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16389        String nameList[] = new String[componentNames.size()];
16390        componentNames.toArray(nameList);
16391        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16392        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16393        extras.putInt(Intent.EXTRA_UID, packageUid);
16394        // If this is not reporting a change of the overall package, then only send it
16395        // to registered receivers.  We don't want to launch a swath of apps for every
16396        // little component state change.
16397        final int flags = !componentNames.contains(packageName)
16398                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16399        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16400                new int[] {UserHandle.getUserId(packageUid)});
16401    }
16402
16403    @Override
16404    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16405        if (!sUserManager.exists(userId)) return;
16406        final int uid = Binder.getCallingUid();
16407        final int permission = mContext.checkCallingOrSelfPermission(
16408                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16409        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16410        enforceCrossUserPermission(uid, userId, true, true, "stop package");
16411        // writer
16412        synchronized (mPackages) {
16413            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16414                    allowedByPermission, uid, userId)) {
16415                scheduleWritePackageRestrictionsLocked(userId);
16416            }
16417        }
16418    }
16419
16420    @Override
16421    public String getInstallerPackageName(String packageName) {
16422        // reader
16423        synchronized (mPackages) {
16424            return mSettings.getInstallerPackageNameLPr(packageName);
16425        }
16426    }
16427
16428    @Override
16429    public int getApplicationEnabledSetting(String packageName, int userId) {
16430        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16431        int uid = Binder.getCallingUid();
16432        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
16433        // reader
16434        synchronized (mPackages) {
16435            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16436        }
16437    }
16438
16439    @Override
16440    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16441        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16442        int uid = Binder.getCallingUid();
16443        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
16444        // reader
16445        synchronized (mPackages) {
16446            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16447        }
16448    }
16449
16450    @Override
16451    public void enterSafeMode() {
16452        enforceSystemOrRoot("Only the system can request entering safe mode");
16453
16454        if (!mSystemReady) {
16455            mSafeMode = true;
16456        }
16457    }
16458
16459    @Override
16460    public void systemReady() {
16461        mSystemReady = true;
16462
16463        // Read the compatibilty setting when the system is ready.
16464        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16465                mContext.getContentResolver(),
16466                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16467        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16468        if (DEBUG_SETTINGS) {
16469            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16470        }
16471
16472        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16473
16474        synchronized (mPackages) {
16475            // Verify that all of the preferred activity components actually
16476            // exist.  It is possible for applications to be updated and at
16477            // that point remove a previously declared activity component that
16478            // had been set as a preferred activity.  We try to clean this up
16479            // the next time we encounter that preferred activity, but it is
16480            // possible for the user flow to never be able to return to that
16481            // situation so here we do a sanity check to make sure we haven't
16482            // left any junk around.
16483            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16484            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16485                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16486                removed.clear();
16487                for (PreferredActivity pa : pir.filterSet()) {
16488                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16489                        removed.add(pa);
16490                    }
16491                }
16492                if (removed.size() > 0) {
16493                    for (int r=0; r<removed.size(); r++) {
16494                        PreferredActivity pa = removed.get(r);
16495                        Slog.w(TAG, "Removing dangling preferred activity: "
16496                                + pa.mPref.mComponent);
16497                        pir.removeFilter(pa);
16498                    }
16499                    mSettings.writePackageRestrictionsLPr(
16500                            mSettings.mPreferredActivities.keyAt(i));
16501                }
16502            }
16503
16504            for (int userId : UserManagerService.getInstance().getUserIds()) {
16505                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16506                    grantPermissionsUserIds = ArrayUtils.appendInt(
16507                            grantPermissionsUserIds, userId);
16508                }
16509            }
16510        }
16511        sUserManager.systemReady();
16512
16513        // If we upgraded grant all default permissions before kicking off.
16514        for (int userId : grantPermissionsUserIds) {
16515            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16516        }
16517
16518        // Kick off any messages waiting for system ready
16519        if (mPostSystemReadyMessages != null) {
16520            for (Message msg : mPostSystemReadyMessages) {
16521                msg.sendToTarget();
16522            }
16523            mPostSystemReadyMessages = null;
16524        }
16525
16526        // Watch for external volumes that come and go over time
16527        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16528        storage.registerListener(mStorageListener);
16529
16530        mInstallerService.systemReady();
16531        mPackageDexOptimizer.systemReady();
16532
16533        MountServiceInternal mountServiceInternal = LocalServices.getService(
16534                MountServiceInternal.class);
16535        mountServiceInternal.addExternalStoragePolicy(
16536                new MountServiceInternal.ExternalStorageMountPolicy() {
16537            @Override
16538            public int getMountMode(int uid, String packageName) {
16539                if (Process.isIsolated(uid)) {
16540                    return Zygote.MOUNT_EXTERNAL_NONE;
16541                }
16542                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16543                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16544                }
16545                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16546                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16547                }
16548                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16549                    return Zygote.MOUNT_EXTERNAL_READ;
16550                }
16551                return Zygote.MOUNT_EXTERNAL_WRITE;
16552            }
16553
16554            @Override
16555            public boolean hasExternalStorage(int uid, String packageName) {
16556                return true;
16557            }
16558        });
16559    }
16560
16561    @Override
16562    public boolean isSafeMode() {
16563        return mSafeMode;
16564    }
16565
16566    @Override
16567    public boolean hasSystemUidErrors() {
16568        return mHasSystemUidErrors;
16569    }
16570
16571    static String arrayToString(int[] array) {
16572        StringBuffer buf = new StringBuffer(128);
16573        buf.append('[');
16574        if (array != null) {
16575            for (int i=0; i<array.length; i++) {
16576                if (i > 0) buf.append(", ");
16577                buf.append(array[i]);
16578            }
16579        }
16580        buf.append(']');
16581        return buf.toString();
16582    }
16583
16584    static class DumpState {
16585        public static final int DUMP_LIBS = 1 << 0;
16586        public static final int DUMP_FEATURES = 1 << 1;
16587        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16588        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16589        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16590        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16591        public static final int DUMP_PERMISSIONS = 1 << 6;
16592        public static final int DUMP_PACKAGES = 1 << 7;
16593        public static final int DUMP_SHARED_USERS = 1 << 8;
16594        public static final int DUMP_MESSAGES = 1 << 9;
16595        public static final int DUMP_PROVIDERS = 1 << 10;
16596        public static final int DUMP_VERIFIERS = 1 << 11;
16597        public static final int DUMP_PREFERRED = 1 << 12;
16598        public static final int DUMP_PREFERRED_XML = 1 << 13;
16599        public static final int DUMP_KEYSETS = 1 << 14;
16600        public static final int DUMP_VERSION = 1 << 15;
16601        public static final int DUMP_INSTALLS = 1 << 16;
16602        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16603        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16604
16605        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16606
16607        private int mTypes;
16608
16609        private int mOptions;
16610
16611        private boolean mTitlePrinted;
16612
16613        private SharedUserSetting mSharedUser;
16614
16615        public boolean isDumping(int type) {
16616            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16617                return true;
16618            }
16619
16620            return (mTypes & type) != 0;
16621        }
16622
16623        public void setDump(int type) {
16624            mTypes |= type;
16625        }
16626
16627        public boolean isOptionEnabled(int option) {
16628            return (mOptions & option) != 0;
16629        }
16630
16631        public void setOptionEnabled(int option) {
16632            mOptions |= option;
16633        }
16634
16635        public boolean onTitlePrinted() {
16636            final boolean printed = mTitlePrinted;
16637            mTitlePrinted = true;
16638            return printed;
16639        }
16640
16641        public boolean getTitlePrinted() {
16642            return mTitlePrinted;
16643        }
16644
16645        public void setTitlePrinted(boolean enabled) {
16646            mTitlePrinted = enabled;
16647        }
16648
16649        public SharedUserSetting getSharedUser() {
16650            return mSharedUser;
16651        }
16652
16653        public void setSharedUser(SharedUserSetting user) {
16654            mSharedUser = user;
16655        }
16656    }
16657
16658    @Override
16659    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16660            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16661        (new PackageManagerShellCommand(this)).exec(
16662                this, in, out, err, args, resultReceiver);
16663    }
16664
16665    @Override
16666    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16667        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16668                != PackageManager.PERMISSION_GRANTED) {
16669            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16670                    + Binder.getCallingPid()
16671                    + ", uid=" + Binder.getCallingUid()
16672                    + " without permission "
16673                    + android.Manifest.permission.DUMP);
16674            return;
16675        }
16676
16677        DumpState dumpState = new DumpState();
16678        boolean fullPreferred = false;
16679        boolean checkin = false;
16680
16681        String packageName = null;
16682        ArraySet<String> permissionNames = null;
16683
16684        int opti = 0;
16685        while (opti < args.length) {
16686            String opt = args[opti];
16687            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16688                break;
16689            }
16690            opti++;
16691
16692            if ("-a".equals(opt)) {
16693                // Right now we only know how to print all.
16694            } else if ("-h".equals(opt)) {
16695                pw.println("Package manager dump options:");
16696                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
16697                pw.println("    --checkin: dump for a checkin");
16698                pw.println("    -f: print details of intent filters");
16699                pw.println("    -h: print this help");
16700                pw.println("  cmd may be one of:");
16701                pw.println("    l[ibraries]: list known shared libraries");
16702                pw.println("    f[eatures]: list device features");
16703                pw.println("    k[eysets]: print known keysets");
16704                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
16705                pw.println("    perm[issions]: dump permissions");
16706                pw.println("    permission [name ...]: dump declaration and use of given permission");
16707                pw.println("    pref[erred]: print preferred package settings");
16708                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
16709                pw.println("    prov[iders]: dump content providers");
16710                pw.println("    p[ackages]: dump installed packages");
16711                pw.println("    s[hared-users]: dump shared user IDs");
16712                pw.println("    m[essages]: print collected runtime messages");
16713                pw.println("    v[erifiers]: print package verifier info");
16714                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
16715                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
16716                pw.println("    version: print database version info");
16717                pw.println("    write: write current settings now");
16718                pw.println("    installs: details about install sessions");
16719                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
16720                pw.println("    <package.name>: info about given package");
16721                return;
16722            } else if ("--checkin".equals(opt)) {
16723                checkin = true;
16724            } else if ("-f".equals(opt)) {
16725                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16726            } else {
16727                pw.println("Unknown argument: " + opt + "; use -h for help");
16728            }
16729        }
16730
16731        // Is the caller requesting to dump a particular piece of data?
16732        if (opti < args.length) {
16733            String cmd = args[opti];
16734            opti++;
16735            // Is this a package name?
16736            if ("android".equals(cmd) || cmd.contains(".")) {
16737                packageName = cmd;
16738                // When dumping a single package, we always dump all of its
16739                // filter information since the amount of data will be reasonable.
16740                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
16741            } else if ("check-permission".equals(cmd)) {
16742                if (opti >= args.length) {
16743                    pw.println("Error: check-permission missing permission argument");
16744                    return;
16745                }
16746                String perm = args[opti];
16747                opti++;
16748                if (opti >= args.length) {
16749                    pw.println("Error: check-permission missing package argument");
16750                    return;
16751                }
16752                String pkg = args[opti];
16753                opti++;
16754                int user = UserHandle.getUserId(Binder.getCallingUid());
16755                if (opti < args.length) {
16756                    try {
16757                        user = Integer.parseInt(args[opti]);
16758                    } catch (NumberFormatException e) {
16759                        pw.println("Error: check-permission user argument is not a number: "
16760                                + args[opti]);
16761                        return;
16762                    }
16763                }
16764                pw.println(checkPermission(perm, pkg, user));
16765                return;
16766            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
16767                dumpState.setDump(DumpState.DUMP_LIBS);
16768            } else if ("f".equals(cmd) || "features".equals(cmd)) {
16769                dumpState.setDump(DumpState.DUMP_FEATURES);
16770            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
16771                if (opti >= args.length) {
16772                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
16773                            | DumpState.DUMP_SERVICE_RESOLVERS
16774                            | DumpState.DUMP_RECEIVER_RESOLVERS
16775                            | DumpState.DUMP_CONTENT_RESOLVERS);
16776                } else {
16777                    while (opti < args.length) {
16778                        String name = args[opti];
16779                        if ("a".equals(name) || "activity".equals(name)) {
16780                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
16781                        } else if ("s".equals(name) || "service".equals(name)) {
16782                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
16783                        } else if ("r".equals(name) || "receiver".equals(name)) {
16784                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
16785                        } else if ("c".equals(name) || "content".equals(name)) {
16786                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
16787                        } else {
16788                            pw.println("Error: unknown resolver table type: " + name);
16789                            return;
16790                        }
16791                        opti++;
16792                    }
16793                }
16794            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
16795                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
16796            } else if ("permission".equals(cmd)) {
16797                if (opti >= args.length) {
16798                    pw.println("Error: permission requires permission name");
16799                    return;
16800                }
16801                permissionNames = new ArraySet<>();
16802                while (opti < args.length) {
16803                    permissionNames.add(args[opti]);
16804                    opti++;
16805                }
16806                dumpState.setDump(DumpState.DUMP_PERMISSIONS
16807                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
16808            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
16809                dumpState.setDump(DumpState.DUMP_PREFERRED);
16810            } else if ("preferred-xml".equals(cmd)) {
16811                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
16812                if (opti < args.length && "--full".equals(args[opti])) {
16813                    fullPreferred = true;
16814                    opti++;
16815                }
16816            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
16817                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
16818            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
16819                dumpState.setDump(DumpState.DUMP_PACKAGES);
16820            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
16821                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
16822            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
16823                dumpState.setDump(DumpState.DUMP_PROVIDERS);
16824            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
16825                dumpState.setDump(DumpState.DUMP_MESSAGES);
16826            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
16827                dumpState.setDump(DumpState.DUMP_VERIFIERS);
16828            } else if ("i".equals(cmd) || "ifv".equals(cmd)
16829                    || "intent-filter-verifiers".equals(cmd)) {
16830                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
16831            } else if ("version".equals(cmd)) {
16832                dumpState.setDump(DumpState.DUMP_VERSION);
16833            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
16834                dumpState.setDump(DumpState.DUMP_KEYSETS);
16835            } else if ("installs".equals(cmd)) {
16836                dumpState.setDump(DumpState.DUMP_INSTALLS);
16837            } else if ("write".equals(cmd)) {
16838                synchronized (mPackages) {
16839                    mSettings.writeLPr();
16840                    pw.println("Settings written.");
16841                    return;
16842                }
16843            }
16844        }
16845
16846        if (checkin) {
16847            pw.println("vers,1");
16848        }
16849
16850        // reader
16851        synchronized (mPackages) {
16852            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
16853                if (!checkin) {
16854                    if (dumpState.onTitlePrinted())
16855                        pw.println();
16856                    pw.println("Database versions:");
16857                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
16858                }
16859            }
16860
16861            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
16862                if (!checkin) {
16863                    if (dumpState.onTitlePrinted())
16864                        pw.println();
16865                    pw.println("Verifiers:");
16866                    pw.print("  Required: ");
16867                    pw.print(mRequiredVerifierPackage);
16868                    pw.print(" (uid=");
16869                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16870                            UserHandle.USER_SYSTEM));
16871                    pw.println(")");
16872                } else if (mRequiredVerifierPackage != null) {
16873                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16874                    pw.print(",");
16875                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16876                            UserHandle.USER_SYSTEM));
16877                }
16878            }
16879
16880            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16881                    packageName == null) {
16882                if (mIntentFilterVerifierComponent != null) {
16883                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16884                    if (!checkin) {
16885                        if (dumpState.onTitlePrinted())
16886                            pw.println();
16887                        pw.println("Intent Filter Verifier:");
16888                        pw.print("  Using: ");
16889                        pw.print(verifierPackageName);
16890                        pw.print(" (uid=");
16891                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16892                                UserHandle.USER_SYSTEM));
16893                        pw.println(")");
16894                    } else if (verifierPackageName != null) {
16895                        pw.print("ifv,"); pw.print(verifierPackageName);
16896                        pw.print(",");
16897                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16898                                UserHandle.USER_SYSTEM));
16899                    }
16900                } else {
16901                    pw.println();
16902                    pw.println("No Intent Filter Verifier available!");
16903                }
16904            }
16905
16906            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16907                boolean printedHeader = false;
16908                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16909                while (it.hasNext()) {
16910                    String name = it.next();
16911                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16912                    if (!checkin) {
16913                        if (!printedHeader) {
16914                            if (dumpState.onTitlePrinted())
16915                                pw.println();
16916                            pw.println("Libraries:");
16917                            printedHeader = true;
16918                        }
16919                        pw.print("  ");
16920                    } else {
16921                        pw.print("lib,");
16922                    }
16923                    pw.print(name);
16924                    if (!checkin) {
16925                        pw.print(" -> ");
16926                    }
16927                    if (ent.path != null) {
16928                        if (!checkin) {
16929                            pw.print("(jar) ");
16930                            pw.print(ent.path);
16931                        } else {
16932                            pw.print(",jar,");
16933                            pw.print(ent.path);
16934                        }
16935                    } else {
16936                        if (!checkin) {
16937                            pw.print("(apk) ");
16938                            pw.print(ent.apk);
16939                        } else {
16940                            pw.print(",apk,");
16941                            pw.print(ent.apk);
16942                        }
16943                    }
16944                    pw.println();
16945                }
16946            }
16947
16948            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16949                if (dumpState.onTitlePrinted())
16950                    pw.println();
16951                if (!checkin) {
16952                    pw.println("Features:");
16953                }
16954
16955                for (FeatureInfo feat : mAvailableFeatures.values()) {
16956                    if (checkin) {
16957                        pw.print("feat,");
16958                        pw.print(feat.name);
16959                        pw.print(",");
16960                        pw.println(feat.version);
16961                    } else {
16962                        pw.print("  ");
16963                        pw.print(feat.name);
16964                        if (feat.version > 0) {
16965                            pw.print(" version=");
16966                            pw.print(feat.version);
16967                        }
16968                        pw.println();
16969                    }
16970                }
16971            }
16972
16973            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16974                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16975                        : "Activity Resolver Table:", "  ", packageName,
16976                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16977                    dumpState.setTitlePrinted(true);
16978                }
16979            }
16980            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16981                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16982                        : "Receiver Resolver Table:", "  ", packageName,
16983                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16984                    dumpState.setTitlePrinted(true);
16985                }
16986            }
16987            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16988                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16989                        : "Service Resolver Table:", "  ", packageName,
16990                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16991                    dumpState.setTitlePrinted(true);
16992                }
16993            }
16994            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16995                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16996                        : "Provider Resolver Table:", "  ", packageName,
16997                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16998                    dumpState.setTitlePrinted(true);
16999                }
17000            }
17001
17002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17003                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17004                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17005                    int user = mSettings.mPreferredActivities.keyAt(i);
17006                    if (pir.dump(pw,
17007                            dumpState.getTitlePrinted()
17008                                ? "\nPreferred Activities User " + user + ":"
17009                                : "Preferred Activities User " + user + ":", "  ",
17010                            packageName, true, false)) {
17011                        dumpState.setTitlePrinted(true);
17012                    }
17013                }
17014            }
17015
17016            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17017                pw.flush();
17018                FileOutputStream fout = new FileOutputStream(fd);
17019                BufferedOutputStream str = new BufferedOutputStream(fout);
17020                XmlSerializer serializer = new FastXmlSerializer();
17021                try {
17022                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17023                    serializer.startDocument(null, true);
17024                    serializer.setFeature(
17025                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17026                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17027                    serializer.endDocument();
17028                    serializer.flush();
17029                } catch (IllegalArgumentException e) {
17030                    pw.println("Failed writing: " + e);
17031                } catch (IllegalStateException e) {
17032                    pw.println("Failed writing: " + e);
17033                } catch (IOException e) {
17034                    pw.println("Failed writing: " + e);
17035                }
17036            }
17037
17038            if (!checkin
17039                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17040                    && packageName == null) {
17041                pw.println();
17042                int count = mSettings.mPackages.size();
17043                if (count == 0) {
17044                    pw.println("No applications!");
17045                    pw.println();
17046                } else {
17047                    final String prefix = "  ";
17048                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17049                    if (allPackageSettings.size() == 0) {
17050                        pw.println("No domain preferred apps!");
17051                        pw.println();
17052                    } else {
17053                        pw.println("App verification status:");
17054                        pw.println();
17055                        count = 0;
17056                        for (PackageSetting ps : allPackageSettings) {
17057                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17058                            if (ivi == null || ivi.getPackageName() == null) continue;
17059                            pw.println(prefix + "Package: " + ivi.getPackageName());
17060                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17061                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17062                            pw.println();
17063                            count++;
17064                        }
17065                        if (count == 0) {
17066                            pw.println(prefix + "No app verification established.");
17067                            pw.println();
17068                        }
17069                        for (int userId : sUserManager.getUserIds()) {
17070                            pw.println("App linkages for user " + userId + ":");
17071                            pw.println();
17072                            count = 0;
17073                            for (PackageSetting ps : allPackageSettings) {
17074                                final long status = ps.getDomainVerificationStatusForUser(userId);
17075                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17076                                    continue;
17077                                }
17078                                pw.println(prefix + "Package: " + ps.name);
17079                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17080                                String statusStr = IntentFilterVerificationInfo.
17081                                        getStatusStringFromValue(status);
17082                                pw.println(prefix + "Status:  " + statusStr);
17083                                pw.println();
17084                                count++;
17085                            }
17086                            if (count == 0) {
17087                                pw.println(prefix + "No configured app linkages.");
17088                                pw.println();
17089                            }
17090                        }
17091                    }
17092                }
17093            }
17094
17095            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17096                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17097                if (packageName == null && permissionNames == null) {
17098                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17099                        if (iperm == 0) {
17100                            if (dumpState.onTitlePrinted())
17101                                pw.println();
17102                            pw.println("AppOp Permissions:");
17103                        }
17104                        pw.print("  AppOp Permission ");
17105                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17106                        pw.println(":");
17107                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17108                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17109                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17110                        }
17111                    }
17112                }
17113            }
17114
17115            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17116                boolean printedSomething = false;
17117                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17118                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17119                        continue;
17120                    }
17121                    if (!printedSomething) {
17122                        if (dumpState.onTitlePrinted())
17123                            pw.println();
17124                        pw.println("Registered ContentProviders:");
17125                        printedSomething = true;
17126                    }
17127                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17128                    pw.print("    "); pw.println(p.toString());
17129                }
17130                printedSomething = false;
17131                for (Map.Entry<String, PackageParser.Provider> entry :
17132                        mProvidersByAuthority.entrySet()) {
17133                    PackageParser.Provider p = entry.getValue();
17134                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17135                        continue;
17136                    }
17137                    if (!printedSomething) {
17138                        if (dumpState.onTitlePrinted())
17139                            pw.println();
17140                        pw.println("ContentProvider Authorities:");
17141                        printedSomething = true;
17142                    }
17143                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17144                    pw.print("    "); pw.println(p.toString());
17145                    if (p.info != null && p.info.applicationInfo != null) {
17146                        final String appInfo = p.info.applicationInfo.toString();
17147                        pw.print("      applicationInfo="); pw.println(appInfo);
17148                    }
17149                }
17150            }
17151
17152            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17153                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17154            }
17155
17156            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17157                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17158            }
17159
17160            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17161                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17162            }
17163
17164            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17165                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17166            }
17167
17168            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17169                // XXX should handle packageName != null by dumping only install data that
17170                // the given package is involved with.
17171                if (dumpState.onTitlePrinted()) pw.println();
17172                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17173            }
17174
17175            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17176                if (dumpState.onTitlePrinted()) pw.println();
17177                mSettings.dumpReadMessagesLPr(pw, dumpState);
17178
17179                pw.println();
17180                pw.println("Package warning messages:");
17181                BufferedReader in = null;
17182                String line = null;
17183                try {
17184                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17185                    while ((line = in.readLine()) != null) {
17186                        if (line.contains("ignored: updated version")) continue;
17187                        pw.println(line);
17188                    }
17189                } catch (IOException ignored) {
17190                } finally {
17191                    IoUtils.closeQuietly(in);
17192                }
17193            }
17194
17195            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17196                BufferedReader in = null;
17197                String line = null;
17198                try {
17199                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17200                    while ((line = in.readLine()) != null) {
17201                        if (line.contains("ignored: updated version")) continue;
17202                        pw.print("msg,");
17203                        pw.println(line);
17204                    }
17205                } catch (IOException ignored) {
17206                } finally {
17207                    IoUtils.closeQuietly(in);
17208                }
17209            }
17210        }
17211    }
17212
17213    private String dumpDomainString(String packageName) {
17214        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
17215        List<IntentFilter> filters = getAllIntentFilters(packageName);
17216
17217        ArraySet<String> result = new ArraySet<>();
17218        if (iviList.size() > 0) {
17219            for (IntentFilterVerificationInfo ivi : iviList) {
17220                for (String host : ivi.getDomains()) {
17221                    result.add(host);
17222                }
17223            }
17224        }
17225        if (filters != null && filters.size() > 0) {
17226            for (IntentFilter filter : filters) {
17227                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17228                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17229                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17230                    result.addAll(filter.getHostsList());
17231                }
17232            }
17233        }
17234
17235        StringBuilder sb = new StringBuilder(result.size() * 16);
17236        for (String domain : result) {
17237            if (sb.length() > 0) sb.append(" ");
17238            sb.append(domain);
17239        }
17240        return sb.toString();
17241    }
17242
17243    // ------- apps on sdcard specific code -------
17244    static final boolean DEBUG_SD_INSTALL = false;
17245
17246    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17247
17248    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17249
17250    private boolean mMediaMounted = false;
17251
17252    static String getEncryptKey() {
17253        try {
17254            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17255                    SD_ENCRYPTION_KEYSTORE_NAME);
17256            if (sdEncKey == null) {
17257                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17258                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17259                if (sdEncKey == null) {
17260                    Slog.e(TAG, "Failed to create encryption keys");
17261                    return null;
17262                }
17263            }
17264            return sdEncKey;
17265        } catch (NoSuchAlgorithmException nsae) {
17266            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17267            return null;
17268        } catch (IOException ioe) {
17269            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17270            return null;
17271        }
17272    }
17273
17274    /*
17275     * Update media status on PackageManager.
17276     */
17277    @Override
17278    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17279        int callingUid = Binder.getCallingUid();
17280        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17281            throw new SecurityException("Media status can only be updated by the system");
17282        }
17283        // reader; this apparently protects mMediaMounted, but should probably
17284        // be a different lock in that case.
17285        synchronized (mPackages) {
17286            Log.i(TAG, "Updating external media status from "
17287                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17288                    + (mediaStatus ? "mounted" : "unmounted"));
17289            if (DEBUG_SD_INSTALL)
17290                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17291                        + ", mMediaMounted=" + mMediaMounted);
17292            if (mediaStatus == mMediaMounted) {
17293                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17294                        : 0, -1);
17295                mHandler.sendMessage(msg);
17296                return;
17297            }
17298            mMediaMounted = mediaStatus;
17299        }
17300        // Queue up an async operation since the package installation may take a
17301        // little while.
17302        mHandler.post(new Runnable() {
17303            public void run() {
17304                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17305            }
17306        });
17307    }
17308
17309    /**
17310     * Called by MountService when the initial ASECs to scan are available.
17311     * Should block until all the ASEC containers are finished being scanned.
17312     */
17313    public void scanAvailableAsecs() {
17314        updateExternalMediaStatusInner(true, false, false);
17315    }
17316
17317    /*
17318     * Collect information of applications on external media, map them against
17319     * existing containers and update information based on current mount status.
17320     * Please note that we always have to report status if reportStatus has been
17321     * set to true especially when unloading packages.
17322     */
17323    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17324            boolean externalStorage) {
17325        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17326        int[] uidArr = EmptyArray.INT;
17327
17328        final String[] list = PackageHelper.getSecureContainerList();
17329        if (ArrayUtils.isEmpty(list)) {
17330            Log.i(TAG, "No secure containers found");
17331        } else {
17332            // Process list of secure containers and categorize them
17333            // as active or stale based on their package internal state.
17334
17335            // reader
17336            synchronized (mPackages) {
17337                for (String cid : list) {
17338                    // Leave stages untouched for now; installer service owns them
17339                    if (PackageInstallerService.isStageName(cid)) continue;
17340
17341                    if (DEBUG_SD_INSTALL)
17342                        Log.i(TAG, "Processing container " + cid);
17343                    String pkgName = getAsecPackageName(cid);
17344                    if (pkgName == null) {
17345                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17346                        continue;
17347                    }
17348                    if (DEBUG_SD_INSTALL)
17349                        Log.i(TAG, "Looking for pkg : " + pkgName);
17350
17351                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17352                    if (ps == null) {
17353                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17354                        continue;
17355                    }
17356
17357                    /*
17358                     * Skip packages that are not external if we're unmounting
17359                     * external storage.
17360                     */
17361                    if (externalStorage && !isMounted && !isExternal(ps)) {
17362                        continue;
17363                    }
17364
17365                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17366                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17367                    // The package status is changed only if the code path
17368                    // matches between settings and the container id.
17369                    if (ps.codePathString != null
17370                            && ps.codePathString.startsWith(args.getCodePath())) {
17371                        if (DEBUG_SD_INSTALL) {
17372                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17373                                    + " at code path: " + ps.codePathString);
17374                        }
17375
17376                        // We do have a valid package installed on sdcard
17377                        processCids.put(args, ps.codePathString);
17378                        final int uid = ps.appId;
17379                        if (uid != -1) {
17380                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17381                        }
17382                    } else {
17383                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17384                                + ps.codePathString);
17385                    }
17386                }
17387            }
17388
17389            Arrays.sort(uidArr);
17390        }
17391
17392        // Process packages with valid entries.
17393        if (isMounted) {
17394            if (DEBUG_SD_INSTALL)
17395                Log.i(TAG, "Loading packages");
17396            loadMediaPackages(processCids, uidArr, externalStorage);
17397            startCleaningPackages();
17398            mInstallerService.onSecureContainersAvailable();
17399        } else {
17400            if (DEBUG_SD_INSTALL)
17401                Log.i(TAG, "Unloading packages");
17402            unloadMediaPackages(processCids, uidArr, reportStatus);
17403        }
17404    }
17405
17406    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17407            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17408        final int size = infos.size();
17409        final String[] packageNames = new String[size];
17410        final int[] packageUids = new int[size];
17411        for (int i = 0; i < size; i++) {
17412            final ApplicationInfo info = infos.get(i);
17413            packageNames[i] = info.packageName;
17414            packageUids[i] = info.uid;
17415        }
17416        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17417                finishedReceiver);
17418    }
17419
17420    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17421            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17422        sendResourcesChangedBroadcast(mediaStatus, replacing,
17423                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17424    }
17425
17426    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17427            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17428        int size = pkgList.length;
17429        if (size > 0) {
17430            // Send broadcasts here
17431            Bundle extras = new Bundle();
17432            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17433            if (uidArr != null) {
17434                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17435            }
17436            if (replacing) {
17437                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17438            }
17439            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17440                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17441            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17442        }
17443    }
17444
17445   /*
17446     * Look at potentially valid container ids from processCids If package
17447     * information doesn't match the one on record or package scanning fails,
17448     * the cid is added to list of removeCids. We currently don't delete stale
17449     * containers.
17450     */
17451    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17452            boolean externalStorage) {
17453        ArrayList<String> pkgList = new ArrayList<String>();
17454        Set<AsecInstallArgs> keys = processCids.keySet();
17455
17456        for (AsecInstallArgs args : keys) {
17457            String codePath = processCids.get(args);
17458            if (DEBUG_SD_INSTALL)
17459                Log.i(TAG, "Loading container : " + args.cid);
17460            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17461            try {
17462                // Make sure there are no container errors first.
17463                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17464                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17465                            + " when installing from sdcard");
17466                    continue;
17467                }
17468                // Check code path here.
17469                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17470                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17471                            + " does not match one in settings " + codePath);
17472                    continue;
17473                }
17474                // Parse package
17475                int parseFlags = mDefParseFlags;
17476                if (args.isExternalAsec()) {
17477                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17478                }
17479                if (args.isFwdLocked()) {
17480                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17481                }
17482
17483                synchronized (mInstallLock) {
17484                    PackageParser.Package pkg = null;
17485                    try {
17486                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17487                    } catch (PackageManagerException e) {
17488                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17489                    }
17490                    // Scan the package
17491                    if (pkg != null) {
17492                        /*
17493                         * TODO why is the lock being held? doPostInstall is
17494                         * called in other places without the lock. This needs
17495                         * to be straightened out.
17496                         */
17497                        // writer
17498                        synchronized (mPackages) {
17499                            retCode = PackageManager.INSTALL_SUCCEEDED;
17500                            pkgList.add(pkg.packageName);
17501                            // Post process args
17502                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17503                                    pkg.applicationInfo.uid);
17504                        }
17505                    } else {
17506                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17507                    }
17508                }
17509
17510            } finally {
17511                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17512                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17513                }
17514            }
17515        }
17516        // writer
17517        synchronized (mPackages) {
17518            // If the platform SDK has changed since the last time we booted,
17519            // we need to re-grant app permission to catch any new ones that
17520            // appear. This is really a hack, and means that apps can in some
17521            // cases get permissions that the user didn't initially explicitly
17522            // allow... it would be nice to have some better way to handle
17523            // this situation.
17524            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17525                    : mSettings.getInternalVersion();
17526            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17527                    : StorageManager.UUID_PRIVATE_INTERNAL;
17528
17529            int updateFlags = UPDATE_PERMISSIONS_ALL;
17530            if (ver.sdkVersion != mSdkVersion) {
17531                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17532                        + mSdkVersion + "; regranting permissions for external");
17533                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17534            }
17535            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17536
17537            // Yay, everything is now upgraded
17538            ver.forceCurrent();
17539
17540            // can downgrade to reader
17541            // Persist settings
17542            mSettings.writeLPr();
17543        }
17544        // Send a broadcast to let everyone know we are done processing
17545        if (pkgList.size() > 0) {
17546            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17547        }
17548    }
17549
17550   /*
17551     * Utility method to unload a list of specified containers
17552     */
17553    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17554        // Just unmount all valid containers.
17555        for (AsecInstallArgs arg : cidArgs) {
17556            synchronized (mInstallLock) {
17557                arg.doPostDeleteLI(false);
17558           }
17559       }
17560   }
17561
17562    /*
17563     * Unload packages mounted on external media. This involves deleting package
17564     * data from internal structures, sending broadcasts about disabled packages,
17565     * gc'ing to free up references, unmounting all secure containers
17566     * corresponding to packages on external media, and posting a
17567     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17568     * that we always have to post this message if status has been requested no
17569     * matter what.
17570     */
17571    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17572            final boolean reportStatus) {
17573        if (DEBUG_SD_INSTALL)
17574            Log.i(TAG, "unloading media packages");
17575        ArrayList<String> pkgList = new ArrayList<String>();
17576        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17577        final Set<AsecInstallArgs> keys = processCids.keySet();
17578        for (AsecInstallArgs args : keys) {
17579            String pkgName = args.getPackageName();
17580            if (DEBUG_SD_INSTALL)
17581                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17582            // Delete package internally
17583            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17584            synchronized (mInstallLock) {
17585                boolean res = deletePackageLI(pkgName, null, false, null,
17586                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17587                if (res) {
17588                    pkgList.add(pkgName);
17589                } else {
17590                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17591                    failedList.add(args);
17592                }
17593            }
17594        }
17595
17596        // reader
17597        synchronized (mPackages) {
17598            // We didn't update the settings after removing each package;
17599            // write them now for all packages.
17600            mSettings.writeLPr();
17601        }
17602
17603        // We have to absolutely send UPDATED_MEDIA_STATUS only
17604        // after confirming that all the receivers processed the ordered
17605        // broadcast when packages get disabled, force a gc to clean things up.
17606        // and unload all the containers.
17607        if (pkgList.size() > 0) {
17608            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17609                    new IIntentReceiver.Stub() {
17610                public void performReceive(Intent intent, int resultCode, String data,
17611                        Bundle extras, boolean ordered, boolean sticky,
17612                        int sendingUser) throws RemoteException {
17613                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17614                            reportStatus ? 1 : 0, 1, keys);
17615                    mHandler.sendMessage(msg);
17616                }
17617            });
17618        } else {
17619            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17620                    keys);
17621            mHandler.sendMessage(msg);
17622        }
17623    }
17624
17625    private void loadPrivatePackages(final VolumeInfo vol) {
17626        mHandler.post(new Runnable() {
17627            @Override
17628            public void run() {
17629                loadPrivatePackagesInner(vol);
17630            }
17631        });
17632    }
17633
17634    private void loadPrivatePackagesInner(VolumeInfo vol) {
17635        final String volumeUuid = vol.fsUuid;
17636        if (TextUtils.isEmpty(volumeUuid)) {
17637            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17638            return;
17639        }
17640
17641        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17642        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17643
17644        final VersionInfo ver;
17645        final List<PackageSetting> packages;
17646        synchronized (mPackages) {
17647            ver = mSettings.findOrCreateVersion(volumeUuid);
17648            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17649        }
17650
17651        // TODO: introduce a new concept similar to "frozen" to prevent these
17652        // apps from being launched until after data has been fully reconciled
17653        for (PackageSetting ps : packages) {
17654            synchronized (mInstallLock) {
17655                final PackageParser.Package pkg;
17656                try {
17657                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17658                    loaded.add(pkg.applicationInfo);
17659
17660                } catch (PackageManagerException e) {
17661                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17662                }
17663
17664                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17665                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17666                }
17667            }
17668        }
17669
17670        // Reconcile app data for all started/unlocked users
17671        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17672        final UserManager um = mContext.getSystemService(UserManager.class);
17673        for (UserInfo user : um.getUsers()) {
17674            final int flags;
17675            if (um.isUserUnlocked(user.id)) {
17676                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17677            } else if (um.isUserRunning(user.id)) {
17678                flags = StorageManager.FLAG_STORAGE_DE;
17679            } else {
17680                continue;
17681            }
17682
17683            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17684            reconcileAppsData(volumeUuid, user.id, flags);
17685        }
17686
17687        synchronized (mPackages) {
17688            int updateFlags = UPDATE_PERMISSIONS_ALL;
17689            if (ver.sdkVersion != mSdkVersion) {
17690                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17691                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17692                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17693            }
17694            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17695
17696            // Yay, everything is now upgraded
17697            ver.forceCurrent();
17698
17699            mSettings.writeLPr();
17700        }
17701
17702        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
17703        sendResourcesChangedBroadcast(true, false, loaded, null);
17704    }
17705
17706    private void unloadPrivatePackages(final VolumeInfo vol) {
17707        mHandler.post(new Runnable() {
17708            @Override
17709            public void run() {
17710                unloadPrivatePackagesInner(vol);
17711            }
17712        });
17713    }
17714
17715    private void unloadPrivatePackagesInner(VolumeInfo vol) {
17716        final String volumeUuid = vol.fsUuid;
17717        if (TextUtils.isEmpty(volumeUuid)) {
17718            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
17719            return;
17720        }
17721
17722        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
17723        synchronized (mInstallLock) {
17724        synchronized (mPackages) {
17725            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
17726            for (PackageSetting ps : packages) {
17727                if (ps.pkg == null) continue;
17728
17729                final ApplicationInfo info = ps.pkg.applicationInfo;
17730                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
17731                if (deletePackageLI(ps.name, null, false, null,
17732                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
17733                    unloaded.add(info);
17734                } else {
17735                    Slog.w(TAG, "Failed to unload " + ps.codePath);
17736                }
17737            }
17738
17739            mSettings.writeLPr();
17740        }
17741        }
17742
17743        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
17744        sendResourcesChangedBroadcast(false, false, unloaded, null);
17745    }
17746
17747    /**
17748     * Examine all users present on given mounted volume, and destroy data
17749     * belonging to users that are no longer valid, or whose user ID has been
17750     * recycled.
17751     */
17752    private void reconcileUsers(String volumeUuid) {
17753        // TODO: also reconcile DE directories
17754        final File[] files = FileUtils
17755                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
17756        for (File file : files) {
17757            if (!file.isDirectory()) continue;
17758
17759            final int userId;
17760            final UserInfo info;
17761            try {
17762                userId = Integer.parseInt(file.getName());
17763                info = sUserManager.getUserInfo(userId);
17764            } catch (NumberFormatException e) {
17765                Slog.w(TAG, "Invalid user directory " + file);
17766                continue;
17767            }
17768
17769            boolean destroyUser = false;
17770            if (info == null) {
17771                logCriticalInfo(Log.WARN, "Destroying user directory " + file
17772                        + " because no matching user was found");
17773                destroyUser = true;
17774            } else {
17775                try {
17776                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
17777                } catch (IOException e) {
17778                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
17779                            + " because we failed to enforce serial number: " + e);
17780                    destroyUser = true;
17781                }
17782            }
17783
17784            if (destroyUser) {
17785                synchronized (mInstallLock) {
17786                    try {
17787                        mInstaller.removeUserDataDirs(volumeUuid, userId);
17788                    } catch (InstallerException e) {
17789                        Slog.w(TAG, "Failed to clean up user dirs", e);
17790                    }
17791                }
17792            }
17793        }
17794    }
17795
17796    private void assertPackageKnown(String volumeUuid, String packageName)
17797            throws PackageManagerException {
17798        synchronized (mPackages) {
17799            final PackageSetting ps = mSettings.mPackages.get(packageName);
17800            if (ps == null) {
17801                throw new PackageManagerException("Package " + packageName + " is unknown");
17802            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17803                throw new PackageManagerException(
17804                        "Package " + packageName + " found on unknown volume " + volumeUuid
17805                                + "; expected volume " + ps.volumeUuid);
17806            }
17807        }
17808    }
17809
17810    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
17811            throws PackageManagerException {
17812        synchronized (mPackages) {
17813            final PackageSetting ps = mSettings.mPackages.get(packageName);
17814            if (ps == null) {
17815                throw new PackageManagerException("Package " + packageName + " is unknown");
17816            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
17817                throw new PackageManagerException(
17818                        "Package " + packageName + " found on unknown volume " + volumeUuid
17819                                + "; expected volume " + ps.volumeUuid);
17820            } else if (!ps.getInstalled(userId)) {
17821                throw new PackageManagerException(
17822                        "Package " + packageName + " not installed for user " + userId);
17823            }
17824        }
17825    }
17826
17827    /**
17828     * Examine all apps present on given mounted volume, and destroy apps that
17829     * aren't expected, either due to uninstallation or reinstallation on
17830     * another volume.
17831     */
17832    private void reconcileApps(String volumeUuid) {
17833        final File[] files = FileUtils
17834                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
17835        for (File file : files) {
17836            final boolean isPackage = (isApkFile(file) || file.isDirectory())
17837                    && !PackageInstallerService.isStageName(file.getName());
17838            if (!isPackage) {
17839                // Ignore entries which are not packages
17840                continue;
17841            }
17842
17843            try {
17844                final PackageLite pkg = PackageParser.parsePackageLite(file,
17845                        PackageParser.PARSE_MUST_BE_APK);
17846                assertPackageKnown(volumeUuid, pkg.packageName);
17847
17848            } catch (PackageParserException | PackageManagerException e) {
17849                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17850                synchronized (mInstallLock) {
17851                    removeCodePathLI(file);
17852                }
17853            }
17854        }
17855    }
17856
17857    /**
17858     * Reconcile all app data for the given user.
17859     * <p>
17860     * Verifies that directories exist and that ownership and labeling is
17861     * correct for all installed apps on all mounted volumes.
17862     */
17863    void reconcileAppsData(int userId, int flags) {
17864        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17865        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17866            final String volumeUuid = vol.getFsUuid();
17867            reconcileAppsData(volumeUuid, userId, flags);
17868        }
17869    }
17870
17871    /**
17872     * Reconcile all app data on given mounted volume.
17873     * <p>
17874     * Destroys app data that isn't expected, either due to uninstallation or
17875     * reinstallation on another volume.
17876     * <p>
17877     * Verifies that directories exist and that ownership and labeling is
17878     * correct for all installed apps.
17879     */
17880    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
17881        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17882                + Integer.toHexString(flags));
17883
17884        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
17885        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
17886
17887        boolean restoreconNeeded = false;
17888
17889        // First look for stale data that doesn't belong, and check if things
17890        // have changed since we did our last restorecon
17891        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17892            if (!isUserKeyUnlocked(userId)) {
17893                throw new RuntimeException(
17894                        "Yikes, someone asked us to reconcile CE storage while " + userId
17895                                + " was still locked; this would have caused massive data loss!");
17896            }
17897
17898            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17899
17900            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17901            for (File file : files) {
17902                final String packageName = file.getName();
17903                try {
17904                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17905                } catch (PackageManagerException e) {
17906                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17907                    synchronized (mInstallLock) {
17908                        destroyAppDataLI(volumeUuid, packageName, userId,
17909                                StorageManager.FLAG_STORAGE_CE);
17910                    }
17911                }
17912            }
17913        }
17914        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17915            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17916
17917            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17918            for (File file : files) {
17919                final String packageName = file.getName();
17920                try {
17921                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17922                } catch (PackageManagerException e) {
17923                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17924                    synchronized (mInstallLock) {
17925                        destroyAppDataLI(volumeUuid, packageName, userId,
17926                                StorageManager.FLAG_STORAGE_DE);
17927                    }
17928                }
17929            }
17930        }
17931
17932        // Ensure that data directories are ready to roll for all packages
17933        // installed for this volume and user
17934        final List<PackageSetting> packages;
17935        synchronized (mPackages) {
17936            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17937        }
17938        int preparedCount = 0;
17939        for (PackageSetting ps : packages) {
17940            final String packageName = ps.name;
17941            if (ps.pkg == null) {
17942                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17943                // TODO: might be due to legacy ASEC apps; we should circle back
17944                // and reconcile again once they're scanned
17945                continue;
17946            }
17947
17948            if (ps.getInstalled(userId)) {
17949                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17950                preparedCount++;
17951            }
17952        }
17953
17954        if (restoreconNeeded) {
17955            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17956                SELinuxMMAC.setRestoreconDone(ceDir);
17957            }
17958            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17959                SELinuxMMAC.setRestoreconDone(deDir);
17960            }
17961        }
17962
17963        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17964                + " packages; restoreconNeeded was " + restoreconNeeded);
17965    }
17966
17967    /**
17968     * Prepare app data for the given app just after it was installed or
17969     * upgraded. This method carefully only touches users that it's installed
17970     * for, and it forces a restorecon to handle any seinfo changes.
17971     * <p>
17972     * Verifies that directories exist and that ownership and labeling is
17973     * correct for all installed apps. If there is an ownership mismatch, it
17974     * will try recovering system apps by wiping data; third-party app data is
17975     * left intact.
17976     */
17977    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17978        prepareAppDataAfterInstallInternal(pkg);
17979        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17980        for (int i = 0; i < childCount; i++) {
17981            PackageParser.Package childPackage = pkg.childPackages.get(i);
17982            prepareAppDataAfterInstallInternal(childPackage);
17983        }
17984    }
17985
17986    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
17987        final PackageSetting ps;
17988        synchronized (mPackages) {
17989            ps = mSettings.mPackages.get(pkg.packageName);
17990        }
17991
17992        final UserManager um = mContext.getSystemService(UserManager.class);
17993        for (UserInfo user : um.getUsers()) {
17994            final int flags;
17995            if (um.isUserUnlocked(user.id)) {
17996                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17997            } else if (um.isUserRunning(user.id)) {
17998                flags = StorageManager.FLAG_STORAGE_DE;
17999            } else {
18000                continue;
18001            }
18002
18003            if (ps.getInstalled(user.id)) {
18004                // Whenever an app changes, force a restorecon of its data
18005                // TODO: when user data is locked, mark that we're still dirty
18006                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18007            }
18008        }
18009    }
18010
18011    /**
18012     * Prepare app data for the given app.
18013     * <p>
18014     * Verifies that directories exist and that ownership and labeling is
18015     * correct for all installed apps. If there is an ownership mismatch, this
18016     * will try recovering system apps by wiping data; third-party app data is
18017     * left intact.
18018     */
18019    private void prepareAppData(String volumeUuid, int userId, int flags,
18020            PackageParser.Package pkg, boolean restoreconNeeded) {
18021        if (DEBUG_APP_DATA) {
18022            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18023                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18024        }
18025
18026        final String packageName = pkg.packageName;
18027        final ApplicationInfo app = pkg.applicationInfo;
18028        final int appId = UserHandle.getAppId(app.uid);
18029
18030        Preconditions.checkNotNull(app.seinfo);
18031
18032        synchronized (mInstallLock) {
18033            try {
18034                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18035                        appId, app.seinfo, app.targetSdkVersion);
18036            } catch (InstallerException e) {
18037                if (app.isSystemApp()) {
18038                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18039                            + ", but trying to recover: " + e);
18040                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18041                    try {
18042                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18043                                appId, app.seinfo, app.targetSdkVersion);
18044                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18045                    } catch (InstallerException e2) {
18046                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18047                    }
18048                } else {
18049                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18050                }
18051            }
18052
18053            if (restoreconNeeded) {
18054                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18055            }
18056
18057            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18058                // Create a native library symlink only if we have native libraries
18059                // and if the native libraries are 32 bit libraries. We do not provide
18060                // this symlink for 64 bit libraries.
18061                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18062                    final String nativeLibPath = app.nativeLibraryDir;
18063                    try {
18064                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18065                                nativeLibPath, userId);
18066                    } catch (InstallerException e) {
18067                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18068                    }
18069                }
18070            }
18071        }
18072    }
18073
18074    private void unfreezePackage(String packageName) {
18075        synchronized (mPackages) {
18076            final PackageSetting ps = mSettings.mPackages.get(packageName);
18077            if (ps != null) {
18078                ps.frozen = false;
18079            }
18080        }
18081    }
18082
18083    @Override
18084    public int movePackage(final String packageName, final String volumeUuid) {
18085        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18086
18087        final int moveId = mNextMoveId.getAndIncrement();
18088        mHandler.post(new Runnable() {
18089            @Override
18090            public void run() {
18091                try {
18092                    movePackageInternal(packageName, volumeUuid, moveId);
18093                } catch (PackageManagerException e) {
18094                    Slog.w(TAG, "Failed to move " + packageName, e);
18095                    mMoveCallbacks.notifyStatusChanged(moveId,
18096                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18097                }
18098            }
18099        });
18100        return moveId;
18101    }
18102
18103    private void movePackageInternal(final String packageName, final String volumeUuid,
18104            final int moveId) throws PackageManagerException {
18105        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18106        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18107        final PackageManager pm = mContext.getPackageManager();
18108
18109        final boolean currentAsec;
18110        final String currentVolumeUuid;
18111        final File codeFile;
18112        final String installerPackageName;
18113        final String packageAbiOverride;
18114        final int appId;
18115        final String seinfo;
18116        final String label;
18117        final int targetSdkVersion;
18118
18119        // reader
18120        synchronized (mPackages) {
18121            final PackageParser.Package pkg = mPackages.get(packageName);
18122            final PackageSetting ps = mSettings.mPackages.get(packageName);
18123            if (pkg == null || ps == null) {
18124                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18125            }
18126
18127            if (pkg.applicationInfo.isSystemApp()) {
18128                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18129                        "Cannot move system application");
18130            }
18131
18132            if (pkg.applicationInfo.isExternalAsec()) {
18133                currentAsec = true;
18134                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18135            } else if (pkg.applicationInfo.isForwardLocked()) {
18136                currentAsec = true;
18137                currentVolumeUuid = "forward_locked";
18138            } else {
18139                currentAsec = false;
18140                currentVolumeUuid = ps.volumeUuid;
18141
18142                final File probe = new File(pkg.codePath);
18143                final File probeOat = new File(probe, "oat");
18144                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18145                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18146                            "Move only supported for modern cluster style installs");
18147                }
18148            }
18149
18150            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18151                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18152                        "Package already moved to " + volumeUuid);
18153            }
18154
18155            if (ps.frozen) {
18156                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18157                        "Failed to move already frozen package");
18158            }
18159            ps.frozen = true;
18160
18161            codeFile = new File(pkg.codePath);
18162            installerPackageName = ps.installerPackageName;
18163            packageAbiOverride = ps.cpuAbiOverrideString;
18164            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18165            seinfo = pkg.applicationInfo.seinfo;
18166            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18167            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18168        }
18169
18170        // Now that we're guarded by frozen state, kill app during move
18171        final long token = Binder.clearCallingIdentity();
18172        try {
18173            killApplication(packageName, appId, "move pkg");
18174        } finally {
18175            Binder.restoreCallingIdentity(token);
18176        }
18177
18178        final Bundle extras = new Bundle();
18179        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18180        extras.putString(Intent.EXTRA_TITLE, label);
18181        mMoveCallbacks.notifyCreated(moveId, extras);
18182
18183        int installFlags;
18184        final boolean moveCompleteApp;
18185        final File measurePath;
18186
18187        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18188            installFlags = INSTALL_INTERNAL;
18189            moveCompleteApp = !currentAsec;
18190            measurePath = Environment.getDataAppDirectory(volumeUuid);
18191        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18192            installFlags = INSTALL_EXTERNAL;
18193            moveCompleteApp = false;
18194            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18195        } else {
18196            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18197            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18198                    || !volume.isMountedWritable()) {
18199                unfreezePackage(packageName);
18200                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18201                        "Move location not mounted private volume");
18202            }
18203
18204            Preconditions.checkState(!currentAsec);
18205
18206            installFlags = INSTALL_INTERNAL;
18207            moveCompleteApp = true;
18208            measurePath = Environment.getDataAppDirectory(volumeUuid);
18209        }
18210
18211        final PackageStats stats = new PackageStats(null, -1);
18212        synchronized (mInstaller) {
18213            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18214                unfreezePackage(packageName);
18215                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18216                        "Failed to measure package size");
18217            }
18218        }
18219
18220        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18221                + stats.dataSize);
18222
18223        final long startFreeBytes = measurePath.getFreeSpace();
18224        final long sizeBytes;
18225        if (moveCompleteApp) {
18226            sizeBytes = stats.codeSize + stats.dataSize;
18227        } else {
18228            sizeBytes = stats.codeSize;
18229        }
18230
18231        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18232            unfreezePackage(packageName);
18233            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18234                    "Not enough free space to move");
18235        }
18236
18237        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18238
18239        final CountDownLatch installedLatch = new CountDownLatch(1);
18240        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18241            @Override
18242            public void onUserActionRequired(Intent intent) throws RemoteException {
18243                throw new IllegalStateException();
18244            }
18245
18246            @Override
18247            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18248                    Bundle extras) throws RemoteException {
18249                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18250                        + PackageManager.installStatusToString(returnCode, msg));
18251
18252                installedLatch.countDown();
18253
18254                // Regardless of success or failure of the move operation,
18255                // always unfreeze the package
18256                unfreezePackage(packageName);
18257
18258                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18259                switch (status) {
18260                    case PackageInstaller.STATUS_SUCCESS:
18261                        mMoveCallbacks.notifyStatusChanged(moveId,
18262                                PackageManager.MOVE_SUCCEEDED);
18263                        break;
18264                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18265                        mMoveCallbacks.notifyStatusChanged(moveId,
18266                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18267                        break;
18268                    default:
18269                        mMoveCallbacks.notifyStatusChanged(moveId,
18270                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18271                        break;
18272                }
18273            }
18274        };
18275
18276        final MoveInfo move;
18277        if (moveCompleteApp) {
18278            // Kick off a thread to report progress estimates
18279            new Thread() {
18280                @Override
18281                public void run() {
18282                    while (true) {
18283                        try {
18284                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18285                                break;
18286                            }
18287                        } catch (InterruptedException ignored) {
18288                        }
18289
18290                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18291                        final int progress = 10 + (int) MathUtils.constrain(
18292                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18293                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18294                    }
18295                }
18296            }.start();
18297
18298            final String dataAppName = codeFile.getName();
18299            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18300                    dataAppName, appId, seinfo, targetSdkVersion);
18301        } else {
18302            move = null;
18303        }
18304
18305        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18306
18307        final Message msg = mHandler.obtainMessage(INIT_COPY);
18308        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18309        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18310                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
18311        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18312        msg.obj = params;
18313
18314        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18315                System.identityHashCode(msg.obj));
18316        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18317                System.identityHashCode(msg.obj));
18318
18319        mHandler.sendMessage(msg);
18320    }
18321
18322    @Override
18323    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18325
18326        final int realMoveId = mNextMoveId.getAndIncrement();
18327        final Bundle extras = new Bundle();
18328        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18329        mMoveCallbacks.notifyCreated(realMoveId, extras);
18330
18331        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18332            @Override
18333            public void onCreated(int moveId, Bundle extras) {
18334                // Ignored
18335            }
18336
18337            @Override
18338            public void onStatusChanged(int moveId, int status, long estMillis) {
18339                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18340            }
18341        };
18342
18343        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18344        storage.setPrimaryStorageUuid(volumeUuid, callback);
18345        return realMoveId;
18346    }
18347
18348    @Override
18349    public int getMoveStatus(int moveId) {
18350        mContext.enforceCallingOrSelfPermission(
18351                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18352        return mMoveCallbacks.mLastStatus.get(moveId);
18353    }
18354
18355    @Override
18356    public void registerMoveCallback(IPackageMoveObserver callback) {
18357        mContext.enforceCallingOrSelfPermission(
18358                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18359        mMoveCallbacks.register(callback);
18360    }
18361
18362    @Override
18363    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18364        mContext.enforceCallingOrSelfPermission(
18365                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18366        mMoveCallbacks.unregister(callback);
18367    }
18368
18369    @Override
18370    public boolean setInstallLocation(int loc) {
18371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18372                null);
18373        if (getInstallLocation() == loc) {
18374            return true;
18375        }
18376        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18377                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18378            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18379                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18380            return true;
18381        }
18382        return false;
18383   }
18384
18385    @Override
18386    public int getInstallLocation() {
18387        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18388                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18389                PackageHelper.APP_INSTALL_AUTO);
18390    }
18391
18392    /** Called by UserManagerService */
18393    void cleanUpUser(UserManagerService userManager, int userHandle) {
18394        synchronized (mPackages) {
18395            mDirtyUsers.remove(userHandle);
18396            mUserNeedsBadging.delete(userHandle);
18397            mSettings.removeUserLPw(userHandle);
18398            mPendingBroadcasts.remove(userHandle);
18399            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18400        }
18401        synchronized (mInstallLock) {
18402            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18403            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18404                final String volumeUuid = vol.getFsUuid();
18405                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18406                try {
18407                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18408                } catch (InstallerException e) {
18409                    Slog.w(TAG, "Failed to remove user data", e);
18410                }
18411            }
18412            synchronized (mPackages) {
18413                removeUnusedPackagesLILPw(userManager, userHandle);
18414            }
18415        }
18416    }
18417
18418    /**
18419     * We're removing userHandle and would like to remove any downloaded packages
18420     * that are no longer in use by any other user.
18421     * @param userHandle the user being removed
18422     */
18423    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18424        final boolean DEBUG_CLEAN_APKS = false;
18425        int [] users = userManager.getUserIds();
18426        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18427        while (psit.hasNext()) {
18428            PackageSetting ps = psit.next();
18429            if (ps.pkg == null) {
18430                continue;
18431            }
18432            final String packageName = ps.pkg.packageName;
18433            // Skip over if system app
18434            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18435                continue;
18436            }
18437            if (DEBUG_CLEAN_APKS) {
18438                Slog.i(TAG, "Checking package " + packageName);
18439            }
18440            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18441            if (keep) {
18442                if (DEBUG_CLEAN_APKS) {
18443                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18444                }
18445            } else {
18446                for (int i = 0; i < users.length; i++) {
18447                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18448                        keep = true;
18449                        if (DEBUG_CLEAN_APKS) {
18450                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18451                                    + users[i]);
18452                        }
18453                        break;
18454                    }
18455                }
18456            }
18457            if (!keep) {
18458                if (DEBUG_CLEAN_APKS) {
18459                    Slog.i(TAG, "  Removing package " + packageName);
18460                }
18461                mHandler.post(new Runnable() {
18462                    public void run() {
18463                        deletePackageX(packageName, userHandle, 0);
18464                    } //end run
18465                });
18466            }
18467        }
18468    }
18469
18470    /** Called by UserManagerService */
18471    void createNewUser(int userHandle) {
18472        synchronized (mInstallLock) {
18473            try {
18474                mInstaller.createUserConfig(userHandle);
18475            } catch (InstallerException e) {
18476                Slog.w(TAG, "Failed to create user config", e);
18477            }
18478            mSettings.createNewUserLI(this, mInstaller, userHandle);
18479        }
18480        synchronized (mPackages) {
18481            applyFactoryDefaultBrowserLPw(userHandle);
18482            primeDomainVerificationsLPw(userHandle);
18483        }
18484    }
18485
18486    void newUserCreated(final int userHandle) {
18487        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18488        // If permission review for legacy apps is required, we represent
18489        // dagerous permissions for such apps as always granted runtime
18490        // permissions to keep per user flag state whether review is needed.
18491        // Hence, if a new user is added we have to propagate dangerous
18492        // permission grants for these legacy apps.
18493        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18494            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18495                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18496        }
18497    }
18498
18499    @Override
18500    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18501        mContext.enforceCallingOrSelfPermission(
18502                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18503                "Only package verification agents can read the verifier device identity");
18504
18505        synchronized (mPackages) {
18506            return mSettings.getVerifierDeviceIdentityLPw();
18507        }
18508    }
18509
18510    @Override
18511    public void setPermissionEnforced(String permission, boolean enforced) {
18512        // TODO: Now that we no longer change GID for storage, this should to away.
18513        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18514                "setPermissionEnforced");
18515        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18516            synchronized (mPackages) {
18517                if (mSettings.mReadExternalStorageEnforced == null
18518                        || mSettings.mReadExternalStorageEnforced != enforced) {
18519                    mSettings.mReadExternalStorageEnforced = enforced;
18520                    mSettings.writeLPr();
18521                }
18522            }
18523            // kill any non-foreground processes so we restart them and
18524            // grant/revoke the GID.
18525            final IActivityManager am = ActivityManagerNative.getDefault();
18526            if (am != null) {
18527                final long token = Binder.clearCallingIdentity();
18528                try {
18529                    am.killProcessesBelowForeground("setPermissionEnforcement");
18530                } catch (RemoteException e) {
18531                } finally {
18532                    Binder.restoreCallingIdentity(token);
18533                }
18534            }
18535        } else {
18536            throw new IllegalArgumentException("No selective enforcement for " + permission);
18537        }
18538    }
18539
18540    @Override
18541    @Deprecated
18542    public boolean isPermissionEnforced(String permission) {
18543        return true;
18544    }
18545
18546    @Override
18547    public boolean isStorageLow() {
18548        final long token = Binder.clearCallingIdentity();
18549        try {
18550            final DeviceStorageMonitorInternal
18551                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18552            if (dsm != null) {
18553                return dsm.isMemoryLow();
18554            } else {
18555                return false;
18556            }
18557        } finally {
18558            Binder.restoreCallingIdentity(token);
18559        }
18560    }
18561
18562    @Override
18563    public IPackageInstaller getPackageInstaller() {
18564        return mInstallerService;
18565    }
18566
18567    private boolean userNeedsBadging(int userId) {
18568        int index = mUserNeedsBadging.indexOfKey(userId);
18569        if (index < 0) {
18570            final UserInfo userInfo;
18571            final long token = Binder.clearCallingIdentity();
18572            try {
18573                userInfo = sUserManager.getUserInfo(userId);
18574            } finally {
18575                Binder.restoreCallingIdentity(token);
18576            }
18577            final boolean b;
18578            if (userInfo != null && userInfo.isManagedProfile()) {
18579                b = true;
18580            } else {
18581                b = false;
18582            }
18583            mUserNeedsBadging.put(userId, b);
18584            return b;
18585        }
18586        return mUserNeedsBadging.valueAt(index);
18587    }
18588
18589    @Override
18590    public KeySet getKeySetByAlias(String packageName, String alias) {
18591        if (packageName == null || alias == null) {
18592            return null;
18593        }
18594        synchronized(mPackages) {
18595            final PackageParser.Package pkg = mPackages.get(packageName);
18596            if (pkg == null) {
18597                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18598                throw new IllegalArgumentException("Unknown package: " + packageName);
18599            }
18600            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18601            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18602        }
18603    }
18604
18605    @Override
18606    public KeySet getSigningKeySet(String packageName) {
18607        if (packageName == null) {
18608            return null;
18609        }
18610        synchronized(mPackages) {
18611            final PackageParser.Package pkg = mPackages.get(packageName);
18612            if (pkg == null) {
18613                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18614                throw new IllegalArgumentException("Unknown package: " + packageName);
18615            }
18616            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18617                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18618                throw new SecurityException("May not access signing KeySet of other apps.");
18619            }
18620            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18621            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18622        }
18623    }
18624
18625    @Override
18626    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18627        if (packageName == null || ks == null) {
18628            return false;
18629        }
18630        synchronized(mPackages) {
18631            final PackageParser.Package pkg = mPackages.get(packageName);
18632            if (pkg == null) {
18633                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18634                throw new IllegalArgumentException("Unknown package: " + packageName);
18635            }
18636            IBinder ksh = ks.getToken();
18637            if (ksh instanceof KeySetHandle) {
18638                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18639                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18640            }
18641            return false;
18642        }
18643    }
18644
18645    @Override
18646    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18647        if (packageName == null || ks == null) {
18648            return false;
18649        }
18650        synchronized(mPackages) {
18651            final PackageParser.Package pkg = mPackages.get(packageName);
18652            if (pkg == null) {
18653                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18654                throw new IllegalArgumentException("Unknown package: " + packageName);
18655            }
18656            IBinder ksh = ks.getToken();
18657            if (ksh instanceof KeySetHandle) {
18658                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18659                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
18660            }
18661            return false;
18662        }
18663    }
18664
18665    private void deletePackageIfUnusedLPr(final String packageName) {
18666        PackageSetting ps = mSettings.mPackages.get(packageName);
18667        if (ps == null) {
18668            return;
18669        }
18670        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
18671            // TODO Implement atomic delete if package is unused
18672            // It is currently possible that the package will be deleted even if it is installed
18673            // after this method returns.
18674            mHandler.post(new Runnable() {
18675                public void run() {
18676                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
18677                }
18678            });
18679        }
18680    }
18681
18682    /**
18683     * Check and throw if the given before/after packages would be considered a
18684     * downgrade.
18685     */
18686    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
18687            throws PackageManagerException {
18688        if (after.versionCode < before.mVersionCode) {
18689            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18690                    "Update version code " + after.versionCode + " is older than current "
18691                    + before.mVersionCode);
18692        } else if (after.versionCode == before.mVersionCode) {
18693            if (after.baseRevisionCode < before.baseRevisionCode) {
18694                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18695                        "Update base revision code " + after.baseRevisionCode
18696                        + " is older than current " + before.baseRevisionCode);
18697            }
18698
18699            if (!ArrayUtils.isEmpty(after.splitNames)) {
18700                for (int i = 0; i < after.splitNames.length; i++) {
18701                    final String splitName = after.splitNames[i];
18702                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
18703                    if (j != -1) {
18704                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
18705                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
18706                                    "Update split " + splitName + " revision code "
18707                                    + after.splitRevisionCodes[i] + " is older than current "
18708                                    + before.splitRevisionCodes[j]);
18709                        }
18710                    }
18711                }
18712            }
18713        }
18714    }
18715
18716    private static class MoveCallbacks extends Handler {
18717        private static final int MSG_CREATED = 1;
18718        private static final int MSG_STATUS_CHANGED = 2;
18719
18720        private final RemoteCallbackList<IPackageMoveObserver>
18721                mCallbacks = new RemoteCallbackList<>();
18722
18723        private final SparseIntArray mLastStatus = new SparseIntArray();
18724
18725        public MoveCallbacks(Looper looper) {
18726            super(looper);
18727        }
18728
18729        public void register(IPackageMoveObserver callback) {
18730            mCallbacks.register(callback);
18731        }
18732
18733        public void unregister(IPackageMoveObserver callback) {
18734            mCallbacks.unregister(callback);
18735        }
18736
18737        @Override
18738        public void handleMessage(Message msg) {
18739            final SomeArgs args = (SomeArgs) msg.obj;
18740            final int n = mCallbacks.beginBroadcast();
18741            for (int i = 0; i < n; i++) {
18742                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
18743                try {
18744                    invokeCallback(callback, msg.what, args);
18745                } catch (RemoteException ignored) {
18746                }
18747            }
18748            mCallbacks.finishBroadcast();
18749            args.recycle();
18750        }
18751
18752        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
18753                throws RemoteException {
18754            switch (what) {
18755                case MSG_CREATED: {
18756                    callback.onCreated(args.argi1, (Bundle) args.arg2);
18757                    break;
18758                }
18759                case MSG_STATUS_CHANGED: {
18760                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
18761                    break;
18762                }
18763            }
18764        }
18765
18766        private void notifyCreated(int moveId, Bundle extras) {
18767            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
18768
18769            final SomeArgs args = SomeArgs.obtain();
18770            args.argi1 = moveId;
18771            args.arg2 = extras;
18772            obtainMessage(MSG_CREATED, args).sendToTarget();
18773        }
18774
18775        private void notifyStatusChanged(int moveId, int status) {
18776            notifyStatusChanged(moveId, status, -1);
18777        }
18778
18779        private void notifyStatusChanged(int moveId, int status, long estMillis) {
18780            Slog.v(TAG, "Move " + moveId + " status " + status);
18781
18782            final SomeArgs args = SomeArgs.obtain();
18783            args.argi1 = moveId;
18784            args.argi2 = status;
18785            args.arg3 = estMillis;
18786            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
18787
18788            synchronized (mLastStatus) {
18789                mLastStatus.put(moveId, status);
18790            }
18791        }
18792    }
18793
18794    private final static class OnPermissionChangeListeners extends Handler {
18795        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
18796
18797        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
18798                new RemoteCallbackList<>();
18799
18800        public OnPermissionChangeListeners(Looper looper) {
18801            super(looper);
18802        }
18803
18804        @Override
18805        public void handleMessage(Message msg) {
18806            switch (msg.what) {
18807                case MSG_ON_PERMISSIONS_CHANGED: {
18808                    final int uid = msg.arg1;
18809                    handleOnPermissionsChanged(uid);
18810                } break;
18811            }
18812        }
18813
18814        public void addListenerLocked(IOnPermissionsChangeListener listener) {
18815            mPermissionListeners.register(listener);
18816
18817        }
18818
18819        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
18820            mPermissionListeners.unregister(listener);
18821        }
18822
18823        public void onPermissionsChanged(int uid) {
18824            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
18825                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
18826            }
18827        }
18828
18829        private void handleOnPermissionsChanged(int uid) {
18830            final int count = mPermissionListeners.beginBroadcast();
18831            try {
18832                for (int i = 0; i < count; i++) {
18833                    IOnPermissionsChangeListener callback = mPermissionListeners
18834                            .getBroadcastItem(i);
18835                    try {
18836                        callback.onPermissionsChanged(uid);
18837                    } catch (RemoteException e) {
18838                        Log.e(TAG, "Permission listener is dead", e);
18839                    }
18840                }
18841            } finally {
18842                mPermissionListeners.finishBroadcast();
18843            }
18844        }
18845    }
18846
18847    private class PackageManagerInternalImpl extends PackageManagerInternal {
18848        @Override
18849        public void setLocationPackagesProvider(PackagesProvider provider) {
18850            synchronized (mPackages) {
18851                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
18852            }
18853        }
18854
18855        @Override
18856        public void setImePackagesProvider(PackagesProvider provider) {
18857            synchronized (mPackages) {
18858                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
18859            }
18860        }
18861
18862        @Override
18863        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
18864            synchronized (mPackages) {
18865                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
18866            }
18867        }
18868
18869        @Override
18870        public void setSmsAppPackagesProvider(PackagesProvider provider) {
18871            synchronized (mPackages) {
18872                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
18873            }
18874        }
18875
18876        @Override
18877        public void setDialerAppPackagesProvider(PackagesProvider provider) {
18878            synchronized (mPackages) {
18879                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
18880            }
18881        }
18882
18883        @Override
18884        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18885            synchronized (mPackages) {
18886                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18887            }
18888        }
18889
18890        @Override
18891        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18892            synchronized (mPackages) {
18893                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18894            }
18895        }
18896
18897        @Override
18898        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18899            synchronized (mPackages) {
18900                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18901                        packageName, userId);
18902            }
18903        }
18904
18905        @Override
18906        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18907            synchronized (mPackages) {
18908                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18909                        packageName, userId);
18910            }
18911        }
18912
18913        @Override
18914        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18915            synchronized (mPackages) {
18916                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18917                        packageName, userId);
18918            }
18919        }
18920
18921        @Override
18922        public void setKeepUninstalledPackages(final List<String> packageList) {
18923            Preconditions.checkNotNull(packageList);
18924            List<String> removedFromList = null;
18925            synchronized (mPackages) {
18926                if (mKeepUninstalledPackages != null) {
18927                    final int packagesCount = mKeepUninstalledPackages.size();
18928                    for (int i = 0; i < packagesCount; i++) {
18929                        String oldPackage = mKeepUninstalledPackages.get(i);
18930                        if (packageList != null && packageList.contains(oldPackage)) {
18931                            continue;
18932                        }
18933                        if (removedFromList == null) {
18934                            removedFromList = new ArrayList<>();
18935                        }
18936                        removedFromList.add(oldPackage);
18937                    }
18938                }
18939                mKeepUninstalledPackages = new ArrayList<>(packageList);
18940                if (removedFromList != null) {
18941                    final int removedCount = removedFromList.size();
18942                    for (int i = 0; i < removedCount; i++) {
18943                        deletePackageIfUnusedLPr(removedFromList.get(i));
18944                    }
18945                }
18946            }
18947        }
18948
18949        @Override
18950        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18951            synchronized (mPackages) {
18952                // If we do not support permission review, done.
18953                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18954                    return false;
18955                }
18956
18957                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18958                if (packageSetting == null) {
18959                    return false;
18960                }
18961
18962                // Permission review applies only to apps not supporting the new permission model.
18963                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18964                    return false;
18965                }
18966
18967                // Legacy apps have the permission and get user consent on launch.
18968                PermissionsState permissionsState = packageSetting.getPermissionsState();
18969                return permissionsState.isPermissionReviewRequired(userId);
18970            }
18971        }
18972    }
18973
18974    @Override
18975    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18976        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18977        synchronized (mPackages) {
18978            final long identity = Binder.clearCallingIdentity();
18979            try {
18980                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18981                        packageNames, userId);
18982            } finally {
18983                Binder.restoreCallingIdentity(identity);
18984            }
18985        }
18986    }
18987
18988    private static void enforceSystemOrPhoneCaller(String tag) {
18989        int callingUid = Binder.getCallingUid();
18990        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18991            throw new SecurityException(
18992                    "Cannot call " + tag + " from UID " + callingUid);
18993        }
18994    }
18995
18996    boolean isHistoricalPackageUsageAvailable() {
18997        return mPackageUsage.isHistoricalPackageUsageAvailable();
18998    }
18999}
19000